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
5d799771643143867cef60386244dfa863ff92df
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/playground/parser/test2.lean
dfcff5987b06151de83b29a3f9145ce0f7f294d3
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,756
lean
import parser abbrev Parser (α : Type) := Lean.Parser.ParserM Unit Unit Unit α open Lean.Parser def check {α} [BEq α] (p : Parser α) (s : String) (e : α) : IO Unit := match p.run () () s with | Lean.Parser.Result.ok v i _ _ := do IO.println ("Ok at " ++ toString i), unless (v == e) (throw "unexpected result") | Result.error msg _ _ _ := throw msg def checkFailure {α} (p : Parser α) (s : String) : IO Unit := match p.run () () s with | Lean.Parser.Result.ok _ i _ _ := throw "Worked" | Result.error msg i _ _ := IO.println ("failed as expected at " ++ toString i ++ ", error: " ++ toString msg) def str' (s : String) : Parser String := str s *> pure s def main : IO Unit := do check (ch 'a') "a" 'a', check any "a" 'a', check any "b" 'b', check (str' "foo" <|> str' "bla" <|> str' "boo") "bla" "bla", check (try (str' "foo" *> str' "foo") <|> str' "foo2" <|> str' "boo") "foo2" "foo2", checkFailure ((str' "foo" *> str' "abc") <|> str' "foo2" <|> str' "boo") "foo2", check (str' "foofoo" <|> str' "foo2" <|> str' "boo") "foo2" "foo2", check (leanWhitespace *> str' "hello") " \n-- comment\nhello" "hello", check (takeUntil (== '\n') *> ch '\n' *> str' "test") "\ntest" "test", check (takeUntil (== 't') *> str' "test") "test" "test", check (takeUntil (== '\n') *> ch '\n' *> str' "test") "abc\ntest" "test", check (try (ch 'a' *> ch 'b') <|> (ch 'a' *> ch 'c')) "ac" 'c', checkFailure ((ch 'a' *> ch 'b') <|> (ch 'a' *> ch 'c')) "ac", check (lookahead (ch 'a')) "abc" 'a', check (lookahead (ch 'a') *> str' "abc") "abc" "abc", check strLit "\"abc\\nd\"" "abc\nd", checkFailure strLit "abc\\nd\"", checkFailure strLit "\"abc", checkFailure strLit "\"abc\\ab̈\""
a8126383ac2749177ff2f9b583b6576a6a2e1808
cc62cd292c1acc80a10b1c645915b70d2cdee661
/src/category_theory/functor/functorial.lean
504855a83c4085452daa6a8096261715d8182874
[]
no_license
RitaAhmadi/lean-category-theory
4afb881c4b387ee2c8ce706c454fbf9db8897a29
a27b4ae5eac978e9188d2e867c3d11d9a5b87a9e
refs/heads/master
1,651,786,183,402
1,565,604,314,000
1,565,604,314,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
921
lean
-- Copyright (c) 2018 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison import category_theory.functor import category_theory.tactics.obviously namespace category_theory universes u₁ u₂ variable {C : Type (u₁+1)} variable [large_category C] variable {D : Type (u₂+1)} variable [large_category D] -- TODO this is WIP class functorial (f : C → D) := (map : Π {X Y : C}, (X ⟶ Y) → ((f X) ⟶ (f Y))) (map_id' : ∀ (X : C), map (𝟙 X) = 𝟙 (f X) . obviously) (map_comp' : ∀ {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z), map (f ≫ g) = (map f) ≫ (map g) . obviously) restate_axiom functorial.map_id' restate_axiom functorial.map_comp' attribute [simp,search] functorial.map_comp functorial.map_id -- instance (F : C ⥤ D) : functorial (F.obj) := -- { map := F.map' } -- TODO notations? end category_theory
a1a4cc5e111aeea405ccc282aede693804c4c06a
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/library/standard/data/nat/basic.lean
b0d9d0770eb80a5042f8ffc730f574fa0bcb99fe
[ "Apache-2.0" ]
permissive
codyroux/lean
7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3
0cca265db19f7296531e339192e9b9bae4a31f8b
refs/heads/master
1,610,909,964,159
1,407,084,399,000
1,416,857,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,900
lean
---------------------------------------------------------------------------------------------------- --- Copyright (c) 2014 Floris van Doorn. All rights reserved. --- Released under Apache 2.0 license as described in the file LICENSE. --- Author: Floris van Doorn ---------------------------------------------------------------------------------------------------- import logic data.num tools.tactic struc.binary using num tactic binary eq_proofs using decidable (hiding induction_on rec_on) -- TODO: this should go in tools, I think namespace helper_tactics definition apply_refl := apply @refl tactic_hint apply_refl end using helper_tactics -- data.nat.basic -- ============== -- -- Basic operations on the natural numbers. -- Definition of the type -- ---------------------- namespace nat inductive nat : Type := | zero : nat | succ : nat → nat notation `ℕ` : max := nat -- Coercion from num -- ----------------- abbreviation plus (x y : ℕ) : ℕ := nat_rec x (λ n r, succ r) y definition to_nat [coercion] [inline] (n : num) : ℕ := num_rec zero (λ n, pos_num_rec (succ zero) (λ n r, plus r (plus r (succ zero))) (λ n r, plus r r) n) n theorem nat_rec_zero {P : ℕ → Type} (x : P 0) (f : ∀m, P m → P (succ m)) : nat_rec x f 0 = x theorem nat_rec_succ {P : ℕ → Type} (x : P 0) (f : ∀m, P m → P (succ m)) (n : ℕ) : nat_rec x f (succ n) = f n (nat_rec x f n) theorem induction_on {P : ℕ → Prop} (a : ℕ) (H1 : P 0) (H2 : ∀ (n : ℕ) (IH : P n), P (succ n)) : P a := nat_rec H1 H2 a definition rec_on {P : ℕ → Type} (n : ℕ) (H1 : P 0) (H2 : ∀m, P m → P (succ m)) : P n := nat_rec H1 H2 n -- Successor and predecessor -- ------------------------- theorem succ_ne_zero (n : ℕ) : succ n ≠ 0 := assume H : succ n = 0, have H2 : true = false, from let f [inline] := (nat_rec false (fun a b, true)) in calc true = f (succ n) : _ ... = f 0 : {H} ... = false : _, absurd H2 true_ne_false -- add_rewrite succ_ne_zero definition pred (n : ℕ) := nat_rec 0 (fun m x, m) n theorem pred_zero : pred 0 = 0 theorem pred_succ (n : ℕ) : pred (succ n) = n opaque_hint (hiding pred) theorem zero_or_succ_pred (n : ℕ) : n = 0 ∨ n = succ (pred n) := induction_on n (or_inl (refl 0)) (take m IH, or_inr (show succ m = succ (pred (succ m)), from congr2 succ (pred_succ m⁻¹))) theorem zero_or_exists_succ (n : ℕ) : n = 0 ∨ ∃k, n = succ k := or_imp_or (zero_or_succ_pred n) (assume H, H) (assume H : n = succ (pred n), exists_intro (pred n) H) theorem case {P : ℕ → Prop} (n : ℕ) (H1: P 0) (H2 : ∀m, P (succ m)) : P n := induction_on n H1 (take m IH, H2 m) theorem discriminate {B : Prop} {n : ℕ} (H1: n = 0 → B) (H2 : ∀m, n = succ m → B) : B := or_elim (zero_or_succ_pred n) (take H3 : n = 0, H1 H3) (take H3 : n = succ (pred n), H2 (pred n) H3) theorem succ_inj {n m : ℕ} (H : succ n = succ m) : n = m := calc n = pred (succ n) : pred_succ n⁻¹ ... = pred (succ m) : {H} ... = m : pred_succ m theorem succ_ne_self (n : ℕ) : succ n ≠ n := induction_on n (take H : 1 = 0, have ne : 1 ≠ 0, from succ_ne_zero 0, absurd H ne) (take k IH H, IH (succ_inj H)) theorem decidable_eq [instance] (n m : ℕ) : decidable (n = m) := have general : ∀n, decidable (n = m), from rec_on m (take n, rec_on n (inl (refl 0)) (λ m iH, inr (succ_ne_zero m))) (λ (m' : ℕ) (iH1 : ∀n, decidable (n = m')), take n, rec_on n (inr (ne_symm (succ_ne_zero m'))) (λ (n' : ℕ) (iH2 : decidable (n' = succ m')), have d1 : decidable (n' = m'), from iH1 n', decidable.rec_on d1 (assume Heq : n' = m', inl (congr2 succ Heq)) (assume Hne : n' ≠ m', have H1 : succ n' ≠ succ m', from assume Heq, absurd (succ_inj Heq) Hne, inr H1))), general n theorem two_step_induction_on {P : ℕ → Prop} (a : ℕ) (H1 : P 0) (H2 : P 1) (H3 : ∀ (n : ℕ) (IH1 : P n) (IH2 : P (succ n)), P (succ (succ n))) : P a := have stronger : P a ∧ P (succ a), from induction_on a (and_intro H1 H2) (take k IH, have IH1 : P k, from and_elim_left IH, have IH2 : P (succ k), from and_elim_right IH, and_intro IH2 (H3 k IH1 IH2)), and_elim_left stronger theorem sub_induction {P : ℕ → ℕ → Prop} (n m : ℕ) (H1 : ∀m, P 0 m) (H2 : ∀n, P (succ n) 0) (H3 : ∀n m, P n m → P (succ n) (succ m)) : P n m := have general : ∀m, P n m, from induction_on n (take m : ℕ, H1 m) (take k : ℕ, assume IH : ∀m, P k m, take m : ℕ, discriminate (assume Hm : m = 0, Hm⁻¹ ▸ (H2 k)) (take l : ℕ, assume Hm : m = succ l, Hm⁻¹ ▸ (H3 k l (IH l)))), general m -- Addition -- -------- definition add (x y : ℕ) : ℕ := plus x y infixl `+` : 65 := add theorem add_zero_right (n : ℕ) : n + 0 = n theorem add_succ_right (n m : ℕ) : n + succ m = succ (n + m) opaque_hint (hiding add) theorem add_zero_left (n : ℕ) : 0 + n = n := induction_on n (add_zero_right 0) (take m IH, show 0 + succ m = succ m, from calc 0 + succ m = succ (0 + m) : add_succ_right _ _ ... = succ m : {IH}) theorem add_succ_left (n m : ℕ) : (succ n) + m = succ (n + m) := induction_on m (calc succ n + 0 = succ n : add_zero_right (succ n) ... = succ (n + 0) : {symm (add_zero_right n)}) (take k IH, calc succ n + succ k = succ (succ n + k) : add_succ_right _ _ ... = succ (succ (n + k)) : {IH} ... = succ (n + succ k) : {symm (add_succ_right _ _)}) theorem add_comm (n m : ℕ) : n + m = m + n := induction_on m (trans (add_zero_right _) (symm (add_zero_left _))) (take k IH, calc n + succ k = succ (n+k) : add_succ_right _ _ ... = succ (k + n) : {IH} ... = succ k + n : symm (add_succ_left _ _)) theorem add_move_succ (n m : ℕ) : succ n + m = n + succ m := calc succ n + m = succ (n + m) : add_succ_left n m ... = n +succ m : symm (add_succ_right n m) theorem add_comm_succ (n m : ℕ) : n + succ m = m + succ n := calc n + succ m = succ n + m : symm (add_move_succ n m) ... = m + succ n : add_comm (succ n) m theorem add_assoc (n m k : ℕ) : (n + m) + k = n + (m + k) := induction_on k (calc (n + m) + 0 = n + m : add_zero_right _ ... = n + (m + 0) : {symm (add_zero_right m)}) (take l IH, calc (n + m) + succ l = succ ((n + m) + l) : add_succ_right _ _ ... = succ (n + (m + l)) : {IH} ... = n + succ (m + l) : symm (add_succ_right _ _) ... = n + (m + succ l) : {symm (add_succ_right _ _)}) theorem add_left_comm (n m k : ℕ) : n + (m + k) = m + (n + k) := left_comm add_comm add_assoc n m k theorem add_right_comm (n m k : ℕ) : n + m + k = n + k + m := right_comm add_comm add_assoc n m k -- add_rewrite add_zero_left add_zero_right -- add_rewrite add_succ_left add_succ_right -- add_rewrite add_comm add_assoc add_left_comm -- ### cancelation theorem add_cancel_left {n m k : ℕ} : n + m = n + k → m = k := induction_on n (take H : 0 + m = 0 + k, calc m = 0 + m : symm (add_zero_left m) ... = 0 + k : H ... = k : add_zero_left k) (take (n : ℕ) (IH : n + m = n + k → m = k) (H : succ n + m = succ n + k), have H2 : succ (n + m) = succ (n + k), from calc succ (n + m) = succ n + m : symm (add_succ_left n m) ... = succ n + k : H ... = succ (n + k) : add_succ_left n k, have H3 : n + m = n + k, from succ_inj H2, IH H3) theorem add_cancel_right {n m k : ℕ} (H : n + m = k + m) : n = k := have H2 : m + n = m + k, from calc m + n = n + m : add_comm m n ... = k + m : H ... = m + k : add_comm k m, add_cancel_left H2 theorem add_eq_zero_left {n m : ℕ} : n + m = 0 → n = 0 := induction_on n (take (H : 0 + m = 0), refl 0) (take k IH, assume (H : succ k + m = 0), absurd_elim (succ k = 0) (show succ (k + m) = 0, from calc succ (k + m) = succ k + m : symm (add_succ_left k m) ... = 0 : H) (succ_ne_zero (k + m))) theorem add_eq_zero_right {n m : ℕ} (H : n + m = 0) : m = 0 := add_eq_zero_left (trans (add_comm m n) H) theorem add_eq_zero {n m : ℕ} (H : n + m = 0) : n = 0 ∧ m = 0 := and_intro (add_eq_zero_left H) (add_eq_zero_right H) -- ### misc theorem add_one (n : ℕ) : n + 1 = succ n := calc n + 1 = succ (n + 0) : add_succ_right _ _ ... = succ n : {add_zero_right _} theorem add_one_left (n : ℕ) : 1 + n = succ n := calc 1 + n = succ (0 + n) : add_succ_left _ _ ... = succ n : {add_zero_left _} -- TODO: rename? remove? theorem induction_plus_one {P : nat → Prop} (a : ℕ) (H1 : P 0) (H2 : ∀ (n : ℕ) (IH : P n), P (n + 1)) : P a := nat_rec H1 (take n IH, (add_one n) ▸ (H2 n IH)) a -- Multiplication -- -------------- definition mul (n m : ℕ) := nat_rec 0 (fun m x, x + n) m infixl `*`:75 := mul theorem mul_zero_right (n:ℕ) : n * 0 = 0 theorem mul_succ_right (n m:ℕ) : n * succ m = n * m + n opaque_hint (hiding mul) -- ### commutativity, distributivity, associativity, identity theorem mul_zero_left (n:ℕ) : 0 * n = 0 := induction_on n (mul_zero_right 0) (take m IH, calc 0 * succ m = 0 * m + 0 : mul_succ_right _ _ ... = 0 * m : add_zero_right _ ... = 0 : IH) theorem mul_succ_left (n m:ℕ) : (succ n) * m = (n * m) + m := induction_on m (calc succ n * 0 = 0 : mul_zero_right _ ... = n * 0 : symm (mul_zero_right _) ... = n * 0 + 0 : symm (add_zero_right _)) (take k IH, calc succ n * succ k = (succ n * k) + succ n : mul_succ_right _ _ ... = (n * k) + k + succ n : { IH } ... = (n * k) + (k + succ n) : add_assoc _ _ _ ... = (n * k) + (n + succ k) : {add_comm_succ _ _} ... = (n * k) + n + succ k : symm (add_assoc _ _ _) ... = (n * succ k) + succ k : {symm (mul_succ_right n k)}) theorem mul_comm (n m:ℕ) : n * m = m * n := induction_on m (trans (mul_zero_right _) (symm (mul_zero_left _))) (take k IH, calc n * succ k = n * k + n : mul_succ_right _ _ ... = k * n + n : {IH} ... = (succ k) * n : symm (mul_succ_left _ _)) theorem mul_add_distr_left (n m k : ℕ) : (n + m) * k = n * k + m * k := induction_on k (calc (n + m) * 0 = 0 : mul_zero_right _ ... = 0 + 0 : symm (add_zero_right _) ... = n * 0 + 0 : {symm (mul_zero_right _)} ... = n * 0 + m * 0 : {symm (mul_zero_right _)}) (take l IH, calc (n + m) * succ l = (n + m) * l + (n + m) : mul_succ_right _ _ ... = n * l + m * l + (n + m) : {IH} ... = n * l + m * l + n + m : symm (add_assoc _ _ _) ... = n * l + n + m * l + m : {add_right_comm _ _ _} ... = n * l + n + (m * l + m) : add_assoc _ _ _ ... = n * succ l + (m * l + m) : {symm (mul_succ_right _ _)} ... = n * succ l + m * succ l : {symm (mul_succ_right _ _)}) theorem mul_add_distr_right (n m k : ℕ) : n * (m + k) = n * m + n * k := calc n * (m + k) = (m + k) * n : mul_comm _ _ ... = m * n + k * n : mul_add_distr_left _ _ _ ... = n * m + k * n : {mul_comm _ _} ... = n * m + n * k : {mul_comm _ _} theorem mul_assoc (n m k:ℕ) : (n * m) * k = n * (m * k) := induction_on k (calc (n * m) * 0 = 0 : mul_zero_right _ ... = n * 0 : symm (mul_zero_right _) ... = n * (m * 0) : {symm (mul_zero_right _)}) (take l IH, calc (n * m) * succ l = (n * m) * l + n * m : mul_succ_right _ _ ... = n * (m * l) + n * m : {IH} ... = n * (m * l + m) : symm (mul_add_distr_right _ _ _) ... = n * (m * succ l) : {symm (mul_succ_right _ _)}) theorem mul_comm_left (n m k : ℕ) : n * (m * k) = m * (n * k) := left_comm mul_comm mul_assoc n m k theorem mul_comm_right (n m k : ℕ) : n * m * k = n * k * m := right_comm mul_comm mul_assoc n m k theorem mul_one_right (n : ℕ) : n * 1 = n := calc n * 1 = n * 0 + n : mul_succ_right n 0 ... = 0 + n : {mul_zero_right n} ... = n : add_zero_left n theorem mul_one_left (n : ℕ) : 1 * n = n := calc 1 * n = n * 1 : mul_comm _ _ ... = n : mul_one_right n theorem mul_eq_zero {n m : ℕ} (H : n * m = 0) : n = 0 ∨ m = 0 := discriminate (take Hn : n = 0, or_intro_left _ Hn) (take (k : ℕ), assume (Hk : n = succ k), discriminate (take (Hm : m = 0), or_intro_right _ Hm) (take (l : ℕ), assume (Hl : m = succ l), have Heq : succ (k * succ l + l) = n * m, from symm (calc n * m = n * succ l : {Hl} ... = succ k * succ l : {Hk} ... = k * succ l + succ l : mul_succ_left _ _ ... = succ (k * succ l + l) : add_succ_right _ _), absurd_elim _ (trans Heq H) (succ_ne_zero _))) ---other inversion theorems appear below -- add_rewrite mul_zero_left mul_zero_right mul_one_right mul_one_left -- add_rewrite mul_succ_left mul_succ_right -- add_rewrite mul_comm mul_assoc mul_left_comm -- add_rewrite mul_distr_right mul_distr_left
229011020f9cabea693d3f4f517756f762b67929
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/test/traversable.lean
9751f1939229108ea001ca53e754e0338d91dfca
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
2,109
lean
import control.traversable.derive import control.traversable.instances universes u /- traversable -/ open tactic.interactive run_cmd do lawful_traversable_derive_handler' `test ``(is_lawful_traversable) ``list -- the above creates local instances of `traversable` and `is_lawful_traversable` -- for `list` -- do not put in instances because they are not universe polymorphic @[derive [traversable, is_lawful_traversable]] structure my_struct (α : Type) := (y : ℤ) @[derive [traversable, is_lawful_traversable]] inductive either (α : Type u) | left : α → ℤ → either | right : α → either @[derive [traversable, is_lawful_traversable]] structure my_struct2 (α : Type u) : Type u := (x : α) (y : ℤ) (η : list α) (k : list (list α)) @[derive [traversable, is_lawful_traversable]] inductive rec_data3 (α : Type u) : Type u | nil : rec_data3 | cons : ℕ → α → rec_data3 → rec_data3 → rec_data3 @[derive traversable] meta structure meta_struct (α : Type u) : Type u := (x : α) (y : ℤ) (z : list α) (k : list (list α)) (w : expr) @[derive [traversable,is_lawful_traversable]] inductive my_tree (α : Type) | leaf : my_tree | node : my_tree → my_tree → α → my_tree @[derive [traversable,is_lawful_traversable]] inductive my_tree' (α : Type) | leaf : my_tree' | node : my_tree' → α → my_tree' → my_tree' section open my_tree (hiding traverse) def x : my_tree (list nat) := node leaf (node (node leaf leaf [1,2,3]) leaf [3,2]) [1] /-- demonstrate the nested use of `traverse`. It traverses each node of the tree and in each node, traverses each list. For each `ℕ` visited, apply an action `ℕ -> state (list ℕ) unit` which adds its argument to the state. -/ def ex : state (list ℕ) (my_tree $ list unit) := do xs ← traverse (traverse $ λ a, modify $ list.cons a) x, pure xs example : (ex.run []).1 = node leaf (node (node leaf leaf [(), (), ()]) leaf [(), ()]) [()] := rfl example : (ex.run []).2 = [1, 2, 3, 3, 2, 1] := rfl example : is_lawful_traversable my_tree := my_tree.is_lawful_traversable end
9495616d53aab989e64ed9a45a907b0e83c818ff
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/multiset/range.lean
0280b36be2c4399a003ae0b032a5c4c17e7accd9
[]
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,133
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.multiset.basic import Mathlib.data.list.range import Mathlib.PostPort namespace Mathlib namespace multiset /- range -/ /-- `range n` is the multiset lifted from the list `range n`, that is, the set `{0, 1, ..., n-1}`. -/ def range (n : ℕ) : multiset ℕ := ↑(list.range n) @[simp] theorem range_zero : range 0 = 0 := rfl @[simp] theorem range_succ (n : ℕ) : range (Nat.succ n) = n ::ₘ range n := sorry @[simp] theorem card_range (n : ℕ) : coe_fn card (range n) = n := list.length_range n theorem range_subset {m : ℕ} {n : ℕ} : range m ⊆ range n ↔ m ≤ n := list.range_subset @[simp] theorem mem_range {m : ℕ} {n : ℕ} : m ∈ range n ↔ m < n := list.mem_range @[simp] theorem not_mem_range_self {n : ℕ} : ¬n ∈ range n := list.not_mem_range_self theorem self_mem_range_succ (n : ℕ) : n ∈ range (n + 1) := list.self_mem_range_succ n
f8dea63193503ce26c210b2ee9dbe858ae333162
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/library/logic/prop.lean
f2df9409680890a3003a4cf7b48870c6ce1f9531
[ "Apache-2.0" ]
permissive
codyroux/lean
7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3
0cca265db19f7296531e339192e9b9bae4a31f8b
refs/heads/master
1,610,909,964,159
1,407,084,399,000
1,416,857,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,367
lean
-- Copyright (c) 2014 Microsoft Corporation. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Leonardo de Moura, Jeremy Avigad import general_notation type -- implication -- ----------- definition imp (a b : Prop) : Prop := a → b -- true and false -- -------------- inductive false : Prop -- make c explicit and rename to false.elim theorem false_elim {c : Prop} (H : false) : c := false.rec c H inductive true : Prop := intro : true definition trivial := true.intro definition not (a : Prop) := a → false prefix `¬` := not -- not -- --- --rename to not.intro or neg.intro theorem not_intro {a : Prop} (H : a → false) : ¬a := H --rename to not.elim or neg.elim theorem not_elim {a : Prop} (H1 : ¬a) (H2 : a) : false := H1 H2 definition absurd {a : Prop} {b : Type} (H1 : a) (H2 : ¬a) : b := false.rec b (H2 H1) theorem not_not_intro {a : Prop} (Ha : a) : ¬¬a := assume Hna : ¬a, absurd Ha Hna theorem mt {a b : Prop} (H1 : a → b) (H2 : ¬b) : ¬a := assume Ha : a, absurd (H1 Ha) H2 theorem not_false_trivial : ¬false := assume H : false, H theorem not_implies_left {a b : Prop} (H : ¬(a → b)) : ¬¬a := assume Hna : ¬a, absurd (assume Ha : a, absurd Ha Hna) H theorem not_implies_right {a b : Prop} (H : ¬(a → b)) : ¬b := assume Hb : b, absurd (assume Ha : a, Hb) H
22356f4705b702026981a0f6bd07845711302819
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/geometry/euclidean/basic.lean
f8d4cf7ee4f1fcce827d390ba5b2af6741f51bd0
[ "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
32,058
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers, Manuel Candales -/ import analysis.inner_product_space.projection import algebra.quadratic_discriminant /-! # Euclidean spaces > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file makes some definitions and proves very basic geometrical results about real inner product spaces and Euclidean affine spaces. Results about real inner product spaces that involve the norm and inner product but not angles generally go in `analysis.normed_space.inner_product`. Results with longer proofs or more geometrical content generally go in separate files. ## Main definitions * `euclidean_geometry.orthogonal_projection` is the orthogonal projection of a point onto an affine subspace. * `euclidean_geometry.reflection` is the reflection of a point in an affine subspace. ## Implementation notes To declare `P` as the type of points in a Euclidean affine space with `V` as the type of vectors, use `[normed_add_comm_group V] [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P]`. This works better with `out_param` to make `V` implicit in most cases than having a separate type alias for Euclidean affine spaces. Rather than requiring Euclidean affine spaces to be finite-dimensional (as in the definition on Wikipedia), this is specified only for those theorems that need it. ## References * https://en.wikipedia.org/wiki/Euclidean_space -/ noncomputable theory open_locale big_operators open_locale classical open_locale real_inner_product_space namespace euclidean_geometry /-! ### Geometrical results on Euclidean affine spaces This section develops some geometrical definitions and results on Euclidean affine spaces. -/ variables {V : Type*} {P : Type*} variables [normed_add_comm_group V] [inner_product_space ℝ V] [metric_space P] variables [normed_add_torsor V P] include V /-- The midpoint of the segment AB is the same distance from A as it is from B. -/ lemma dist_left_midpoint_eq_dist_right_midpoint (p1 p2 : P) : dist p1 (midpoint ℝ p1 p2) = dist p2 (midpoint ℝ p1 p2) := by rw [dist_left_midpoint p1 p2, dist_right_midpoint p1 p2] /-- The inner product of two vectors given with `weighted_vsub`, in terms of the pairwise distances. -/ lemma inner_weighted_vsub {ι₁ : Type*} {s₁ : finset ι₁} {w₁ : ι₁ → ℝ} (p₁ : ι₁ → P) (h₁ : ∑ i in s₁, w₁ i = 0) {ι₂ : Type*} {s₂ : finset ι₂} {w₂ : ι₂ → ℝ} (p₂ : ι₂ → P) (h₂ : ∑ i in s₂, w₂ i = 0) : ⟪s₁.weighted_vsub p₁ w₁, s₂.weighted_vsub p₂ w₂⟫ = (-∑ i₁ in s₁, ∑ i₂ in s₂, w₁ i₁ * w₂ i₂ * (dist (p₁ i₁) (p₂ i₂) * dist (p₁ i₁) (p₂ i₂))) / 2 := begin rw [finset.weighted_vsub_apply, finset.weighted_vsub_apply, inner_sum_smul_sum_smul_of_sum_eq_zero _ h₁ _ h₂], simp_rw [vsub_sub_vsub_cancel_right], rcongr i₁ i₂; rw dist_eq_norm_vsub V (p₁ i₁) (p₂ i₂) end /-- The distance between two points given with `affine_combination`, in terms of the pairwise distances between the points in that combination. -/ lemma dist_affine_combination {ι : Type*} {s : finset ι} {w₁ w₂ : ι → ℝ} (p : ι → P) (h₁ : ∑ i in s, w₁ i = 1) (h₂ : ∑ i in s, w₂ i = 1) : by have a₁ := s.affine_combination ℝ p w₁; have a₂ := s.affine_combination ℝ p w₂; exact dist a₁ a₂ * dist a₁ a₂ = (-∑ i₁ in s, ∑ i₂ in s, (w₁ - w₂) i₁ * (w₁ - w₂) i₂ * (dist (p i₁) (p i₂) * dist (p i₁) (p i₂))) / 2 := begin rw [dist_eq_norm_vsub V (s.affine_combination ℝ p w₁) (s.affine_combination ℝ p w₂), ←@inner_self_eq_norm_mul_norm ℝ, finset.affine_combination_vsub], have h : ∑ i in s, (w₁ - w₂) i = 0, { simp_rw [pi.sub_apply, finset.sum_sub_distrib, h₁, h₂, sub_self] }, exact inner_weighted_vsub p h p h end /-- Suppose that `c₁` is equidistant from `p₁` and `p₂`, and the same applies to `c₂`. Then the vector between `c₁` and `c₂` is orthogonal to that between `p₁` and `p₂`. (In two dimensions, this says that the diagonals of a kite are orthogonal.) -/ lemma inner_vsub_vsub_of_dist_eq_of_dist_eq {c₁ c₂ p₁ p₂ : P} (hc₁ : dist p₁ c₁ = dist p₂ c₁) (hc₂ : dist p₁ c₂ = dist p₂ c₂) : ⟪c₂ -ᵥ c₁, p₂ -ᵥ p₁⟫ = 0 := begin have h : ⟪(c₂ -ᵥ c₁) + (c₂ -ᵥ c₁), p₂ -ᵥ p₁⟫ = 0, { conv_lhs { congr, congr, rw ←vsub_sub_vsub_cancel_right c₂ c₁ p₁, skip, rw ←vsub_sub_vsub_cancel_right c₂ c₁ p₂ }, rw [sub_add_sub_comm, inner_sub_left], conv_lhs { congr, rw ←vsub_sub_vsub_cancel_right p₂ p₁ c₂, skip, rw ←vsub_sub_vsub_cancel_right p₂ p₁ c₁ }, rw [dist_comm p₁, dist_comm p₂, dist_eq_norm_vsub V _ p₁, dist_eq_norm_vsub V _ p₂, ←real_inner_add_sub_eq_zero_iff] at hc₁ hc₂, simp_rw [←neg_vsub_eq_vsub_rev c₁, ←neg_vsub_eq_vsub_rev c₂, sub_neg_eq_add, neg_add_eq_sub, hc₁, hc₂, sub_zero] }, simpa [inner_add_left, ←mul_two, (by norm_num : (2 : ℝ) ≠ 0)] using h end /-- The squared distance between points on a line (expressed as a multiple of a fixed vector added to a point) and another point, expressed as a quadratic. -/ lemma dist_smul_vadd_sq (r : ℝ) (v : V) (p₁ p₂ : P) : dist (r • v +ᵥ p₁) p₂ * dist (r • v +ᵥ p₁) p₂ = ⟪v, v⟫ * r * r + 2 * ⟪v, p₁ -ᵥ p₂⟫ * r + ⟪p₁ -ᵥ p₂, p₁ -ᵥ p₂⟫ := begin rw [dist_eq_norm_vsub V _ p₂, ←real_inner_self_eq_norm_mul_norm, vadd_vsub_assoc, real_inner_add_add_self, real_inner_smul_left, real_inner_smul_left, real_inner_smul_right], ring end /-- The condition for two points on a line to be equidistant from another point. -/ lemma dist_smul_vadd_eq_dist {v : V} (p₁ p₂ : P) (hv : v ≠ 0) (r : ℝ) : dist (r • v +ᵥ p₁) p₂ = dist p₁ p₂ ↔ (r = 0 ∨ r = -2 * ⟪v, p₁ -ᵥ p₂⟫ / ⟪v, v⟫) := begin conv_lhs { rw [←mul_self_inj_of_nonneg dist_nonneg dist_nonneg, dist_smul_vadd_sq, ←sub_eq_zero, add_sub_assoc, dist_eq_norm_vsub V p₁ p₂, ←real_inner_self_eq_norm_mul_norm, sub_self] }, have hvi : ⟪v, v⟫ ≠ 0, by simpa using hv, have hd : discrim ⟪v, v⟫ (2 * ⟪v, p₁ -ᵥ p₂⟫) 0 = (2 * ⟪v, p₁ -ᵥ p₂⟫) * (2 * ⟪v, p₁ -ᵥ p₂⟫), { rw discrim, ring }, rw [quadratic_eq_zero_iff hvi hd, add_left_neg, zero_div, neg_mul_eq_neg_mul, ←mul_sub_right_distrib, sub_eq_add_neg, ←mul_two, mul_assoc, mul_div_assoc, mul_div_mul_left, mul_div_assoc], norm_num end open affine_subspace finite_dimensional /-- Distances `r₁` `r₂` of `p` from two different points `c₁` `c₂` determine at most two points `p₁` `p₂` in a two-dimensional subspace containing those points (two circles intersect in at most two points). -/ lemma eq_of_dist_eq_of_dist_eq_of_mem_of_finrank_eq_two {s : affine_subspace ℝ P} [finite_dimensional ℝ s.direction] (hd : finrank ℝ s.direction = 2) {c₁ c₂ p₁ p₂ p : P} (hc₁s : c₁ ∈ s) (hc₂s : c₂ ∈ s) (hp₁s : p₁ ∈ s) (hp₂s : p₂ ∈ s) (hps : p ∈ s) {r₁ r₂ : ℝ} (hc : c₁ ≠ c₂) (hp : p₁ ≠ p₂) (hp₁c₁ : dist p₁ c₁ = r₁) (hp₂c₁ : dist p₂ c₁ = r₁) (hpc₁ : dist p c₁ = r₁) (hp₁c₂ : dist p₁ c₂ = r₂) (hp₂c₂ : dist p₂ c₂ = r₂) (hpc₂ : dist p c₂ = r₂) : p = p₁ ∨ p = p₂ := begin have ho : ⟪c₂ -ᵥ c₁, p₂ -ᵥ p₁⟫ = 0 := inner_vsub_vsub_of_dist_eq_of_dist_eq (hp₁c₁.trans hp₂c₁.symm) (hp₁c₂.trans hp₂c₂.symm), have hop : ⟪c₂ -ᵥ c₁, p -ᵥ p₁⟫ = 0 := inner_vsub_vsub_of_dist_eq_of_dist_eq (hp₁c₁.trans hpc₁.symm) (hp₁c₂.trans hpc₂.symm), let b : fin 2 → V := ![c₂ -ᵥ c₁, p₂ -ᵥ p₁], have hb : linear_independent ℝ b, { refine linear_independent_of_ne_zero_of_inner_eq_zero _ _, { intro i, fin_cases i; simp [b, hc.symm, hp.symm], }, { intros i j hij, fin_cases i; fin_cases j; try { exact false.elim (hij rfl) }, { exact ho }, { rw real_inner_comm, exact ho } } }, have hbs : submodule.span ℝ (set.range b) = s.direction, { refine eq_of_le_of_finrank_eq _ _, { rw [submodule.span_le, set.range_subset_iff], intro i, fin_cases i, { exact vsub_mem_direction hc₂s hc₁s }, { exact vsub_mem_direction hp₂s hp₁s } }, { rw [finrank_span_eq_card hb, fintype.card_fin, hd] } }, have hv : ∀ v ∈ s.direction, ∃ t₁ t₂ : ℝ, v = t₁ • (c₂ -ᵥ c₁) + t₂ • (p₂ -ᵥ p₁), { intros v hv, have hr : set.range b = {c₂ -ᵥ c₁, p₂ -ᵥ p₁}, { have hu : (finset.univ : finset (fin 2)) = {0, 1}, by dec_trivial, rw [←fintype.coe_image_univ, hu], simp, refl }, rw [←hbs, hr, submodule.mem_span_insert] at hv, rcases hv with ⟨t₁, v', hv', hv⟩, rw submodule.mem_span_singleton at hv', rcases hv' with ⟨t₂, rfl⟩, exact ⟨t₁, t₂, hv⟩ }, rcases hv (p -ᵥ p₁) (vsub_mem_direction hps hp₁s) with ⟨t₁, t₂, hpt⟩, simp only [hpt, inner_add_right, inner_smul_right, ho, mul_zero, add_zero, mul_eq_zero, inner_self_eq_zero, vsub_eq_zero_iff_eq, hc.symm, or_false] at hop, rw [hop, zero_smul, zero_add, ←eq_vadd_iff_vsub_eq] at hpt, subst hpt, have hp' : (p₂ -ᵥ p₁ : V) ≠ 0, { simp [hp.symm] }, have hp₂ : dist ((1 : ℝ) • (p₂ -ᵥ p₁) +ᵥ p₁) c₁ = r₁, { simp [hp₂c₁] }, rw [←hp₁c₁, dist_smul_vadd_eq_dist _ _ hp'] at hpc₁ hp₂, simp only [one_ne_zero, false_or] at hp₂, rw hp₂.symm at hpc₁, cases hpc₁; simp [hpc₁] end /-- Distances `r₁` `r₂` of `p` from two different points `c₁` `c₂` determine at most two points `p₁` `p₂` in two-dimensional space (two circles intersect in at most two points). -/ lemma eq_of_dist_eq_of_dist_eq_of_finrank_eq_two [finite_dimensional ℝ V] (hd : finrank ℝ V = 2) {c₁ c₂ p₁ p₂ p : P} {r₁ r₂ : ℝ} (hc : c₁ ≠ c₂) (hp : p₁ ≠ p₂) (hp₁c₁ : dist p₁ c₁ = r₁) (hp₂c₁ : dist p₂ c₁ = r₁) (hpc₁ : dist p c₁ = r₁) (hp₁c₂ : dist p₁ c₂ = r₂) (hp₂c₂ : dist p₂ c₂ = r₂) (hpc₂ : dist p c₂ = r₂) : p = p₁ ∨ p = p₂ := begin have hd' : finrank ℝ (⊤ : affine_subspace ℝ P).direction = 2, { rw [direction_top, finrank_top], exact hd }, exact eq_of_dist_eq_of_dist_eq_of_mem_of_finrank_eq_two hd' (mem_top ℝ V _) (mem_top ℝ V _) (mem_top ℝ V _) (mem_top ℝ V _) (mem_top ℝ V _) hc hp hp₁c₁ hp₂c₁ hpc₁ hp₁c₂ hp₂c₂ hpc₂ end variables {V} /-- The orthogonal projection of a point onto a nonempty affine subspace, whose direction is complete, as an unbundled function. This definition is only intended for use in setting up the bundled version `orthogonal_projection` and should not be used once that is defined. -/ def orthogonal_projection_fn (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p : P) : P := classical.some $ inter_eq_singleton_of_nonempty_of_is_compl (nonempty_subtype.mp ‹_›) (mk'_nonempty p s.directionᗮ) begin rw direction_mk' p s.directionᗮ, exact submodule.is_compl_orthogonal_of_complete_space, end /-- The intersection of the subspace and the orthogonal subspace through the given point is the `orthogonal_projection_fn` of that point onto the subspace. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma inter_eq_singleton_orthogonal_projection_fn {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : P) : (s : set P) ∩ (mk' p s.directionᗮ) = {orthogonal_projection_fn s p} := classical.some_spec $ inter_eq_singleton_of_nonempty_of_is_compl (nonempty_subtype.mp ‹_›) (mk'_nonempty p s.directionᗮ) begin rw direction_mk' p s.directionᗮ, exact submodule.is_compl_orthogonal_of_complete_space end /-- The `orthogonal_projection_fn` lies in the given subspace. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma orthogonal_projection_fn_mem {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : P) : orthogonal_projection_fn s p ∈ s := begin rw [←mem_coe, ←set.singleton_subset_iff, ←inter_eq_singleton_orthogonal_projection_fn], exact set.inter_subset_left _ _ end /-- The `orthogonal_projection_fn` lies in the orthogonal subspace. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma orthogonal_projection_fn_mem_orthogonal {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : P) : orthogonal_projection_fn s p ∈ mk' p s.directionᗮ := begin rw [←mem_coe, ←set.singleton_subset_iff, ←inter_eq_singleton_orthogonal_projection_fn], exact set.inter_subset_right _ _ end /-- Subtracting `p` from its `orthogonal_projection_fn` produces a result in the orthogonal direction. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma orthogonal_projection_fn_vsub_mem_direction_orthogonal {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : P) : orthogonal_projection_fn s p -ᵥ p ∈ s.directionᗮ := direction_mk' p s.directionᗮ ▸ vsub_mem_direction (orthogonal_projection_fn_mem_orthogonal p) (self_mem_mk' _ _) local attribute [instance] affine_subspace.to_add_torsor /-- The orthogonal projection of a point onto a nonempty affine subspace, whose direction is complete. The corresponding linear map (mapping a vector to the difference between the projections of two points whose difference is that vector) is the `orthogonal_projection` for real inner product spaces, onto the direction of the affine subspace being projected onto. -/ def orthogonal_projection (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] : P →ᵃ[ℝ] s := { to_fun := λ p, ⟨orthogonal_projection_fn s p, orthogonal_projection_fn_mem p⟩, linear := orthogonal_projection s.direction, map_vadd' := λ p v, begin have hs : ((orthogonal_projection s.direction) v : V) +ᵥ orthogonal_projection_fn s p ∈ s := vadd_mem_of_mem_direction (orthogonal_projection s.direction v).2 (orthogonal_projection_fn_mem p), have ho : ((orthogonal_projection s.direction) v : V) +ᵥ orthogonal_projection_fn s p ∈ mk' (v +ᵥ p) s.directionᗮ, { rw [←vsub_right_mem_direction_iff_mem (self_mem_mk' _ _) _, direction_mk', vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, add_comm, add_sub_assoc], refine submodule.add_mem _ (orthogonal_projection_fn_vsub_mem_direction_orthogonal p) _, rw submodule.mem_orthogonal', intros w hw, rw [←neg_sub, inner_neg_left, orthogonal_projection_inner_eq_zero _ w hw, neg_zero], }, have hm : ((orthogonal_projection s.direction) v : V) +ᵥ orthogonal_projection_fn s p ∈ ({orthogonal_projection_fn s (v +ᵥ p)} : set P), { rw ←inter_eq_singleton_orthogonal_projection_fn (v +ᵥ p), exact set.mem_inter hs ho }, rw set.mem_singleton_iff at hm, ext, exact hm.symm end } @[simp] lemma orthogonal_projection_fn_eq {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : P) : orthogonal_projection_fn s p = orthogonal_projection s p := rfl /-- The linear map corresponding to `orthogonal_projection`. -/ @[simp] lemma orthogonal_projection_linear {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] : (orthogonal_projection s).linear = _root_.orthogonal_projection s.direction := rfl /-- The intersection of the subspace and the orthogonal subspace through the given point is the `orthogonal_projection` of that point onto the subspace. -/ lemma inter_eq_singleton_orthogonal_projection {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : P) : (s : set P) ∩ (mk' p s.directionᗮ) = {orthogonal_projection s p} := begin rw ←orthogonal_projection_fn_eq, exact inter_eq_singleton_orthogonal_projection_fn p end /-- The `orthogonal_projection` lies in the given subspace. -/ lemma orthogonal_projection_mem {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : P) : ↑(orthogonal_projection s p) ∈ s := (orthogonal_projection s p).2 /-- The `orthogonal_projection` lies in the orthogonal subspace. -/ lemma orthogonal_projection_mem_orthogonal (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p : P) : ↑(orthogonal_projection s p) ∈ mk' p s.directionᗮ := orthogonal_projection_fn_mem_orthogonal p /-- Subtracting a point in the given subspace from the `orthogonal_projection` produces a result in the direction of the given subspace. -/ lemma orthogonal_projection_vsub_mem_direction {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p1 : P} (p2 : P) (hp1 : p1 ∈ s) : ↑(orthogonal_projection s p2 -ᵥ ⟨p1, hp1⟩ : s.direction) ∈ s.direction := (orthogonal_projection s p2 -ᵥ ⟨p1, hp1⟩ : s.direction).2 /-- Subtracting the `orthogonal_projection` from a point in the given subspace produces a result in the direction of the given subspace. -/ lemma vsub_orthogonal_projection_mem_direction {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p1 : P} (p2 : P) (hp1 : p1 ∈ s) : ↑((⟨p1, hp1⟩ : s) -ᵥ orthogonal_projection s p2 : s.direction) ∈ s.direction := ((⟨p1, hp1⟩ : s) -ᵥ orthogonal_projection s p2 : s.direction).2 /-- A point equals its orthogonal projection if and only if it lies in the subspace. -/ lemma orthogonal_projection_eq_self_iff {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p : P} : ↑(orthogonal_projection s p) = p ↔ p ∈ s := begin split, { exact λ h, h ▸ orthogonal_projection_mem p }, { intro h, have hp : p ∈ ((s : set P) ∩ mk' p s.directionᗮ) := ⟨h, self_mem_mk' p _⟩, rw [inter_eq_singleton_orthogonal_projection p] at hp, symmetry, exact hp } end @[simp] lemma orthogonal_projection_mem_subspace_eq_self {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : s) : orthogonal_projection s p = p := begin ext, rw orthogonal_projection_eq_self_iff, exact p.2 end /-- Orthogonal projection is idempotent. -/ @[simp] lemma orthogonal_projection_orthogonal_projection (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p : P) : orthogonal_projection s (orthogonal_projection s p) = orthogonal_projection s p := begin ext, rw orthogonal_projection_eq_self_iff, exact orthogonal_projection_mem p, end lemma eq_orthogonal_projection_of_eq_subspace {s s' : affine_subspace ℝ P} [nonempty s] [nonempty s'] [complete_space s.direction] [complete_space s'.direction] (h : s = s') (p : P) : (orthogonal_projection s p : P) = (orthogonal_projection s' p : P) := begin change orthogonal_projection_fn s p = orthogonal_projection_fn s' p, congr, exact h end /-- The distance to a point's orthogonal projection is 0 iff it lies in the subspace. -/ lemma dist_orthogonal_projection_eq_zero_iff {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p : P} : dist p (orthogonal_projection s p) = 0 ↔ p ∈ s := by rw [dist_comm, dist_eq_zero, orthogonal_projection_eq_self_iff] /-- The distance between a point and its orthogonal projection is nonzero if it does not lie in the subspace. -/ lemma dist_orthogonal_projection_ne_zero_of_not_mem {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p : P} (hp : p ∉ s) : dist p (orthogonal_projection s p) ≠ 0 := mt dist_orthogonal_projection_eq_zero_iff.mp hp /-- Subtracting `p` from its `orthogonal_projection` produces a result in the orthogonal direction. -/ lemma orthogonal_projection_vsub_mem_direction_orthogonal (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p : P) : (orthogonal_projection s p : P) -ᵥ p ∈ s.directionᗮ := orthogonal_projection_fn_vsub_mem_direction_orthogonal p /-- Subtracting the `orthogonal_projection` from `p` produces a result in the orthogonal direction. -/ lemma vsub_orthogonal_projection_mem_direction_orthogonal (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p : P) : p -ᵥ orthogonal_projection s p ∈ s.directionᗮ := direction_mk' p s.directionᗮ ▸ vsub_mem_direction (self_mem_mk' _ _) (orthogonal_projection_mem_orthogonal s p) /-- Subtracting the `orthogonal_projection` from `p` produces a result in the kernel of the linear part of the orthogonal projection. -/ lemma orthogonal_projection_vsub_orthogonal_projection (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p : P) : _root_.orthogonal_projection s.direction (p -ᵥ orthogonal_projection s p) = 0 := begin apply orthogonal_projection_mem_subspace_orthogonal_complement_eq_zero, intros c hc, rw [← neg_vsub_eq_vsub_rev, inner_neg_right, (orthogonal_projection_vsub_mem_direction_orthogonal s p c hc), neg_zero] end /-- Adding a vector to a point in the given subspace, then taking the orthogonal projection, produces the original point if the vector was in the orthogonal direction. -/ lemma orthogonal_projection_vadd_eq_self {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p : P} (hp : p ∈ s) {v : V} (hv : v ∈ s.directionᗮ) : orthogonal_projection s (v +ᵥ p) = ⟨p, hp⟩ := begin have h := vsub_orthogonal_projection_mem_direction_orthogonal s (v +ᵥ p), rw [vadd_vsub_assoc, submodule.add_mem_iff_right _ hv] at h, refine (eq_of_vsub_eq_zero _).symm, ext, refine submodule.disjoint_def.1 s.direction.orthogonal_disjoint _ _ h, exact (_ : s.direction).2 end /-- Adding a vector to a point in the given subspace, then taking the orthogonal projection, produces the original point if the vector is a multiple of the result of subtracting a point's orthogonal projection from that point. -/ lemma orthogonal_projection_vadd_smul_vsub_orthogonal_projection {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p1 : P} (p2 : P) (r : ℝ) (hp : p1 ∈ s) : orthogonal_projection s (r • (p2 -ᵥ orthogonal_projection s p2 : V) +ᵥ p1) = ⟨p1, hp⟩ := orthogonal_projection_vadd_eq_self hp (submodule.smul_mem _ _ (vsub_orthogonal_projection_mem_direction_orthogonal s _)) /-- The square of the distance from a point in `s` to `p2` equals the sum of the squares of the distances of the two points to the `orthogonal_projection`. -/ lemma dist_sq_eq_dist_orthogonal_projection_sq_add_dist_orthogonal_projection_sq {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p1 : P} (p2 : P) (hp1 : p1 ∈ s) : dist p1 p2 * dist p1 p2 = dist p1 (orthogonal_projection s p2) * dist p1 (orthogonal_projection s p2) + dist p2 (orthogonal_projection s p2) * dist p2 (orthogonal_projection s p2) := begin rw [dist_comm p2 _, dist_eq_norm_vsub V p1 _, dist_eq_norm_vsub V p1 _, dist_eq_norm_vsub V _ p2, ← vsub_add_vsub_cancel p1 (orthogonal_projection s p2) p2, norm_add_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero], exact submodule.inner_right_of_mem_orthogonal (vsub_orthogonal_projection_mem_direction p2 hp1) (orthogonal_projection_vsub_mem_direction_orthogonal s p2), end /-- The square of the distance between two points constructed by adding multiples of the same orthogonal vector to points in the same subspace. -/ lemma dist_sq_smul_orthogonal_vadd_smul_orthogonal_vadd {s : affine_subspace ℝ P} {p1 p2 : P} (hp1 : p1 ∈ s) (hp2 : p2 ∈ s) (r1 r2 : ℝ) {v : V} (hv : v ∈ s.directionᗮ) : dist (r1 • v +ᵥ p1) (r2 • v +ᵥ p2) * dist (r1 • v +ᵥ p1) (r2 • v +ᵥ p2) = dist p1 p2 * dist p1 p2 + (r1 - r2) * (r1 - r2) * (‖v‖ * ‖v‖) := calc dist (r1 • v +ᵥ p1) (r2 • v +ᵥ p2) * dist (r1 • v +ᵥ p1) (r2 • v +ᵥ p2) = ‖(p1 -ᵥ p2) + (r1 - r2) • v‖ * ‖(p1 -ᵥ p2) + (r1 - r2) • v‖ : by rw [dist_eq_norm_vsub V (r1 • v +ᵥ p1), vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, sub_smul, add_comm, add_sub_assoc] ... = ‖p1 -ᵥ p2‖ * ‖p1 -ᵥ p2‖ + ‖(r1 - r2) • v‖ * ‖(r1 - r2) • v‖ : norm_add_sq_eq_norm_sq_add_norm_sq_real (submodule.inner_right_of_mem_orthogonal (vsub_mem_direction hp1 hp2) (submodule.smul_mem _ _ hv)) ... = ‖(p1 -ᵥ p2 : V)‖ * ‖(p1 -ᵥ p2 : V)‖ + |r1 - r2| * |r1 - r2| * ‖v‖ * ‖v‖ : by { rw [norm_smul, real.norm_eq_abs], ring } ... = dist p1 p2 * dist p1 p2 + (r1 - r2) * (r1 - r2) * (‖v‖ * ‖v‖) : by { rw [dist_eq_norm_vsub V p1, abs_mul_abs_self, mul_assoc] } /-- Reflection in an affine subspace, which is expected to be nonempty and complete. The word "reflection" is sometimes understood to mean specifically reflection in a codimension-one subspace, and sometimes more generally to cover operations such as reflection in a point. The definition here, of reflection in an affine subspace, is a more general sense of the word that includes both those common cases. -/ def reflection (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] : P ≃ᵃⁱ[ℝ] P := affine_isometry_equiv.mk' (λ p, (↑(orthogonal_projection s p) -ᵥ p) +ᵥ orthogonal_projection s p) (_root_.reflection s.direction) ↑(classical.arbitrary s) begin intros p, let v := p -ᵥ ↑(classical.arbitrary s), let a : V := _root_.orthogonal_projection s.direction v, let b : P := ↑(classical.arbitrary s), have key : a +ᵥ b -ᵥ (v +ᵥ b) +ᵥ (a +ᵥ b) = a + a - v +ᵥ (b -ᵥ b +ᵥ b), { rw [← add_vadd, vsub_vadd_eq_vsub_sub, vsub_vadd, vadd_vsub], congr' 1, abel }, have : p = v +ᵥ ↑(classical.arbitrary s) := (vsub_vadd p ↑(classical.arbitrary s)).symm, simpa only [coe_vadd, reflection_apply, affine_map.map_vadd, orthogonal_projection_linear, orthogonal_projection_mem_subspace_eq_self, vadd_vsub, continuous_linear_map.coe_coe, continuous_linear_equiv.coe_coe, this] using key, end /-- The result of reflecting. -/ lemma reflection_apply (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p : P) : reflection s p = (↑(orthogonal_projection s p) -ᵥ p) +ᵥ orthogonal_projection s p := rfl lemma eq_reflection_of_eq_subspace {s s' : affine_subspace ℝ P} [nonempty s] [nonempty s'] [complete_space s.direction] [complete_space s'.direction] (h : s = s') (p : P) : (reflection s p : P) = (reflection s' p : P) := by unfreezingI { subst h } /-- Reflecting twice in the same subspace. -/ @[simp] lemma reflection_reflection (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p : P) : reflection s (reflection s p) = p := begin have : ∀ a : s, ∀ b : V, (_root_.orthogonal_projection s.direction) b = 0 → reflection s (reflection s (b +ᵥ a)) = b +ᵥ a, { intros a b h, have : (a:P) -ᵥ (b +ᵥ a) = - b, { rw [vsub_vadd_eq_vsub_sub, vsub_self, zero_sub] }, simp [reflection, h, this] }, rw ← vsub_vadd p (orthogonal_projection s p), exact this (orthogonal_projection s p) _ (orthogonal_projection_vsub_orthogonal_projection s p), end /-- Reflection is its own inverse. -/ @[simp] lemma reflection_symm (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] : (reflection s).symm = reflection s := by { ext, rw ← (reflection s).injective.eq_iff, simp } /-- Reflection is involutive. -/ lemma reflection_involutive (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] : function.involutive (reflection s) := reflection_reflection s /-- A point is its own reflection if and only if it is in the subspace. -/ lemma reflection_eq_self_iff {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : P) : reflection s p = p ↔ p ∈ s := begin rw [←orthogonal_projection_eq_self_iff, reflection_apply], split, { intro h, rw [←@vsub_eq_zero_iff_eq V, vadd_vsub_assoc, ←two_smul ℝ (↑(orthogonal_projection s p) -ᵥ p), smul_eq_zero] at h, norm_num at h, exact h }, { intro h, simp [h] } end /-- Reflecting a point in two subspaces produces the same result if and only if the point has the same orthogonal projection in each of those subspaces. -/ lemma reflection_eq_iff_orthogonal_projection_eq (s₁ s₂ : affine_subspace ℝ P) [nonempty s₁] [nonempty s₂] [complete_space s₁.direction] [complete_space s₂.direction] (p : P) : reflection s₁ p = reflection s₂ p ↔ (orthogonal_projection s₁ p : P) = orthogonal_projection s₂ p := begin rw [reflection_apply, reflection_apply], split, { intro h, rw [←@vsub_eq_zero_iff_eq V, vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, add_comm, add_sub_assoc, vsub_sub_vsub_cancel_right, ←two_smul ℝ ((orthogonal_projection s₁ p : P) -ᵥ orthogonal_projection s₂ p), smul_eq_zero] at h, norm_num at h, exact h }, { intro h, rw h } end /-- The distance between `p₁` and the reflection of `p₂` equals that between the reflection of `p₁` and `p₂`. -/ lemma dist_reflection (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p₁ p₂ : P) : dist p₁ (reflection s p₂) = dist (reflection s p₁) p₂ := begin conv_lhs { rw ←reflection_reflection s p₁ }, exact (reflection s).dist_map _ _ end /-- A point in the subspace is equidistant from another point and its reflection. -/ lemma dist_reflection_eq_of_mem (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] {p₁ : P} (hp₁ : p₁ ∈ s) (p₂ : P) : dist p₁ (reflection s p₂) = dist p₁ p₂ := begin rw ←reflection_eq_self_iff p₁ at hp₁, convert (reflection s).dist_map p₁ p₂, rw hp₁ end /-- The reflection of a point in a subspace is contained in any larger subspace containing both the point and the subspace reflected in. -/ lemma reflection_mem_of_le_of_mem {s₁ s₂ : affine_subspace ℝ P} [nonempty s₁] [complete_space s₁.direction] (hle : s₁ ≤ s₂) {p : P} (hp : p ∈ s₂) : reflection s₁ p ∈ s₂ := begin rw [reflection_apply], have ho : ↑(orthogonal_projection s₁ p) ∈ s₂ := hle (orthogonal_projection_mem p), exact vadd_mem_of_mem_direction (vsub_mem_direction ho hp) ho end /-- Reflecting an orthogonal vector plus a point in the subspace produces the negation of that vector plus the point. -/ lemma reflection_orthogonal_vadd {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p : P} (hp : p ∈ s) {v : V} (hv : v ∈ s.directionᗮ) : reflection s (v +ᵥ p) = -v +ᵥ p := begin rw [reflection_apply, orthogonal_projection_vadd_eq_self hp hv, vsub_vadd_eq_vsub_sub], simp end /-- Reflecting a vector plus a point in the subspace produces the negation of that vector plus the point if the vector is a multiple of the result of subtracting a point's orthogonal projection from that point. -/ lemma reflection_vadd_smul_vsub_orthogonal_projection {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p₁ : P} (p₂ : P) (r : ℝ) (hp₁ : p₁ ∈ s) : reflection s (r • (p₂ -ᵥ orthogonal_projection s p₂) +ᵥ p₁) = -(r • (p₂ -ᵥ orthogonal_projection s p₂)) +ᵥ p₁ := reflection_orthogonal_vadd hp₁ (submodule.smul_mem _ _ (vsub_orthogonal_projection_mem_direction_orthogonal s _)) end euclidean_geometry
61c483e5a8d74be279c4e9460b34fa546925e097
618003631150032a5676f229d13a079ac875ff77
/src/group_theory/bundled_subgroup.lean
9baf26be107d970fcb2ef124b89eb3286ab1d490
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
28,275
lean
/- Copyright (c) 2020 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying -/ import group_theory.subgroup /-! # Subgroups This file defines multiplicative and additive subgroups as an extension of submonoids, in a bundled form (unbundled subgroups are in /subgroups.lean). We prove subgroups of a group form a complete lattice, and results about images and preimages of subgroups under group homomorphisms. The bundled subgroups use bundled monoid homomorphisms. There are also theorems about the subgroups generated by an element or a subset of a group, defined both inductively and as the infimum of the set of subgroups containing a given element/subset. Special thanks goes to Amelia Livingston and Yury Kudryashov for their help and inspiration. ## Main definitions Notation used here: - `G N` are groups - `A` is an add_group - `H K` are subgroups of `G` or add_subgroups of `A` - `x` is an element of type `G` or type `A` - `f g : N →* G` are group homomorphisms - `s k` are sets of elements of type `G` Definitions in the file: * `subgroup G` : the type of subgroups of a group `G` * `add_subgroup A` : the type of subgroups of an additive group `A` * `complete_lattice (subgroup G)` : the subgroups of `G` form a complete lattice * `closure k` : the minimal subgroup that includes the set `k` * `subtype` : the natural group homomorphism from a subgroup of group `G` to `G` * `gi` : `closure` forms a Galois insertion with the coercion to set * `comap H f` : the preimage of a subgroup `H` along the group homomorphism `f` is also a subgroup * `map f H` : the image of a subgroup `H` along the group homomorphism `f` is also a subgroup * `prod H K` : the product of subgroups `H`, `K` of groups `G`, `N` respectively, `H × K` is a subgroup of `G × N` * `monoid_hom.range f` : the range of the group homomorphism `f` is a subgroup * `monoid_hom.ker f` : the kernel of a group homomorphism `f` is the subgroup of elements `x : G` such that `f x = 1` * `monoid_hom.eq_locus f g` : given group homomorphisms `f`, `g`, the elements of `G` such that `f x = g x` form a subgroup of `G` ## Implementation notes Subgroup inclusion is denoted `≤` rather than `⊆`, although `∈` is defined as membership of a subgroup's underlying set. ## Tags subgroup, subgroups -/ variables {G : Type*} [group G] variables {A : Type*} [add_group A] set_option old_structure_cmd true /-- A subgroup of a group `G` is a subset containing 1, closed under multiplication and closed under multiplicative inverse. -/ structure subgroup (G : Type*) [group G] extends submonoid G := (inv_mem' {x} : x ∈ carrier → x⁻¹ ∈ carrier) /-- An additive subgroup of an additive group `G` is a subset containing 0, closed under addition and additive inverse. -/ structure add_subgroup (G : Type*) [add_group G] extends add_submonoid G:= (neg_mem' {x} : x ∈ carrier → -x ∈ carrier) attribute [to_additive add_subgroup] subgroup attribute [to_additive add_subgroup.to_add_submonoid] subgroup.to_submonoid /-- Reinterpret a `subgroup` as a `submonoid`. -/ add_decl_doc subgroup.to_submonoid /-- Reinterpret an `add_subgroup` as an `add_submonoid`. -/ add_decl_doc add_subgroup.to_add_submonoid /-- Create a bundled subgroup from a set `s` and `[is_subroup s]`. -/ @[to_additive "Create a bundled additive subgroup from a set `s` and `[is_add_subgroup s]`."] def subgroup.of (s : set G) [h : is_subgroup s] : subgroup G := { carrier := s, one_mem' := h.1.1, mul_mem' := h.1.2, inv_mem' := h.2 } /-- Map from subgroups of group `G` to `add_subgroup`s of `additive G`. -/ def subgroup.to_add_subgroup {G : Type*} [group G] (H : subgroup G) : add_subgroup (additive G) := { neg_mem' := H.inv_mem', .. submonoid.to_add_submonoid H.to_submonoid} /-- Map from `add_subgroup`s of `additive G` to subgroups of `G`. -/ def subgroup.of_add_subgroup {G : Type*} [group G] (H : add_subgroup (additive G)) : subgroup G := { inv_mem' := H.neg_mem', .. submonoid.of_add_submonoid H.to_add_submonoid} /-- Map from `add_subgroup`s of `add_group G` to subgroups of `multiplicative G`. -/ def add_subgroup.to_subgroup {G : Type*} [add_group G] (H : add_subgroup G) : subgroup (multiplicative G) := { inv_mem' := H.neg_mem', .. add_submonoid.to_submonoid H.to_add_submonoid} /-- Map from subgroups of `multiplicative G` to `add_subgroup`s of `add_group G`. -/ def add_subgroup.of_subgroup {G : Type*} [add_group G] (H : subgroup (multiplicative G)) : add_subgroup G := { neg_mem' := H.inv_mem', .. add_submonoid.of_submonoid H.to_submonoid } /-- Subgroups of group `G` are isomorphic to additive subgroups of `additive G`. -/ def subgroup.add_subgroup_equiv (G : Type*) [group G] : subgroup G ≃ add_subgroup (additive G) := { to_fun := subgroup.to_add_subgroup, inv_fun := subgroup.of_add_subgroup, left_inv := λ x, by cases x; refl, right_inv := λ x, by cases x; refl } namespace subgroup @[to_additive] instance : has_coe (subgroup G) (set G) := { coe := subgroup.carrier } @[simp, to_additive] lemma coe_to_submonoid (K : subgroup G) : (K.to_submonoid : set G) = K := rfl @[to_additive] instance : has_mem G (subgroup G) := ⟨λ m K, m ∈ (K : set G)⟩ @[to_additive] instance : has_coe_to_sort (subgroup G) := ⟨_, λ G, (G : Type*)⟩ @[simp, norm_cast, to_additive] lemma mem_coe {K : subgroup G} [g : G] : g ∈ (K : set G) ↔ g ∈ K := iff.rfl @[simp, norm_cast, to_additive] lemma coe_coe (K : subgroup G) : ↥(K : set G) = K := rfl attribute [norm_cast] add_subgroup.mem_coe attribute [norm_cast] add_subgroup.coe_coe @[to_additive] instance is_subgroup (K : subgroup G) : is_subgroup (K : set G) := { one_mem := K.one_mem', mul_mem := K.mul_mem', inv_mem := K.inv_mem' } end subgroup @[to_additive] protected lemma subgroup.exists {K : subgroup G} {p : K → Prop} : (∃ x : K, p x) ↔ ∃ x ∈ K, p ⟨x, ‹x ∈ K›⟩ := set_coe.exists @[to_additive] protected lemma subgroup.forall {K : subgroup G} {p : K → Prop} : (∀ x : K, p x) ↔ ∀ x ∈ K, p ⟨x, ‹x ∈ K›⟩ := set_coe.forall namespace subgroup variables (H K : subgroup G) /-- Copy of a subgroup with a new `carrier` equal to the old one. Useful to fix definitional equalities.-/ @[to_additive "Copy of an additive subgroup with a new `carrier` equal to the old one. Useful to fix definitional equalities"] protected def copy (K : subgroup G) (s : set G) (hs : s = K) : subgroup G := { carrier := s, one_mem' := hs.symm ▸ K.one_mem', mul_mem' := hs.symm ▸ K.mul_mem', inv_mem' := hs.symm ▸ K.inv_mem' } /- Two subgroups are equal if the underlying set are the same. -/ @[to_additive "Two `add_group`s are equal if the underlying subsets are equal."] theorem ext' {H K : subgroup G} (h : (H : set G) = K) : H = K := by { cases H, cases K, congr, exact h } /- Two subgroups are equal if and only if the underlying subsets are equal. -/ @[to_additive "Two `add_subgroup`s are equal if and only if the underlying subsets are equal."] protected theorem ext'_iff {H K : subgroup G} : H = K ↔ (H : set G) = K := ⟨λ h, h ▸ rfl, ext'⟩ /-- Two subgroups are equal if they have the same elements. -/ @[ext, to_additive "Two `add_subgroup`s are equal if they have the same elements."] theorem ext {H K : subgroup G} (h : ∀ x, x ∈ H ↔ x ∈ K) : H = K := ext' $ set.ext h attribute [ext] subgroup.ext /-- A subgroup contains the group's 1. -/ @[to_additive "An `add_subgroup` contains the group's 0."] theorem one_mem : (1 : G) ∈ H := H.one_mem' /-- A subgroup is closed under multiplication. -/ @[to_additive "An `add_subgroup` is closed under addition."] theorem mul_mem {x y : G} : x ∈ H → y ∈ H → x * y ∈ H := λ hx hy, H.mul_mem' hx hy /-- A subgroup is closed under inverse. -/ @[to_additive "An `add_subgroup` is closed under inverse."] theorem inv_mem {x : G} : x ∈ H → x⁻¹ ∈ H := λ hx, H.inv_mem' hx /-- Product of a list of elements in a subgroup is in the subgroup. -/ @[to_additive "Sum of a list of elements in an `add_subgroup` is in the `add_subgroup`."] lemma list_prod_mem {l : list G} : (∀ x ∈ l, x ∈ K) → l.prod ∈ K := K.to_submonoid.list_prod_mem /-- Product of a multiset of elements in a subgroup of a `comm_group` is in the subgroup. -/ @[to_additive "Sum of a multiset of elements in an `add_subgroup` of an `add_comm_group` is in the `add_subgroup`."] lemma multiset_prod_mem {G} [comm_group G] (K : subgroup G) (g : multiset G) : (∀ a ∈ g, a ∈ K) → g.prod ∈ K := K.to_submonoid.multiset_prod_mem g /-- Product of elements of a subgroup of a `comm_group` indexed by a `finset` is in the subgroup. -/ @[to_additive "Sum of elements in an `add_subgroup` of an `add_comm_group` indexed by a `finset` is in the `add_subgroup`."] lemma prod_mem {G : Type*} [comm_group G] (K : subgroup G) {ι : Type*} {t : finset ι} {f : ι → G} (h : ∀ c ∈ t, f c ∈ K) : t.prod f ∈ K := K.to_submonoid.prod_mem h lemma pow_mem {x : G} (hx : x ∈ K) : ∀ n : ℕ, x ^ n ∈ K := K.to_submonoid.pow_mem hx lemma gpow_mem {x : G} (hx : x ∈ K) : ∀ n : ℤ, x ^ n ∈ K | (int.of_nat n) := pow_mem _ hx n | -[1+ n] := K.inv_mem $ K.pow_mem hx n.succ /-- A subgroup of a group inherits a multiplication. -/ @[to_additive "An `add_subgroup` of an `add_group` inherits an addition."] instance has_mul : has_mul H := H.to_submonoid.has_mul /-- A subgroup of a group inherits a 1. -/ @[to_additive "An `add_subgroup` of an `add_group` inherits a zero."] instance has_one : has_one H := H.to_submonoid.has_one /-- A subgroup of a group inherits an inverse. -/ @[to_additive "A `add_subgroup` of a `add_group` inherits an inverse."] instance has_inv : has_inv H := ⟨λ a, ⟨a⁻¹, H.inv_mem a.2⟩⟩ @[simp, to_additive] lemma coe_mul (x y : H) : (↑(x * y) : G) = ↑x * ↑y := rfl @[simp, to_additive] lemma coe_one : ((1 : H) : G) = 1 := rfl @[simp, to_additive] lemma coe_inv (x : H) : ((↑x)⁻¹ : G) = ↑(x⁻¹) := rfl /-- A subgroup of a group inherits a group structure. -/ @[to_additive to_add_group "An `add_subgroup` of an `add_group` inherits an `add_group` structure."] instance to_group {G : Type*} [group G] (H : subgroup G) : group H := { inv := has_inv.inv, mul_left_inv := λ x, subtype.eq $ mul_left_inv x, .. H.to_submonoid.to_monoid } /-- A subgroup of a `comm_group` is a `comm_group`. -/ @[to_additive to_add_comm_group "An `add_subgroup` of an `add_comm_group` is an `add_comm_group`."] instance to_comm_group {G : Type*} [comm_group G] (H : subgroup G) : comm_group H := { mul_comm := λ _ _, subtype.eq $ mul_comm _ _, .. H.to_group} /-- The natural group hom from a subgroup of group `G` to `G`. -/ @[to_additive "The natural group hom from an `add_subgroup` of `add_group` `G` to `G`."] def subtype : H →* G := ⟨coe, rfl, λ _ _, rfl⟩ @[simp, to_additive] theorem coe_subtype : ⇑H.subtype = coe := rfl @[to_additive] instance : has_le (subgroup G) := ⟨λ H K, ∀ ⦃x⦄, x ∈ H → x ∈ K⟩ @[to_additive] lemma le_def {H K : subgroup G} : H ≤ K ↔ ∀ ⦃x : G⦄, x ∈ H → x ∈ K := iff.rfl @[simp, to_additive] lemma coe_subset_coe {H K : subgroup G} : (H : set G) ⊆ K ↔ H ≤ K := iff.rfl @[to_additive] instance : partial_order (subgroup G) := { le := (≤), .. partial_order.lift (coe : subgroup G → set G) (λ a b, ext') infer_instance } /-- The subgroup `G` of the group `G`. -/ @[to_additive "The `add_subgroup G` of the `add_group G`."] instance : has_top (subgroup G) := ⟨{ inv_mem' := λ _ _, set.mem_univ _ , .. (⊤ : submonoid G) }⟩ /-- The trivial subgroup `{1}` of an group `G`. -/ @[to_additive "The trivial `add_subgroup` `{0}` of an `add_group` `G`."] instance : has_bot (subgroup G) := ⟨{ inv_mem' := λ _, by simp *, .. (⊥ : submonoid G) }⟩ @[to_additive] instance : inhabited (subgroup G) := ⟨⊥⟩ @[simp, to_additive] lemma mem_bot {x : G} : x ∈ (⊥ : subgroup G) ↔ x = 1 := set.mem_singleton_iff @[simp, to_additive] lemma mem_top (x : G) : x ∈ (⊤ : subgroup G) := set.mem_univ x @[simp, to_additive] lemma coe_top : ((⊤ : subgroup G) : set G) = set.univ := rfl @[simp, to_additive] lemma coe_bot : ((⊥ : subgroup G) : set G) = {1} := rfl /-- The inf of two subgroups is their intersection. -/ @[to_additive "The inf of two `add_subgroups`s is their intersection."] instance : has_inf (subgroup G) := ⟨λ H₁ H₂, { inv_mem' := λ _ ⟨hx, hx'⟩, ⟨H₁.inv_mem hx, H₂.inv_mem hx'⟩, .. H₁.to_submonoid ⊓ H₂.to_submonoid }⟩ @[simp, to_additive] lemma coe_inf (p p' : subgroup G) : ((p ⊓ p' : subgroup G) : set G) = p ∩ p' := rfl @[simp, to_additive] lemma mem_inf {p p' : subgroup G} {x : G} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl @[to_additive] instance : has_Inf (subgroup G) := ⟨λ s, { inv_mem' := λ x hx, set.mem_bInter $ λ i h, i.inv_mem (by apply set.mem_bInter_iff.1 hx i h), .. (⨅ S ∈ s, subgroup.to_submonoid S).copy (⋂ S ∈ s, ↑S) (by simp) }⟩ @[simp, to_additive] lemma coe_Inf (H : set (subgroup G)) : ((Inf H : subgroup G) : set G) = ⋂ s ∈ H, ↑s := rfl attribute [norm_cast] coe_Inf add_subgroup.coe_Inf @[simp, to_additive] lemma mem_Inf {S : set (subgroup G)} {x : G} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_bInter_iff /-- Subgroups of a group form a complete lattice. -/ @[to_additive "The `add_subgroup`s of an `add_group` form a complete lattice."] instance : complete_lattice (subgroup G) := { bot := (⊥), bot_le := λ S x hx, (mem_bot.1 hx).symm ▸ S.one_mem, top := (⊤), le_top := λ S x hx, mem_top x, inf := (⊓), le_inf := λ a b c ha hb x hx, ⟨ha hx, hb hx⟩, inf_le_left := λ a b x, and.left, inf_le_right := λ a b x, and.right, .. complete_lattice_of_Inf (subgroup G) $ λ s, is_glb.of_image (λ H K, show (H : set G) ≤ K ↔ H ≤ K, from coe_subset_coe) is_glb_binfi } /-- The `subgroup` generated by a set. -/ @[to_additive "The `add_subgroup` generated by a set"] def closure (k : set G) : subgroup G := Inf {K | k ⊆ K} variable {k : set G} @[to_additive] lemma mem_closure {x : G} : x ∈ closure k ↔ ∀ K : subgroup G, k ⊆ K → x ∈ K := mem_Inf /-- The subgroup generated by a set includes the set. -/ @[simp, to_additive "The `add_subgroup` generated by a set includes the set."] lemma subset_closure : k ⊆ closure k := λ x hx, mem_closure.2 $ λ K hK, hK hx open set /-- A subgroup `K` includes `closure k` if and only if it includes `k`. -/ @[simp, to_additive "An additive subgroup `K` includes `closure k` if and only if it includes `k`"] lemma closure_le : closure k ≤ K ↔ k ⊆ K := ⟨subset.trans subset_closure, λ h, Inf_le h⟩ @[to_additive] lemma closure_eq_of_le (h₁ : k ⊆ K) (h₂ : K ≤ closure k) : closure k = K := le_antisymm ((closure_le $ K).2 h₁) h₂ /-- An induction principle for closure membership. If `p` holds for `1` and all elements of `k`, and is preserved under multiplication and inverse, then `p` holds for all elements of the closure of `k`. -/ @[to_additive "An induction principle for additive closure membership. If `p` holds for `0` and all elements of `k`, and is preserved under addition and isvers, then `p` holds for all elements of the additive closure of `k`."] lemma closure_induction {p : G → Prop} {x} (h : x ∈ closure k) (Hk : ∀ x ∈ k, p x) (H1 : p 1) (Hmul : ∀ x y, p x → p y → p (x * y)) (Hinv : ∀ x, p x → p x⁻¹) : p x := (@closure_le _ _ ⟨p, H1, Hmul, Hinv⟩ _).2 Hk h attribute [elab_as_eliminator] subgroup.closure_induction add_subgroup.closure_induction variable (G) /-- `closure` forms a Galois insertion with the coercion to set. -/ @[to_additive "`closure` forms a Galois insertion with the coercion to set."] protected def gi : galois_insertion (@closure G _) coe := { choice := λ s _, closure s, gc := λ s t, @closure_le _ _ t s, le_l_u := λ s, subset_closure, choice_eq := λ s h, rfl } variable {G} /-- Subgroup closure of a set is monotone in its argument: if `h ⊆ k`, then `closure h ≤ closure k`. -/ @[to_additive "Additive subgroup closure of a set is monotone in its argument: if `h ⊆ k`, then `closure h ≤ closure k`"] lemma closure_mono ⦃h k : set G⦄ (h' : h ⊆ k) : closure h ≤ closure k := (subgroup.gi G).gc.monotone_l h' /-- Closure of a subgroup `K` equals `K`. -/ @[simp, to_additive "Additive closure of an additive subgroup `K` equals `K`"] lemma closure_eq : closure (K : set G) = K := (subgroup.gi G).l_u_eq K @[simp, to_additive] lemma closure_empty : closure (∅ : set G) = ⊥ := (subgroup.gi G).gc.l_bot @[simp, to_additive] lemma closure_univ : closure (univ : set G) = ⊤ := @coe_top G _ ▸ closure_eq ⊤ @[to_additive] lemma closure_union (s t : set G) : closure (s ∪ t) = closure s ⊔ closure t := (subgroup.gi G).gc.l_sup @[to_additive] lemma closure_Union {ι} (s : ι → set G) : closure (⋃ i, s i) = ⨆ i, closure (s i) := (subgroup.gi G).gc.l_supr /-- The subgroup generated by an element of a group equals the set of integer number powers of the element. -/ lemma mem_closure_singleton {x y : G} : y ∈ closure ({x} : set G) ↔ ∃ n : ℤ, x ^ n = y := begin refine ⟨λ hy, closure_induction hy _ _ _ _, λ ⟨n, hn⟩, hn ▸ gpow_mem _ (subset_closure $ mem_singleton x) n⟩, { intros y hy, rw [eq_of_mem_singleton hy], exact ⟨1, gpow_one x⟩ }, { exact ⟨0, rfl⟩ }, { rintros _ _ ⟨n, rfl⟩ ⟨m, rfl⟩, exact ⟨n + m, gpow_add x n m⟩ }, rintros _ ⟨n, rfl⟩, exact ⟨-n, gpow_neg x n⟩ end @[to_additive] lemma mem_supr_of_directed {ι} [hι : nonempty ι] {K : ι → subgroup G} (hK : directed (≤) K) {x : G} : x ∈ (supr K : subgroup G) ↔ ∃ i, x ∈ K i := begin refine ⟨_, λ ⟨i, hi⟩, (le_def.1 $ le_supr K i) hi⟩, suffices : x ∈ closure (⋃ i, (K i : set G)) → ∃ i, x ∈ K i, by simpa only [closure_Union, closure_eq (K _)] using this, refine (λ hx, closure_induction hx (λ _, mem_Union.1) _ _ _), { exact hι.elim (λ i, ⟨i, (K i).one_mem⟩) }, { rintros x y ⟨i, hi⟩ ⟨j, hj⟩, rcases hK i j with ⟨k, hki, hkj⟩, exact ⟨k, (K k).mul_mem (hki hi) (hkj hj)⟩ }, rintros _ ⟨i, hi⟩, exact ⟨i, inv_mem (K i) hi⟩ end @[to_additive] lemma mem_Sup_of_directed_on {K : set (subgroup G)} (Kne : K.nonempty) (hK : directed_on (≤) K) {x : G} : x ∈ Sup K ↔ ∃ s ∈ K, x ∈ s := begin haveI : nonempty K := Kne.to_subtype, rw [Sup_eq_supr, supr_subtype', mem_supr_of_directed, subtype.exists], exact (directed_on_iff_directed _).1 hK end variables {N : Type*} [group N] {P : Type*} [group P] /-- The preimage of a subgroup along a monoid homomorphism is a subgroup. -/ @[to_additive "The preimage of an `add_subgroup` along an `add_monoid` homomorphism is an `add_subgroup`."] def comap {N : Type*} [group N] (f : G →* N) (H : subgroup N) : subgroup G := { carrier := (f ⁻¹' H), inv_mem' := λ a ha, show f a⁻¹ ∈ H, by rw f.map_inv; exact H.inv_mem ha, .. H.to_submonoid.comap f } @[simp, to_additive] lemma coe_comap (K : subgroup N) (f : G →* N) : (K.comap f : set G) = f ⁻¹' K := rfl @[simp, to_additive] lemma mem_comap {K : subgroup N} {f : G →* N} {x : G} : x ∈ K.comap f ↔ f x ∈ K := iff.rfl @[to_additive] lemma comap_comap (K : subgroup P) (g : N →* P) (f : G →* N) : (K.comap g).comap f = K.comap (g.comp f) := rfl /-- The image of a subgroup along a monoid homomorphism is a subgroup. -/ @[to_additive "The image of an `add_subgroup` along an `add_monoid` homomorphism is an `add_subgroup`."] def map (f : G →* N) (H : subgroup G) : subgroup N := { carrier := (f '' H), inv_mem' := by { rintros _ ⟨x, hx, rfl⟩, exact ⟨x⁻¹, H.inv_mem hx, f.map_inv x⟩ }, .. H.to_submonoid.map f } @[simp, to_additive] lemma coe_map (f : G →* N) (K : subgroup G) : (K.map f : set N) = f '' K := rfl @[simp, to_additive] lemma mem_map {f : G →* N} {K : subgroup G} {y : N} : y ∈ K.map f ↔ ∃ x ∈ K, f x = y := mem_image_iff_bex @[to_additive] lemma map_map (g : N →* P) (f : G →* N) : (K.map f).map g = K.map (g.comp f) := ext' $ image_image _ _ _ @[to_additive] lemma map_le_iff_le_comap {f : G →* N} {K : subgroup G} {H : subgroup N} : K.map f ≤ H ↔ K ≤ H.comap f := image_subset_iff @[to_additive] lemma gc_map_comap (f : G →* N) : galois_connection (map f) (comap f) := λ _ _, map_le_iff_le_comap @[to_additive] lemma map_sup (H K : subgroup G) (f : G →* N) : (H ⊔ K).map f = H.map f ⊔ K.map f := (gc_map_comap f).l_sup @[to_additive] lemma map_supr {ι : Sort*} (f : G →* N) (s : ι → subgroup G) : (supr s).map f = ⨆ i, (s i).map f := (gc_map_comap f).l_supr @[to_additive] lemma comap_inf (H K : subgroup N) (f : G →* N) : (H ⊓ K).comap f = H.comap f ⊓ K.comap f := (gc_map_comap f).u_inf @[to_additive] lemma comap_infi {ι : Sort*} (f : G →* N) (s : ι → subgroup N) : (infi s).comap f = ⨅ i, (s i).comap f := (gc_map_comap f).u_infi @[simp, to_additive] lemma map_bot (f : G →* N) : (⊥ : subgroup G).map f = ⊥ := (gc_map_comap f).l_bot @[simp, to_additive] lemma comap_top (f : G →* N) : (⊤ : subgroup N).comap f = ⊤ := (gc_map_comap f).u_top /-- Given `subgroup`s `H`, `K` of groups `G`, `N` respectively, `H × K` as a subgroup of `G × N`. -/ @[to_additive prod "Given `add_subgroup`s `H`, `K` of `add_group`s `A`, `B` respectively, `H × K` as an `add_subgroup` of `A × B`."] def prod (H : subgroup G) (K : subgroup N) : subgroup (G × N) := { inv_mem' := λ _ hx, ⟨H.inv_mem' hx.1, K.inv_mem' hx.2⟩, .. submonoid.prod H.to_submonoid K.to_submonoid} @[to_additive coe_prod] lemma coe_prod (H : subgroup G) (K : subgroup N) : (H.prod K : set (G × N)) = (H : set G).prod (K : set N) := rfl @[to_additive mem_prod] lemma mem_prod {H : subgroup G} {K : subgroup N} {p : G × N} : p ∈ H.prod K ↔ p.1 ∈ H ∧ p.2 ∈ K := iff.rfl @[to_additive prod_mono] lemma prod_mono : ((≤) ⇒ (≤) ⇒ (≤)) (@prod G _ N _) (@prod G _ N _) := λ s s' hs t t' ht, set.prod_mono hs ht @[to_additive prod_mono_right] lemma prod_mono_right (K : subgroup G) : monotone (λ t : subgroup N, K.prod t) := prod_mono (le_refl K) @[to_additive prod_mono_left] lemma prod_mono_left (H : subgroup N) : monotone (λ K : subgroup G, K.prod H) := λ s₁ s₂ hs, prod_mono hs (le_refl H) @[to_additive prod_top] lemma prod_top (K : subgroup G) : K.prod (⊤ : subgroup N) = K.comap (monoid_hom.fst G N) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_fst] @[to_additive top_prod] lemma top_prod (H : subgroup N) : (⊤ : subgroup G).prod H = H.comap (monoid_hom.snd G N) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_snd] @[simp, to_additive top_prod_top] lemma top_prod_top : (⊤ : subgroup G).prod (⊤ : subgroup N) = ⊤ := (top_prod _).trans $ comap_top _ @[to_additive] lemma bot_prod_bot : (⊥ : subgroup G).prod (⊥ : subgroup N) = ⊥ := ext' $ by simp [coe_prod, prod.one_eq_mk] /-- Product of subgroups is isomorphic to their product as groups. -/ @[to_additive prod_equiv "Product of additive subgroups is isomorphic to their product as additive groups"] def prod_equiv (H : subgroup G) (K : subgroup N) : H.prod K ≃* H × K := { map_mul' := λ x y, rfl, .. equiv.set.prod ↑H ↑K } end subgroup namespace add_subgroup open set lemma gsmul_mem (H : add_subgroup A) {x : A} (hx : x ∈ H) : ∀ n : ℤ, gsmul n x ∈ H | (int.of_nat n) := add_submonoid.smul_mem H.to_add_submonoid hx n | -[1+ n] := H.neg_mem' $ H.add_mem hx $ add_submonoid.smul_mem H.to_add_submonoid hx n /-- The `add_subgroup` generated by an element of an `add_group` equals the set of natural number multiples of the element. -/ lemma mem_closure_singleton {x y : A} : y ∈ closure ({x} : set A) ↔ ∃ n : ℤ, gsmul n x = y := begin refine ⟨λ hy, closure_induction hy _ _ _ _, λ ⟨n, hn⟩, hn ▸ gsmul_mem _ (subset_closure $ mem_singleton x) n⟩, { intros y hy, rw [eq_of_mem_singleton hy], exact ⟨1, one_gsmul x⟩ }, { exact ⟨0, rfl⟩ }, { rintros _ _ ⟨n, rfl⟩ ⟨m, rfl⟩, exact ⟨n + m, add_gsmul x n m⟩ }, { rintros _ ⟨n, rfl⟩, refine ⟨-n, neg_gsmul x n⟩ } end end add_subgroup namespace monoid_hom variables {N : Type*} {P : Type*} [group N] [group P] (K : subgroup G) open subgroup /-- The range of a monoid homomorphism from a group is a subgroup. -/ @[to_additive "The range of an `add_monoid_hom` from an `add_group` is an `add_subgroup`."] def range (f : G →* N) : subgroup N := (⊤ : subgroup G).map f @[simp, to_additive] lemma coe_range (f : G →* N) : (f.range : set N) = set.range f := set.image_univ @[simp, to_additive] lemma mem_range {f : G →* N} {y : N} : y ∈ f.range ↔ ∃ x, f x = y := by simp [range] @[to_additive] lemma map_range (g : N →* P) (f : G →* N) : f.range.map g = (g.comp f).range := (⊤ : subgroup G).map_map g f @[to_additive] lemma range_top_iff_surjective {N} [group N] {f : G →* N} : f.range = (⊤ : subgroup N) ↔ function.surjective f := subgroup.ext'_iff.trans $ iff.trans (by rw [coe_range, coe_top]) set.range_iff_surjective /-- The range of a surjective monoid homomorphism is the whole of the codomain. -/ @[to_additive "The range of a surjective `add_monoid` homomorphism is the whole of the codomain."] lemma rang_top_of_surjective {N} [group N] (f : G →* N) (hf : function.surjective f) : f.range = (⊤ : subgroup N) := range_top_iff_surjective.2 hf /-- The multiplicative kernel of a monoid homomorphism is the subgroup of elements `x : G` such that `f x = 1` -/ @[to_additive "The additive kernel of an `add_monoid` homomorphism is the `add_subgroup` of elements such that `f x = 0`"] def ker (f : G →* N) := (⊥ : subgroup N).comap f @[to_additive] lemma mem_ker {f : G →* N} {x : G} : x ∈ f.ker ↔ f x = 1 := subgroup.mem_bot @[to_additive] lemma comap_ker (g : N →* P) (f : G →* N) : g.ker.comap f = (g.comp f).ker := rfl /-- The subgroup of elements `x : G` such that `f x = g x` -/ @[to_additive "The additive subgroup of elements `x : G` such that `f x = g x`"] def eq_locus (f g : G →* N) : subgroup G := { inv_mem' := λ x (hx : f x = g x), show f x⁻¹ = g x⁻¹, by rw [f.map_inv, g.map_inv, hx], .. eq_mlocus f g} /-- If two monoid homomorphisms are equal on a set, then they are equal on its subgroup closure. -/ @[to_additive] lemma eq_on_closure {f g : G →* N} {s : set G} (h : set.eq_on f g s) : set.eq_on f g (closure s) := show closure s ≤ f.eq_locus g, from (closure_le _).2 h @[to_additive] lemma eq_of_eq_on_top {f g : G →* N} (h : set.eq_on f g (⊤ : subgroup G)) : f = g := ext $ λ x, h trivial @[to_additive] lemma eq_of_eq_on_dense {s : set G} (hs : closure s = ⊤) {f g : G →* N} (h : s.eq_on f g) : f = g := eq_of_eq_on_top $ hs ▸ eq_on_closure h @[to_additive] lemma gclosure_preimage_le (f : G →* N) (s : set N) : closure (f ⁻¹' s) ≤ (closure s).comap f := (closure_le _).2 $ λ x hx, by rw [mem_coe, mem_comap]; exact subset_closure hx /-- The image under a monoid homomorphism of the subgroup generated by a set equals the subgroup generated by the image of the set. -/ @[to_additive "The image under an `add_monoid` hom of the `add_subgroup` generated by a set equals the `add_subgroup` generated by the image of the set."] lemma map_closure (f : G →* N) (s : set G) : (closure s).map f = closure (f '' s) := le_antisymm (map_le_iff_le_comap.2 $ le_trans (closure_mono $ set.subset_preimage_image f s) (gclosure_preimage_le _ _)) ((closure_le _).2 $ set.image_subset _ subset_closure) end monoid_hom namespace mul_equiv variables {H K : subgroup G} /-- Makes the identity isomorphism from a proof two subgroups of a multiplicative group are equal. -/ @[to_additive add_subgroup_congr "Makes the identity additive isomorphism from a proof two subgroups of an additive group are equal."] def subgroup_congr (h : H = K) : H ≃* K := { map_mul' := λ _ _, rfl, ..equiv.set_congr $ subgroup.ext'_iff.1 h } end mul_equiv
5fe417c72d5db6d3b5dea0e6bee59391e559412c
5a5e1bb8063d7934afac91f30aa17c715821040b
/lean3SOS/src/float/round.lean
c1c8ae2d6f0a7a9eb08f7b9ba3efdbbd088a7cd3
[]
no_license
ramonfmir/leanSOS
1883392d73710db5c6e291a2abd03a6c5b44a42b
14b50713dc887f6d408b7b2bce1f8af5bb619958
refs/heads/main
1,683,348,826,105
1,622,056,982,000
1,622,056,982,000
341,232,766
1
0
null
null
null
null
UTF-8
Lean
false
false
1,108
lean
import float.basic -- Following https://isabelle.in.tum.de/website-Isabelle2013/dist/library/HOL/HOL-Library/Float.html variable (prec : ℕ) def round_up (x : ℚ) : 𝔽 := float.mk (⌈x * 2 ^ prec⌉) (-prec) def round_down (x : ℚ) : 𝔽 := float.mk (⌊x * 2 ^ prec⌋) (-prec) lemma round_up_zero : round_up prec 0 = 0 := by { apply quotient.sound, show to_rat _ = _, simp [to_rat], } lemma round_down_zero : round_down prec 0 = 0 := by { apply quotient.sound, show to_rat _ = _, simp [to_rat], } lemma round_up_diff_round_down (x : ℚ) : round_up prec x - round_down prec x ≤ float.mk 1 (-prec) := begin show float.eval _ ≤ _, simp [float.eval_sub, round_up, round_down, float.eval_mk], suffices hsuff : ↑(⌈x * 2 ^ prec⌉ - ⌊x * 2 ^ prec⌋) * ((2 : ℚ) ^ prec)⁻¹ ≤ 1 * ((2 : ℚ) ^ prec)⁻¹, { push_cast at hsuff, rw [sub_mul, one_mul] at hsuff, exact hsuff, }, have h : 0 < ((2 : ℚ) ^ prec)⁻¹, { norm_num, }, rw [mul_le_mul_right h], show _ ≤ ↑(1 : ℤ), simp [coe], rw [sub_le_iff_le_add, add_comm], exact ceil_le_floor_add_one _, end
fd087655c6c159d9ffc311ef5669d405d993d227
da3a76c514d38801bae19e8a9e496dc31f8e5866
/library/init/meta/lean/parser.lean
72f779a4e1dd9c4f1c60104f671567a6541a83a7
[ "Apache-2.0" ]
permissive
cipher1024/lean
270c1ac5781e6aee12f5c8d720d267563a164beb
f5cbdff8932dd30c6dd8eec68f3059393b4f8b3a
refs/heads/master
1,611,223,459,029
1,487,566,573,000
1,487,566,573,000
83,356,543
0
0
null
1,488,229,336,000
1,488,229,336,000
null
UTF-8
Lean
false
false
2,306
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich -/ prelude import init.data.option.basic init.category.monad init.category.alternative import init.meta.pexpr init.meta.interaction_monad namespace lean -- TODO: make inspectable (and pure) meta constant parser_state : Type meta constant parser_state.cur_pos : parser_state → pos @[reducible] meta def parser := interaction_monad parser_state @[reducible] meta def parser_result := interaction_monad.result parser_state open interaction_monad open interaction_monad.result namespace parser /-- Make sure the next token is an identifier, consume it, and produce the quoted name `t, where t is the identifier. -/ meta constant ident : parser name /-- Check that the next token is `tk` and consume it. `tk` must be a registered token. -/ meta constant tk (tk : string) : parser unit /-- Parse an unelaborated expression using the given right-binding power. The expression may contain antiquotations (`%%e`). -/ meta constant qexpr (rbp := nat.of_num std.prec.max) : parser pexpr /-- Return the current parser position without consuming any input. -/ meta def cur_pos : parser pos := λ s, success (parser_state.cur_pos s) s meta def parser_orelse {α : Type} (p₁ p₂ : parser α) : parser α := λ s, let pos₁ := parser_state.cur_pos s in result.cases_on (p₁ s) success (λ e₁ ref₁ s', let pos₂ := parser_state.cur_pos s' in if pos₁ ≠ pos₂ then exception e₁ ref₁ s' else result.cases_on (p₂ s) success exception) meta instance : alternative parser := ⟨@interaction_monad_fmap parser_state, (λ α a s, success a s), (@fapp _ _), @interaction_monad.failed parser_state, @parser_orelse⟩ -- TODO: move meta def {u v} many {f : Type u → Type v} [monad f] [alternative f] {a : Type u} : f a → f (list a) | x := (do y ← x, ys ← many x, return $ y::ys) <|> pure list.nil local postfix ?:100 := optional local notation p ` ?: `:100 d := (λ o, option.get_or_else o d) <$> p? local postfix * := many meta def sep_by {α : Type} : string → parser α → parser (list α) | s p := (list.cons <$> p <*> (tk s *> p)*) ?: [] end parser end lean
8775366bcf0e023e18d5cb46e4b3a1a67fb9aa11
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/tests/elabissues/vars.lean
dc9e8375be9b51a95c6bcee74d49755f1f93fb73
[ "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
1,166
lean
def f1 {α} [ToString α] (a : α) : String := -- works ">> " ++ toString a -- Moving `{α} [ToString α]` to a `variables` break the example variables {α} [ToString α] def f2 (a : α) : String := ">> " ++ toString a class Dummy (α : Type) := (val : α) /- The following fails because `variables {α : Type _} [Dummy α]` is processed as `variable {α : Type _} variable [Dummy α]` The first command elaborates `α` as `variable {α : Type u_1}` where `u_1` is a fresh metavariable. That is, in Lean3, metavariables are resolved before the end of the command. -/ variables {α : Type _} [Dummy α] def f3 {α : Type _} [Dummy α] : α := -- works Dummy.val α /- In Lean4, we should use a different approach. We keep a metavariable context in the command elaborator. Before, a declaration `D` is sent to the kernel we resolve the metavariables occuring in `D`. We must implement a MetavarContext GC to make sure the metavariable context does not keep increasing. That is, after a declaration is sent to the kernel, we visit all variables in the elaborator context and instantiate assigned metavariables. Then, we delete all assigned metavariables. -/
b5d2b1298c473898baaa5992a8c3be38ab999298
3618c6e11aa822fd542440674dfb9a7b9921dba0
/scratch/main.lean
43872a5313989861e9bac0430b810ab9f8089ea5
[]
no_license
ChrisHughes24/single_relation
99ceedcc02d236ce46d6c65d72caa669857533c5
057e157a59de6d0e43b50fcb537d66792ec20450
refs/heads/master
1,683,652,062,698
1,683,360,089,000
1,683,360,089,000
279,346,432
0
0
null
null
null
null
UTF-8
Lean
false
false
3,587
lean
import .exp_sum_eq_zero import .base_case import .choose_letters import .no_exp_sum_zero import .golf open semidirect_product -- Did I take into account the case when T is everything in r? -- This rarely happens right? Unless it happens at the start -- Proof assumes wlog every element of S appears in r, where is this used? meta def main : Π ⦃ι : Type⦄ [decidable_eq ι] [inhabited ι] (r : free_group ι) (T : set ι) [decidable_pred T], by exactI solver r T := λ ι _ _ r T _ w, match r with | ⟨[], _⟩ := by exactI if w ∈ closure_var T then some (inr w) else none | ⟨[⟨r₁, r₂⟩], _⟩ := by exactI base_case_solver T r₁ r₂ w | r := by exactI let vars_w := vars w in if vars_w.all (λ i, i ∈ T) then (some (inr w)) else let (c₁, cyc_r) := cyclically_reduce r in if (vars cyc_r).any (λ i, i ∉ vars_w ∧ i ∉ T) then none else let ((t, α), (x, β)) := choose_t_and_x cyc_r T in P.change_r c₁ <$> if α = 1 then exp_sum_eq_zero T t x (λ r T _, by exactI main r T) cyc_r w else (exp_sum_ne_zero T t x α β (λ r T _, by exactI main r T) cyc_r w) end set_option profiler true open free_group #eval ((main (of 0 * of 1) ∅ (of 0 * (of 1) * (of 0)⁻¹ * (of 1)⁻¹)).is_some) #eval (main (of 0 * of 1 * (of 0)⁻¹ * (of 1)⁻¹) ∅ (of 0 ^ 2 * (of 1)⁻¹ ^ 2 * (of 0)⁻¹ ^ 2 * (of 1) ^ 2)).iget.left #eval --P.lhs (of "a" * of "b" * (of "a")⁻¹ * (of "b")⁻¹) --free_group.map (golf_single (of "a" * of "b" * (of "a")⁻¹ * (of "b")⁻¹)) ((main (of "a" * of "b" * (of "a")⁻¹ * (of "b")⁻¹) ∅ (of "a" ^ 2 * (of "b") * (of "a")⁻¹ ^ 2 * (of "b")⁻¹)).iget) #eval let r := of 0 * of 1 * (of 0)^(-3 : ℤ) * (of 1)^4 in (main r ∅ (of 1 * r * (of 1)⁻¹ * r⁻¹ * (of 0) * r⁻¹ * (of 0)⁻¹ * r)).iget.left #eval let r := of 0 * of 1 * (of 0)^(-100 : ℤ) * (of 1)^4 in free_group.map (golf_single r) ((main r ∅ (of 1 * r * (of 1)⁻¹ * r⁻¹ * (of 0)⁻¹ * r⁻¹ * (of 0) * r)).iget.left) #eval let r := of 0 * of 1 * (of 0)^(-100 : ℤ) * (of 1)^(4 : ℤ) in (P.lhs r (main r ∅ (of 1 * r * (of 1)⁻¹ * r⁻¹ * (of 0)⁻¹ * r⁻¹ * (of 0) * r)).iget = (of 1 * r * (of 1)⁻¹ * r⁻¹ * (of 0)⁻¹ * r⁻¹ * (of 0) * r) : bool) #eval let r := of 0 * of 1 * (of 0)^(-1 : ℤ) * (of 1)^(1 : ℤ) in (P.lhs r (main r ∅ (of 1 * r * (of 1)⁻¹ * r⁻¹ * (of 0)⁻¹ * r⁻¹ * (of 0) * r)).iget = (of 1 * r * (of 1)⁻¹ * r⁻¹ * (of 0)⁻¹ * r⁻¹ * (of 0) * r) : bool) #eval let r := of 0 * of 1 * (of 0)⁻¹ * (of 1) in of 1 * r * (of 1)⁻¹ * r⁻¹ * (of 0) * r⁻¹ * (of 0)⁻¹ * r #eval let r := of 0 * of 1 * (of 0)⁻¹ * (of 1) in (main r ∅ ((of 1 * r * (of 1)⁻¹ * r⁻¹ * (of 0) * r⁻¹ * (of 0)⁻¹ * r))).iget.left #eval let r := of 0 * of 1 * of 2 * of 3 in free_group.map (golf_single r) (main r ∅ (of 1 * of 2 * of 3 * of 0)).iget.left --set_option timeout 10000000000 def w : ℕ → free_group char | 0 := of 'a' | (n+1) := ((of 'b')⁻¹ * w n * of 'b')⁻¹ * of 'a' * ((of 'b')⁻¹ * w n * of 'b') --#print string.decidable_eq #eval free_group.map (golf_single (w 1 * (of 'a') ^ (-2 : ℤ))) (main (w 1 * (of 'a') ^ (-2 : ℤ)) {'a'} (w 3)).iget.left -- #eval -- let r := (of 'a' * of 'b')^2 in -- (free_group.map (golf_single r) -- (main r ∅ ((of 'a' * r⁻¹ * (of 'a')⁻¹ * r)^44)).iget.left = -- (main r ∅ ((of 'a' * r⁻¹ * (of 'a')⁻¹ * r)^44)).iget.left : bool) open multiplicative
1a6d03971a1b839244f4e51036b60fceb42849c2
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/algebraic_topology/cech_nerve.lean
4a0ce5ebc27b3ac1f2457755d9255e205a9ada45
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
10,460
lean
/- Copyright (c) 2021 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz -/ import algebraic_topology.simplicial_object import category_theory.limits.shapes.wide_pullbacks import category_theory.arrow /-! # The Čech Nerve This file provides a definition of the Čech nerve associated to an arrow, provided the base category has the correct wide pullbacks. Several variants are provided, given `f : arrow C`: 1. `f.cech_nerve` is the Čech nerve, considered as a simplicial object in `C`. 2. `f.augmented_cech_nerve` is the augmented Čech nerve, considered as an augmented simplicial object in `C`. 3. `simplicial_object.cech_nerve` and `simplicial_object.augmented_cech_nerve` are functorial versions of 1 resp. 2. -/ open category_theory open category_theory.limits noncomputable theory universes v u variables {C : Type u} [category.{v} C] namespace category_theory.arrow variables (f : arrow C) variables [∀ n : ℕ, has_wide_pullback f.right (λ i : ulift (fin (n+1)), f.left) (λ i, f.hom)] /-- The Čech nerve associated to an arrow. -/ @[simps] def cech_nerve : simplicial_object C := { obj := λ n, wide_pullback f.right (λ i : ulift (fin (n.unop.len + 1)), f.left) (λ i, f.hom), map := λ m n g, wide_pullback.lift (wide_pullback.base _) (λ i, wide_pullback.π (λ i, f.hom) $ ulift.up $ g.unop.to_preorder_hom i.down) (by tidy) } /-- The augmented Čech nerve associated to an arrow. -/ @[simps] def augmented_cech_nerve : simplicial_object.augmented C := { left := f.cech_nerve, right := f.right, hom := { app := λ i, wide_pullback.base _ } } end category_theory.arrow namespace category_theory namespace simplicial_object variables [∀ (n : ℕ) (f : arrow C), has_wide_pullback f.right (λ i : ulift (fin (n+1)), f.left) (λ i, f.hom)] /-- The Čech nerve construction, as a functor from `arrow C`. -/ @[simps] def cech_nerve : arrow C ⥤ simplicial_object C := { obj := λ f, f.cech_nerve, map := λ f g F, { app := λ n, wide_pullback.lift (wide_pullback.base _ ≫ F.right) (λ i, wide_pullback.π _ i ≫ F.left) (λ i, by simp [← category.assoc]) }, -- tidy needs a bit of help here... map_id' := by { intros i, ext, tidy }, map_comp' := begin intros f g h F G, ext, all_goals { dsimp, simp only [category.assoc, limits.wide_pullback.lift_base, limits.wide_pullback.lift_π, limits.limit.lift_π_assoc], simpa only [← category.assoc] }, end } /-- The augmented Čech nerve construction, as a functor from `arrow C`. -/ @[simps] def augmented_cech_nerve : arrow C ⥤ simplicial_object.augmented C := { obj := λ f, f.augmented_cech_nerve, map := λ f g F, { left := cech_nerve.map F, right := F.right } } /-- A helper function used in defining the Čech adjunction. -/ @[simps] def equivalence_right_to_left (X : simplicial_object.augmented C) (F : arrow C) (G : X ⟶ F.augmented_cech_nerve) : augmented.to_arrow.obj X ⟶ F := { left := G.left.app _ ≫ wide_pullback.π (λ i, F.hom) ⟨0⟩, right := G.right, w' := begin have := G.w, apply_fun (λ e, e.app (opposite.op $ simplex_category.mk 0)) at this, tidy, end } /-- A helper function used in defining the Čech adjunction. -/ @[simps] def equivalence_left_to_right (X : simplicial_object.augmented C) (F : arrow C) (G : augmented.to_arrow.obj X ⟶ F) : X ⟶ F.augmented_cech_nerve := { left := { app := λ x, limits.wide_pullback.lift (X.hom.app _ ≫ G.right) (λ i, X.left.map (simplex_category.const x.unop i.down).op ≫ G.left) (by tidy), naturality' := begin intros x y f, ext, { dsimp, simp only [wide_pullback.lift_π, category.assoc], rw [← category.assoc, ← X.left.map_comp], refl }, { dsimp, simp only [functor.const.obj_map, nat_trans.naturality_assoc, wide_pullback.lift_base, category.assoc], erw category.id_comp } end }, right := G.right } /-- A helper function used in defining the Čech adjunction. -/ @[simps] def cech_nerve_equiv (X : simplicial_object.augmented C) (F : arrow C) : (augmented.to_arrow.obj X ⟶ F) ≃ (X ⟶ F.augmented_cech_nerve) := { to_fun := equivalence_left_to_right _ _, inv_fun := equivalence_right_to_left _ _, left_inv := begin intro A, dsimp, ext, { dsimp, erw wide_pullback.lift_π, nth_rewrite 1 ← category.id_comp A.left, congr' 1, convert X.left.map_id _, rw ← op_id, congr' 1, ext ⟨a,ha⟩, change a < 1 at ha, change 0 = a, linarith }, { refl, } end, right_inv := begin intro A, dsimp, ext _ ⟨j⟩, { dsimp, simp only [arrow.cech_nerve_map, wide_pullback.lift_π, nat_trans.naturality_assoc], erw wide_pullback.lift_π, refl }, { dsimp, erw wide_pullback.lift_base, have := A.w, apply_fun (λ e, e.app x) at this, rw nat_trans.comp_app at this, erw this, refl }, { refl } end } /-- The augmented Čech nerve construction is right adjoint to the `to_arrow` functor. -/ abbreviation cech_nerve_adjunction : (augmented.to_arrow : _ ⥤ arrow C) ⊣ augmented_cech_nerve := adjunction.mk_of_hom_equiv { hom_equiv := cech_nerve_equiv } end simplicial_object end category_theory namespace category_theory.arrow variables (f : arrow C) variables [∀ n : ℕ, has_wide_pushout f.left (λ i : ulift (fin (n+1)), f.right) (λ i, f.hom)] /-- The Čech conerve associated to an arrow. -/ @[simps] def cech_conerve : cosimplicial_object C := { obj := λ n, wide_pushout f.left (λ i : ulift (fin (n.len + 1)), f.right) (λ i, f.hom), map := λ m n g, wide_pushout.desc (wide_pushout.head _) (λ i, wide_pushout.ι (λ i, f.hom) $ ulift.up $ g.to_preorder_hom i.down) begin rintros ⟨⟨j⟩⟩, dsimp, rw [wide_pushout.arrow_ι (λ i, f.hom)], end } /-- The augmented Čech conerve associated to an arrow. -/ @[simps] def augmented_cech_conerve : cosimplicial_object.augmented C := { left := f.left, right := f.cech_conerve, hom := { app := λ i, wide_pushout.head _ } } end category_theory.arrow namespace category_theory namespace cosimplicial_object variables [∀ (n : ℕ) (f : arrow C), has_wide_pushout f.left (λ i : ulift (fin (n+1)), f.right) (λ i, f.hom)] /-- The Čech conerve construction, as a functor from `arrow C`. -/ @[simps] def cech_conerve : arrow C ⥤ cosimplicial_object C := { obj := λ f, f.cech_conerve, map := λ f g F, { app := λ n, wide_pushout.desc (F.left ≫ wide_pushout.head _) (λ i, F.right ≫ wide_pushout.ι _ i) (λ i, by { rw [←arrow.w_assoc F, wide_pushout.arrow_ι (λ i, g.hom)], }) }, -- tidy needs a bit of help here... map_id' := by { intros i, ext, tidy }, map_comp' := begin intros f g h F G, ext, all_goals { dsimp, simp only [category.assoc, limits.wide_pushout.head_desc_assoc, limits.wide_pushout.ι_desc_assoc, limits.colimit.ι_desc], simpa only [← category.assoc], }, end } /-- The augmented Čech conerve construction, as a functor from `arrow C`. -/ @[simps] def augmented_cech_conerve : arrow C ⥤ cosimplicial_object.augmented C := { obj := λ f, f.augmented_cech_conerve, map := λ f g F, { left := F.left, right := cech_conerve.map F, } } /-- A helper function used in defining the Čech conerve adjunction. -/ @[simps] def equivalence_left_to_right (F : arrow C) (X : cosimplicial_object.augmented C) (G : F.augmented_cech_conerve ⟶ X) : F ⟶ augmented.to_arrow.obj X := { left := G.left, right := (wide_pushout.ι (λ i, F.hom) (_root_.ulift.up 0) ≫ G.right.app (simplex_category.mk 0) : _), w' := begin have := G.w, apply_fun (λ e, e.app (simplex_category.mk 0)) at this, dsimp at this, simpa only [category_theory.functor.id_map, augmented.to_arrow_obj_hom, wide_pushout.arrow_ι_assoc (λ i, F.hom)], end } /-- A helper function used in defining the Čech conerve adjunction. -/ @[simps] def equivalence_right_to_left (F : arrow C) (X : cosimplicial_object.augmented C) (G : F ⟶ augmented.to_arrow.obj X) : F.augmented_cech_conerve ⟶ X := { left := G.left, right := { app := λ x, limits.wide_pushout.desc (G.left ≫ X.hom.app _) (λ i, G.right ≫ X.right.map (simplex_category.const x i.down)) begin rintros ⟨j⟩, rw ←arrow.w_assoc G, dsimp, have t := X.hom.naturality (x.const j), dsimp at t, simp only [category.id_comp] at t, rw ←t, end, naturality' := begin intros x y f, ext, { dsimp, simp only [wide_pushout.ι_desc_assoc, wide_pushout.ι_desc], rw [category.assoc, ←X.right.map_comp], refl }, { dsimp, simp only [functor.const.obj_map, ←nat_trans.naturality, wide_pushout.head_desc_assoc, wide_pushout.head_desc, category.assoc], erw category.id_comp } end }, } /-- A helper function used in defining the Čech conerve adjunction. -/ @[simps] def cech_conerve_equiv (F : arrow C) (X : cosimplicial_object.augmented C) : (F.augmented_cech_conerve ⟶ X) ≃ (F ⟶ augmented.to_arrow.obj X) := { to_fun := equivalence_left_to_right _ _, inv_fun := equivalence_right_to_left _ _, left_inv := begin intro A, dsimp, ext, { refl, }, { cases j, dsimp, simp only [arrow.cech_conerve_map, wide_pushout.ι_desc, category.assoc, ←nat_trans.naturality, wide_pushout.ι_desc_assoc], refl }, { dsimp, erw wide_pushout.head_desc, have := A.w, apply_fun (λ e, e.app x) at this, rw nat_trans.comp_app at this, erw this, refl }, end, right_inv := begin intro A, dsimp, ext, { refl, }, { dsimp, erw wide_pushout.ι_desc, nth_rewrite 1 ← category.comp_id A.right, congr' 1, convert X.right.map_id _, ext ⟨a,ha⟩, change a < 1 at ha, change 0 = a, linarith }, end } /-- The augmented Čech conerve construction is left adjoint to the `to_arrow` functor. -/ abbreviation cech_conerve_adjunction : augmented_cech_conerve ⊣ (augmented.to_arrow : _ ⥤ arrow C) := adjunction.mk_of_hom_equiv { hom_equiv := cech_conerve_equiv } end cosimplicial_object end category_theory
2bd88567caa39c0bc51f719eaf2deeadbaf4e790
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/normed/group/SemiNormedGroup/completion.lean
05582511cc5f9cd726130f9b73c56fbfed576322
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
4,513
lean
/- Copyright (c) 2021 Riccardo Brasca. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Riccardo Brasca, Johan Commelin -/ import analysis.normed.group.SemiNormedGroup import category_theory.preadditive.additive_functor import analysis.normed.group.hom_completion /-! # Completions of normed groups This file contains an API for completions of seminormed groups (basic facts about objects and morphisms). ## Main definitions - `SemiNormedGroup.Completion : SemiNormedGroup ⥤ SemiNormedGroup` : the completion of a seminormed group (defined as a functor on `SemiNormedGroup` to itself). - `SemiNormedGroup.Completion.lift (f : V ⟶ W) : (Completion.obj V ⟶ W)` : a normed group hom from `V` to complete `W` extends ("lifts") to a seminormed group hom from the completion of `V` to `W`. ## Projects 1. Construct the category of complete seminormed groups, say `CompleteSemiNormedGroup` and promote the `Completion` functor below to a functor landing in this category. 2. Prove that the functor `Completion : SemiNormedGroup ⥤ CompleteSemiNormedGroup` is left adjoint to the forgetful functor. -/ noncomputable theory universe u open uniform_space mul_opposite category_theory normed_group_hom namespace SemiNormedGroup /-- The completion of a seminormed group, as an endofunctor on `SemiNormedGroup`. -/ @[simps] def Completion : SemiNormedGroup.{u} ⥤ SemiNormedGroup.{u} := { obj := λ V, SemiNormedGroup.of (completion V), map := λ V W f, f.completion, map_id' := λ V, completion_id, map_comp' := λ U V W f g, (completion_comp f g).symm } instance Completion_complete_space {V : SemiNormedGroup} : complete_space (Completion.obj V) := completion.complete_space _ /-- The canonical morphism from a seminormed group `V` to its completion. -/ @[simps] def Completion.incl {V : SemiNormedGroup} : V ⟶ Completion.obj V := { to_fun := λ v, (v : completion V), map_add' := completion.coe_add, bound' := ⟨1, λ v, by simp⟩ } lemma Completion.norm_incl_eq {V : SemiNormedGroup} {v : V} : ∥Completion.incl v∥ = ∥v∥ := by simp lemma Completion.map_norm_noninc {V W : SemiNormedGroup} {f : V ⟶ W} (hf : f.norm_noninc) : (Completion.map f).norm_noninc := normed_group_hom.norm_noninc.norm_noninc_iff_norm_le_one.2 $ (normed_group_hom.norm_completion f).le.trans $ normed_group_hom.norm_noninc.norm_noninc_iff_norm_le_one.1 hf /-- Given a normed group hom `V ⟶ W`, this defines the associated morphism from the completion of `V` to the completion of `W`. The difference from the definition obtained from the functoriality of completion is in that the map sending a morphism `f` to the associated morphism of completions is itself additive. -/ def Completion.map_hom (V W : SemiNormedGroup.{u}) : (V ⟶ W) →+ (Completion.obj V ⟶ Completion.obj W) := add_monoid_hom.mk' (category_theory.functor.map Completion) $ λ f g, f.completion_add g @[simp] lemma Completion.map_zero (V W : SemiNormedGroup) : Completion.map (0 : V ⟶ W) = 0 := (Completion.map_hom V W).map_zero instance : preadditive SemiNormedGroup.{u} := { hom_group := λ P Q, infer_instance, add_comp' := by { intros, ext, simp only [normed_group_hom.add_apply, category_theory.comp_apply, normed_group_hom.map_add] }, comp_add' := by { intros, ext, simp only [normed_group_hom.add_apply, category_theory.comp_apply, normed_group_hom.map_add] } } instance : functor.additive Completion := { map_add' := λ X Y, (Completion.map_hom _ _).map_add } /-- Given a normed group hom `f : V → W` with `W` complete, this provides a lift of `f` to the completion of `V`. The lemmas `lift_unique` and `lift_comp_incl` provide the api for the universal property of the completion. -/ def Completion.lift {V W : SemiNormedGroup} [complete_space W] [separated_space W] (f : V ⟶ W) : Completion.obj V ⟶ W := { to_fun := f.extension, map_add' := f.extension.to_add_monoid_hom.map_add', bound' := f.extension.bound' } lemma Completion.lift_comp_incl {V W : SemiNormedGroup} [complete_space W] [separated_space W] (f : V ⟶ W) : Completion.incl ≫ (Completion.lift f) = f := by { ext, apply normed_group_hom.extension_coe } lemma Completion.lift_unique {V W : SemiNormedGroup} [complete_space W] [separated_space W] (f : V ⟶ W) (g : Completion.obj V ⟶ W) : Completion.incl ≫ g = f → g = Completion.lift f := λ h, (normed_group_hom.extension_unique _ (λ v, ((ext_iff.1 h) v).symm)).symm end SemiNormedGroup
3124079921abb35ffdbdc530ede1d45ce4b40f3b
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/no_eqn_lemma_for_meta_default.lean
54e0ac2d743689c6fe675f101c2bafc1dafd32f6
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
62
lean
meta structure foo := (x := 10) #print prefix foo.x._default
d298e082ac7735eab2522495979a00dcbbd30fcb
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/field_theory/splitting_field.lean
50eb8508117e3cd54e6db52074ca3a7a9ed6fadc
[ "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
19,604
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import field_theory.intermediate_field import ring_theory.adjoin.field /-! # Splitting fields This file introduces the notion of a splitting field of a polynomial and provides an embedding from a splitting field to any field that splits the polynomial. A polynomial `f : K[X]` splits over a field extension `L` of `K` if it is zero or all of its irreducible factors over `L` have degree `1`. A field extension of `K` of a polynomial `f : K[X]` is called a splitting field if it is the smallest field extension of `K` such that `f` splits. ## Main definitions * `polynomial.splitting_field f`: A fixed splitting field of the polynomial `f`. * `polynomial.is_splitting_field`: A predicate on a field to be a splitting field of a polynomial `f`. ## Main statements * `polynomial.is_splitting_field.lift`: An embedding of a splitting field of the polynomial `f` into another field such that `f` splits. * `polynomial.is_splitting_field.alg_equiv`: Every splitting field of a polynomial `f` is isomorphic to `splitting_field f` and thus, being a splitting field is unique up to isomorphism. -/ noncomputable theory open_locale classical big_operators polynomial universes u v w variables {F : Type u} {K : Type v} {L : Type w} namespace polynomial variables [field K] [field L] [field F] open polynomial section splitting_field /-- Non-computably choose an irreducible factor from a polynomial. -/ def factor (f : K[X]) : K[X] := if H : ∃ g, irreducible g ∧ g ∣ f then classical.some H else X lemma irreducible_factor (f : K[X]) : irreducible (factor f) := begin rw factor, split_ifs with H, { exact (classical.some_spec H).1 }, { exact irreducible_X } end /-- See note [fact non-instances]. -/ lemma fact_irreducible_factor (f : K[X]) : fact (irreducible (factor f)) := ⟨irreducible_factor f⟩ local attribute [instance] fact_irreducible_factor theorem factor_dvd_of_not_is_unit {f : K[X]} (hf1 : ¬is_unit f) : factor f ∣ f := begin by_cases hf2 : f = 0, { rw hf2, exact dvd_zero _ }, rw [factor, dif_pos (wf_dvd_monoid.exists_irreducible_factor hf1 hf2)], exact (classical.some_spec $ wf_dvd_monoid.exists_irreducible_factor hf1 hf2).2 end theorem factor_dvd_of_degree_ne_zero {f : K[X]} (hf : f.degree ≠ 0) : factor f ∣ f := factor_dvd_of_not_is_unit (mt degree_eq_zero_of_is_unit hf) theorem factor_dvd_of_nat_degree_ne_zero {f : K[X]} (hf : f.nat_degree ≠ 0) : factor f ∣ f := factor_dvd_of_degree_ne_zero (mt nat_degree_eq_of_degree_eq_some hf) /-- Divide a polynomial f by X - C r where r is a root of f in a bigger field extension. -/ def remove_factor (f : K[X]) : polynomial (adjoin_root $ factor f) := map (adjoin_root.of f.factor) f /ₘ (X - C (adjoin_root.root f.factor)) theorem X_sub_C_mul_remove_factor (f : K[X]) (hf : f.nat_degree ≠ 0) : (X - C (adjoin_root.root f.factor)) * f.remove_factor = map (adjoin_root.of f.factor) f := let ⟨g, hg⟩ := factor_dvd_of_nat_degree_ne_zero hf in mul_div_by_monic_eq_iff_is_root.2 $ by rw [is_root.def, eval_map, hg, eval₂_mul, ← hg, adjoin_root.eval₂_root, zero_mul] theorem nat_degree_remove_factor (f : K[X]) : f.remove_factor.nat_degree = f.nat_degree - 1 := by rw [remove_factor, nat_degree_div_by_monic _ (monic_X_sub_C _), nat_degree_map, nat_degree_X_sub_C] theorem nat_degree_remove_factor' {f : K[X]} {n : ℕ} (hfn : f.nat_degree = n+1) : f.remove_factor.nat_degree = n := by rw [nat_degree_remove_factor, hfn, n.add_sub_cancel] /-- Auxiliary construction to a splitting field of a polynomial, which removes `n` (arbitrarily-chosen) factors. Uses recursion on the degree. For better definitional behaviour, structures including `splitting_field_aux` (such as instances) should be defined using this recursion in each field, rather than defining the whole tuple through recursion. -/ def splitting_field_aux (n : ℕ) : Π {K : Type u} [field K], by exactI Π (f : K[X]), Type u := nat.rec_on n (λ K _ _, K) $ λ n ih K _ f, by exactI ih f.remove_factor namespace splitting_field_aux theorem succ (n : ℕ) (f : K[X]) : splitting_field_aux (n+1) f = splitting_field_aux n f.remove_factor := rfl instance field (n : ℕ) : Π {K : Type u} [field K], by exactI Π {f : K[X]}, field (splitting_field_aux n f) := nat.rec_on n (λ K _ _, ‹field K›) $ λ n ih K _ f, ih instance inhabited {n : ℕ} {f : K[X]} : inhabited (splitting_field_aux n f) := ⟨37⟩ /- Note that the recursive nature of this definition and `splitting_field_aux.field` creates non-definitionally-equal diamonds in the `ℕ`- and `ℤ`- actions. ```lean example (n : ℕ) {K : Type u} [field K] {f : K[X]} (hfn : f.nat_degree = n) : (add_comm_monoid.nat_module : module ℕ (splitting_field_aux n f hfn)) = @algebra.to_module _ _ _ _ (splitting_field_aux.algebra n _ hfn) := rfl -- fails ``` It's not immediately clear whether this _can_ be fixed; the failure is much the same as the reason that the following fails: ```lean def cases_twice {α} (a₀ aₙ : α) : ℕ → α × α | 0 := (a₀, a₀) | (n + 1) := (aₙ, aₙ) example (x : ℕ) {α} (a₀ aₙ : α) : (cases_twice a₀ aₙ x).1 = (cases_twice a₀ aₙ x).2 := rfl -- fails ``` We don't really care at this point because this is an implementation detail (which is why this is not a docstring), but we do in `splitting_field.algebra'` below. -/ instance algebra (n : ℕ) : Π (R : Type*) {K : Type u} [comm_semiring R] [field K], by exactI Π [algebra R K] {f : K[X]}, algebra R (splitting_field_aux n f) := nat.rec_on n (λ R K _ _ _ _, by exactI ‹algebra R K›) $ λ n ih R K _ _ _ f, by exactI ih R instance is_scalar_tower (n : ℕ) : Π (R₁ R₂ : Type*) {K : Type u} [comm_semiring R₁] [comm_semiring R₂] [has_smul R₁ R₂] [field K], by exactI Π [algebra R₁ K] [algebra R₂ K], by exactI Π [is_scalar_tower R₁ R₂ K] {f : K[X]}, is_scalar_tower R₁ R₂ (splitting_field_aux n f) := nat.rec_on n (λ R₁ R₂ K _ _ _ _ _ _ _ _, by exactI ‹is_scalar_tower R₁ R₂ K›) $ λ n ih R₁ R₂ K _ _ _ _ _ _ _ f, by exactI ih R₁ R₂ instance algebra''' {n : ℕ} {f : K[X]} : algebra (adjoin_root f.factor) (splitting_field_aux n f.remove_factor) := splitting_field_aux.algebra n _ instance algebra' {n : ℕ} {f : K[X]} : algebra (adjoin_root f.factor) (splitting_field_aux n.succ f) := splitting_field_aux.algebra''' instance algebra'' {n : ℕ} {f : K[X]} : algebra K (splitting_field_aux n f.remove_factor) := splitting_field_aux.algebra n K instance scalar_tower' {n : ℕ} {f : K[X]} : is_scalar_tower K (adjoin_root f.factor) (splitting_field_aux n f.remove_factor) := begin -- finding this instance ourselves makes things faster haveI : is_scalar_tower K (adjoin_root f.factor) (adjoin_root f.factor) := is_scalar_tower.right, exact splitting_field_aux.is_scalar_tower n K (adjoin_root f.factor), end instance scalar_tower {n : ℕ} {f : K[X]} : is_scalar_tower K (adjoin_root f.factor) (splitting_field_aux (n + 1) f) := splitting_field_aux.scalar_tower' theorem algebra_map_succ (n : ℕ) (f : K[X]) : by exact algebra_map K (splitting_field_aux (n+1) f) = (algebra_map (adjoin_root f.factor) (splitting_field_aux n f.remove_factor)).comp (adjoin_root.of f.factor) := is_scalar_tower.algebra_map_eq _ _ _ protected theorem splits (n : ℕ) : ∀ {K : Type u} [field K], by exactI ∀ (f : K[X]) (hfn : f.nat_degree = n), splits (algebra_map K $ splitting_field_aux n f) f := nat.rec_on n (λ K _ _ hf, by exactI splits_of_degree_le_one _ (le_trans degree_le_nat_degree $ hf.symm ▸ with_bot.coe_le_coe.2 zero_le_one)) $ λ n ih K _ f hf, by { resetI, rw [← splits_id_iff_splits, algebra_map_succ, ← map_map, splits_id_iff_splits, ← X_sub_C_mul_remove_factor f (λ h, by { rw h at hf, cases hf })], exact splits_mul _ (splits_X_sub_C _) (ih _ (nat_degree_remove_factor' hf)) } theorem exists_lift (n : ℕ) : ∀ {K : Type u} [field K], by exactI ∀ (f : K[X]) (hfn : f.nat_degree = n) {L : Type*} [field L], by exactI ∀ (j : K →+* L) (hf : splits j f), ∃ k : splitting_field_aux n f →+* L, k.comp (algebra_map _ _) = j := nat.rec_on n (λ K _ _ _ L _ j _, by exactI ⟨j, j.comp_id⟩) $ λ n ih K _ f hf L _ j hj, by exactI have hndf : f.nat_degree ≠ 0, by { intro h, rw h at hf, cases hf }, have hfn0 : f ≠ 0, by { intro h, rw h at hndf, exact hndf rfl }, let ⟨r, hr⟩ := exists_root_of_splits _ (splits_of_splits_of_dvd j hfn0 hj (factor_dvd_of_nat_degree_ne_zero hndf)) (mt is_unit_iff_degree_eq_zero.2 f.irreducible_factor.1) in have hmf0 : map (adjoin_root.of f.factor) f ≠ 0, from map_ne_zero hfn0, have hsf : splits (adjoin_root.lift j r hr) f.remove_factor, by { rw ← X_sub_C_mul_remove_factor _ hndf at hmf0, refine (splits_of_splits_mul _ hmf0 _).2, rwa [X_sub_C_mul_remove_factor _ hndf, ← splits_id_iff_splits, map_map, adjoin_root.lift_comp_of, splits_id_iff_splits] }, let ⟨k, hk⟩ := ih f.remove_factor (nat_degree_remove_factor' hf) (adjoin_root.lift j r hr) hsf in ⟨k, by rw [algebra_map_succ, ← ring_hom.comp_assoc, hk, adjoin_root.lift_comp_of]⟩ theorem adjoin_roots (n : ℕ) : ∀ {K : Type u} [field K], by exactI ∀ (f : K[X]) (hfn : f.nat_degree = n), algebra.adjoin K (↑(f.map $ algebra_map K $ splitting_field_aux n f).roots.to_finset : set (splitting_field_aux n f)) = ⊤ := nat.rec_on n (λ K _ f hf, by exactI algebra.eq_top_iff.2 (λ x, subalgebra.range_le _ ⟨x, rfl⟩)) $ λ n ih K _ f hfn, by exactI have hndf : f.nat_degree ≠ 0, by { intro h, rw h at hfn, cases hfn }, have hfn0 : f ≠ 0, by { intro h, rw h at hndf, exact hndf rfl }, have hmf0 : map (algebra_map K (splitting_field_aux n.succ f)) f ≠ 0 := map_ne_zero hfn0, by { rw [algebra_map_succ, ← map_map, ← X_sub_C_mul_remove_factor _ hndf, polynomial.map_mul] at hmf0 ⊢, rw [roots_mul hmf0, polynomial.map_sub, map_X, map_C, roots_X_sub_C, multiset.to_finset_add, finset.coe_union, multiset.to_finset_singleton, finset.coe_singleton, algebra.adjoin_union_eq_adjoin_adjoin, ← set.image_singleton, algebra.adjoin_algebra_map K (adjoin_root f.factor) (splitting_field_aux n f.remove_factor), adjoin_root.adjoin_root_eq_top, algebra.map_top, is_scalar_tower.adjoin_range_to_alg_hom K (adjoin_root f.factor) (splitting_field_aux n f.remove_factor), ih _ (nat_degree_remove_factor' hfn), subalgebra.restrict_scalars_top] } end splitting_field_aux /-- A splitting field of a polynomial. -/ def splitting_field (f : K[X]) := splitting_field_aux f.nat_degree f namespace splitting_field variables (f : K[X]) instance : field (splitting_field f) := splitting_field_aux.field _ instance inhabited : inhabited (splitting_field f) := ⟨37⟩ /-- This should be an instance globally, but it creates diamonds with the `ℕ`, `ℤ`, and `ℚ` algebras (via their `smul` and `to_fun` fields): ```lean example : (algebra_nat : algebra ℕ (splitting_field f)) = splitting_field.algebra' f := rfl -- fails example : (algebra_int _ : algebra ℤ (splitting_field f)) = splitting_field.algebra' f := rfl -- fails example [char_zero K] [char_zero (splitting_field f)] : (algebra_rat : algebra ℚ (splitting_field f)) = splitting_field.algebra' f := rfl -- fails ``` Until we resolve these diamonds, it's more convenient to only turn this instance on with `local attribute [instance]` in places where the benefit of having the instance outweighs the cost. In the meantime, the `splitting_field.algebra` instance below is immune to these particular diamonds since `K = ℕ` and `K = ℤ` are not possible due to the `field K` assumption. Diamonds in `algebra ℚ (splitting_field f)` instances are still possible via this instance unfortunately, but these are less common as they require suitable `char_zero` instances to be present. -/ instance algebra' {R} [comm_semiring R] [algebra R K] : algebra R (splitting_field f) := splitting_field_aux.algebra _ _ instance : algebra K (splitting_field f) := splitting_field_aux.algebra _ _ protected theorem splits : splits (algebra_map K (splitting_field f)) f := splitting_field_aux.splits _ _ rfl variables [algebra K L] (hb : splits (algebra_map K L) f) /-- Embeds the splitting field into any other field that splits the polynomial. -/ def lift : splitting_field f →ₐ[K] L := { commutes' := λ r, by { have := classical.some_spec (splitting_field_aux.exists_lift _ _ rfl _ hb), exact ring_hom.ext_iff.1 this r }, .. classical.some (splitting_field_aux.exists_lift _ _ _ _ hb) } theorem adjoin_roots : algebra.adjoin K (↑(f.map (algebra_map K $ splitting_field f)).roots.to_finset : set (splitting_field f)) = ⊤ := splitting_field_aux.adjoin_roots _ _ rfl theorem adjoin_root_set : algebra.adjoin K (f.root_set f.splitting_field) = ⊤ := adjoin_roots f end splitting_field variables (K L) [algebra K L] /-- Typeclass characterising splitting fields. -/ class is_splitting_field (f : K[X]) : Prop := (splits [] : splits (algebra_map K L) f) (adjoin_roots [] : algebra.adjoin K (↑(f.map (algebra_map K L)).roots.to_finset : set L) = ⊤) namespace is_splitting_field variables {K} instance splitting_field (f : K[X]) : is_splitting_field K (splitting_field f) f := ⟨splitting_field.splits f, splitting_field.adjoin_roots f⟩ section scalar_tower variables {K L F} [algebra F K] [algebra F L] [is_scalar_tower F K L] variables {K} instance map (f : F[X]) [is_splitting_field F L f] : is_splitting_field K L (f.map $ algebra_map F K) := ⟨by { rw [splits_map_iff, ← is_scalar_tower.algebra_map_eq], exact splits L f }, subalgebra.restrict_scalars_injective F $ by { rw [map_map, ← is_scalar_tower.algebra_map_eq, subalgebra.restrict_scalars_top, eq_top_iff, ← adjoin_roots L f, algebra.adjoin_le_iff], exact λ x hx, @algebra.subset_adjoin K _ _ _ _ _ _ hx }⟩ variables {K} (L) theorem splits_iff (f : K[X]) [is_splitting_field K L f] : polynomial.splits (ring_hom.id K) f ↔ (⊤ : subalgebra K L) = ⊥ := ⟨λ h, eq_bot_iff.2 $ adjoin_roots L f ▸ (roots_map (algebra_map K L) h).symm ▸ algebra.adjoin_le_iff.2 (λ y hy, let ⟨x, hxs, hxy⟩ := finset.mem_image.1 (by rwa multiset.to_finset_map at hy) in hxy ▸ set_like.mem_coe.2 $ subalgebra.algebra_map_mem _ _), λ h, @ring_equiv.to_ring_hom_refl K _ ▸ ring_equiv.self_trans_symm (ring_equiv.of_bijective _ $ algebra.bijective_algebra_map_iff.2 h) ▸ by { rw ring_equiv.to_ring_hom_trans, exact splits_comp_of_splits _ _ (splits L f) }⟩ theorem mul (f g : F[X]) (hf : f ≠ 0) (hg : g ≠ 0) [is_splitting_field F K f] [is_splitting_field K L (g.map $ algebra_map F K)] : is_splitting_field F L (f * g) := ⟨(is_scalar_tower.algebra_map_eq F K L).symm ▸ splits_mul _ (splits_comp_of_splits _ _ (splits K f)) ((splits_map_iff _ _).1 (splits L $ g.map $ algebra_map F K)), by rw [polynomial.map_mul, roots_mul (mul_ne_zero (map_ne_zero hf : f.map (algebra_map F L) ≠ 0) (map_ne_zero hg)), multiset.to_finset_add, finset.coe_union, algebra.adjoin_union_eq_adjoin_adjoin, is_scalar_tower.algebra_map_eq F K L, ← map_map, roots_map (algebra_map K L) ((splits_id_iff_splits $ algebra_map F K).2 $ splits K f), multiset.to_finset_map, finset.coe_image, algebra.adjoin_algebra_map, adjoin_roots, algebra.map_top, is_scalar_tower.adjoin_range_to_alg_hom, ← map_map, adjoin_roots, subalgebra.restrict_scalars_top]⟩ end scalar_tower /-- Splitting field of `f` embeds into any field that splits `f`. -/ def lift [algebra K F] (f : K[X]) [is_splitting_field K L f] (hf : polynomial.splits (algebra_map K F) f) : L →ₐ[K] F := if hf0 : f = 0 then (algebra.of_id K F).comp $ (algebra.bot_equiv K L : (⊥ : subalgebra K L) →ₐ[K] K).comp $ by { rw ← (splits_iff L f).1 (show f.splits (ring_hom.id K), from hf0.symm ▸ splits_zero _), exact algebra.to_top } else alg_hom.comp (by { rw ← adjoin_roots L f, exact classical.choice (lift_of_splits _ $ λ y hy, have aeval y f = 0, from (eval₂_eq_eval_map _).trans $ (mem_roots $ by exact map_ne_zero hf0).1 (multiset.mem_to_finset.mp hy), ⟨is_algebraic_iff_is_integral.1 ⟨f, hf0, this⟩, splits_of_splits_of_dvd _ hf0 hf $ minpoly.dvd _ _ this⟩) }) algebra.to_top theorem finite_dimensional (f : K[X]) [is_splitting_field K L f] : finite_dimensional K L := ⟨@algebra.top_to_submodule K L _ _ _ ▸ adjoin_roots L f ▸ fg_adjoin_of_finite (finset.finite_to_set _) (λ y hy, if hf : f = 0 then by { rw [hf, polynomial.map_zero, roots_zero] at hy, cases hy } else is_algebraic_iff_is_integral.1 ⟨f, hf, (eval₂_eq_eval_map _).trans $ (mem_roots $ by exact map_ne_zero hf).1 (multiset.mem_to_finset.mp hy)⟩)⟩ instance (f : K[X]) : _root_.finite_dimensional K f.splitting_field := finite_dimensional f.splitting_field f /-- Any splitting field is isomorphic to `splitting_field f`. -/ def alg_equiv (f : K[X]) [is_splitting_field K L f] : L ≃ₐ[K] splitting_field f := begin refine alg_equiv.of_bijective (lift L f $ splits (splitting_field f) f) ⟨ring_hom.injective (lift L f $ splits (splitting_field f) f).to_ring_hom, _⟩, haveI := finite_dimensional (splitting_field f) f, haveI := finite_dimensional L f, have : finite_dimensional.finrank K L = finite_dimensional.finrank K (splitting_field f) := le_antisymm (linear_map.finrank_le_finrank_of_injective (show function.injective (lift L f $ splits (splitting_field f) f).to_linear_map, from ring_hom.injective (lift L f $ splits (splitting_field f) f : L →+* f.splitting_field))) (linear_map.finrank_le_finrank_of_injective (show function.injective (lift (splitting_field f) f $ splits L f).to_linear_map, from ring_hom.injective (lift (splitting_field f) f $ splits L f : f.splitting_field →+* L))), change function.surjective (lift L f $ splits (splitting_field f) f).to_linear_map, refine (linear_map.injective_iff_surjective_of_finrank_eq_finrank this).1 _, exact ring_hom.injective (lift L f $ splits (splitting_field f) f : L →+* f.splitting_field) end lemma of_alg_equiv [algebra K F] (p : K[X]) (f : F ≃ₐ[K] L) [is_splitting_field K F p] : is_splitting_field K L p := begin split, { rw ← f.to_alg_hom.comp_algebra_map, exact splits_comp_of_splits _ _ (splits F p) }, { rw [←(algebra.range_top_iff_surjective f.to_alg_hom).mpr f.surjective, ←root_set, adjoin_root_set_eq_range (splits F p), root_set, adjoin_roots F p] }, end end is_splitting_field end splitting_field end polynomial namespace intermediate_field open polynomial variables [field K] [field L] [algebra K L] {p : K[X]} lemma splits_of_splits {F : intermediate_field K L} (h : p.splits (algebra_map K L)) (hF : ∀ x ∈ p.root_set L, x ∈ F) : p.splits (algebra_map K F) := begin simp_rw [root_set, finset.mem_coe, multiset.mem_to_finset] at hF, rw splits_iff_exists_multiset, refine ⟨multiset.pmap subtype.mk _ hF, map_injective _ (algebra_map F L).injective _⟩, conv_lhs { rw [polynomial.map_map, ←is_scalar_tower.algebra_map_eq, eq_prod_roots_of_splits h, ←multiset.pmap_eq_map _ _ _ hF] }, simp_rw [polynomial.map_mul, polynomial.map_multiset_prod, multiset.map_pmap, polynomial.map_sub, map_C, map_X], refl, end end intermediate_field
c7ea3bf0a8ceb6c610903846be8c7d0c9070a429
3dc4623269159d02a444fe898d33e8c7e7e9461b
/.github/workflows/groupk.lean
493a302004bd25e5af4f762ee98c550220fe1716
[]
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
17,273
lean
import category_theory.limits.limits import category_theory.limits.shapes import category_theory.yoneda import category_theory.opposites import category_theory.types import category_theory.limits.types -- set_option trace.simplify.rewrite true run_cmd mk_simp_attr `PRODUCT ----- BOF BOF meta def PRODUCT_CAT : tactic unit := `[ try {simp only with PRODUCT}] run_cmd add_interactive [`PRODUCT_CAT] universes v u open category_theory open category_theory.limits open category_theory.category open opposite namespace lem -------------------------------------------------------------------- variables {C : Type u} variables [𝒞 : category.{v} C] variables [has_binary_products.{v} C][has_terminal.{v} C] include 𝒞 attribute [PRODUCT] category.assoc category.id_comp category.comp_id @[PRODUCT] lemma prod_left_def {X Y : C} : limit.π (pair X Y) walking_pair.left = limits.prod.fst := rfl @[PRODUCT] lemma prod_right_def {X Y : C} : limit.π (pair X Y) walking_pair.right = limits.prod.snd := rfl lemma prod.hom_ext {A X Y : C} {a b : A ⟶ X ⨯ Y} (h1 : a ≫ limits.prod.fst = b ≫ limits.prod.fst) (h2 : a ≫ limits.prod.snd = b ≫ limits.prod.snd) : a = b := begin apply limit.hom_ext, rintros (_ | _), rw prod_left_def, exact h1, rw prod_right_def, exact h2, end @[PRODUCT, reassoc] lemma lem.prod.lift_fst {Y A B : C} (f : Y ⟶ A) (g : Y ⟶ B) : prod.lift f g ≫ category_theory.limits.prod.fst = f := limit.lift_π (binary_fan.mk f g) _ attribute [PRODUCT] lem.prod.lift_fst_assoc @[PRODUCT,reassoc]lemma lem.prod.lift_snd {Y A B : C} (f : Y ⟶ A) (g : Y ⟶ B) : prod.lift f g ≫ category_theory.limits.prod.snd = g := limit.lift_π (binary_fan.mk f g) _ attribute [PRODUCT] lem.prod.lift_snd_assoc end lem namespace Product_stuff notation f ` ⊗ `:20 g :20 := category_theory.limits.prod.map f g ---- 20 notation `T`C :20 := (terminal C) notation `T`X : 20 := (terminal.from X) notation f ` | `:20 g :20 := prod.lift f g notation `π1` := limits.prod.fst notation `π2` := limits.prod.snd variables {C : Type u} variables [𝒞 : category.{v} C] variables [has_binary_products.{v} C][has_terminal.{v} C] include 𝒞 variables (X :C) open lem ------------------------------------------------------- /- π notation for projection -/ example {Y A B : C} (f : Y ⟶ A) (g : Y ⟶ B) : ( f | g) ≫ π1 = f := lem.prod.lift_fst f g /- we can type π : A ⨯ B ⟶ B if we need -/ example {Y A B : C} (f : Y ⟶ A) (g : Y ⟶ B) : ( f | g) ≫ (π2 : A ⨯ B ⟶ B) = g := lem.prod.lift_snd f g example {A X Y : C} {a b : A ⟶ X ⨯ Y} (h1 : a ≫ π1 = b ≫ π1 ) (h2 : a ≫ π2 = b ≫ π2) : a = b := prod.hom_ext h1 h2 -- use the tatict example {Y A B : C} (f : Y ⟶ A) (g : Y ⟶ B) : ( f | g) ≫ (π2 : A ⨯ B ⟶ B) = g := by PRODUCT_CAT @[PRODUCT]lemma prod.left_composition{Z' Z A B : C}(h : Z' ⟶ Z)(f : Z ⟶ A)(g : Z ⟶ B) : h ≫ (f | g) = (h ≫ f | h ≫ g) := begin apply lem.prod.hom_ext, --- Le right member is of the form ( | ) composition π1 π2 -- PRODUCT_CAT, PRODUCT_CAT, --- here assoc rw assoc, rw lem.prod.lift_fst, rw lem.prod.lift_fst, rw lem.prod.lift_snd, rw assoc, rw lem.prod.lift_snd, end -- #print notation @[PRODUCT,reassoc]lemma prod.map_first{X Y Z W : C}(f : X ⟶ Y)(g : Z ⟶ W) : (f ⊗ g) ≫ (π1 : Y ⨯ W ⟶ Y) = π1 ≫ f := begin exact limit.map_π (map_pair f g) walking_pair.left, end attribute [PRODUCT] prod.map_first_assoc @[PRODUCT,reassoc]lemma prod.map_second{X Y Z W : C}(f : X ⟶ Y)(g : Z ⟶ W) : (f ⊗ g) ≫ π2 = π2 ≫ g := begin exact limit.map_π (map_pair f g) walking_pair.right, end attribute [PRODUCT] prod.map_second_assoc @[PRODUCT]lemma prod.otimes_is_prod {X Y Z W : C}(f : X ⟶ Y)(g : Z ⟶ W) : (f ⊗ g) = ( π1 ≫ f | π2 ≫ g ) := begin apply prod.hom_ext, PRODUCT_CAT, PRODUCT_CAT, -- rw lem.prod.lift_fst, -- rw prod.map_first, -- rw lem.prod.lift_snd, -- rw prod.map_second, end -- notation π1`(`X `x` Y`)` := (limits.prod.fst : X⨯Y ⟶ X) @[PRODUCT]lemma prod.map_ext{X Y Z W : C}(f1 f2 : X ⟶ Y)(g1 g2 : Z ⟶ W) : (f1 ⊗ g1) = (f2 ⊗ g2) → (π1 : X ⨯ Z ⟶ X) ≫ f1 = (π1 : X ⨯ Z ⟶ X) ≫ f2 := λ certif, begin iterate 2 {rw prod.otimes_is_prod at certif}, rw ← prod.map_first ( f1) (g1), rw ← prod.map_first ( f2) (g2), iterate 2 {rw prod.otimes_is_prod}, rw certif, end lemma prod.map_eq {X Y Z W : C}(f1 f2 : X ⟶ Y)(g1 g2 : Z ⟶ W) : ((π1 : X ⨯ Z ⟶ X) ≫ f1 = (π1 : X ⨯ Z ⟶ X) ≫ f2) → ((π2 : X ⨯ Z ⟶ Z) ≫ g1 = (π2 : X ⨯ Z ⟶ Z) ≫ g2) → ((f1 ⊗ g1) = (f2 ⊗ g2)) := λ certif1 certif2, begin iterate 2 {rw prod.otimes_is_prod}, -- PRODUCT_CAT, rw certif1, rw certif2, end @[PRODUCT,reassoc]lemma prod.prod_otimes {X Y Z : C} (f : Y ⟶ X) (g : X ⟶ Z ) : (f | 𝟙 Y) ≫ (g ⊗ (𝟙 Y)) = (f ≫ g | 𝟙 Y) := begin apply prod.hom_ext, PRODUCT_CAT,PRODUCT_CAT, ---------------------- PROBLEME With the tatict HEEEEEEERRRRRRE -- rw [lem.prod.lift_fst], -- rw assoc, -- rw prod.map_first, -- rw ← assoc, ----- ← assoc here Problem ? -- rw lem.prod.lift_fst, -- tidy, -- super - power tidy end attribute [PRODUCT] prod.prod_otimes_assoc @[PRODUCT,reassoc] lemma prod.prod_comp_otimes {A1 A2 X1 X2 Z: C} (f1 : Z ⟶ A1)(f2 : Z ⟶ A2) (g1 :A1 ⟶ X1 )(g2 : A2 ⟶ X2) : (f1 | f2) ≫ (g1 ⊗ g2) = (f1 ≫ g1 | f2 ≫ g2 ) := begin apply prod.hom_ext, PRODUCT_CAT,PRODUCT_CAT, end attribute [PRODUCT] prod.prod_comp_otimes_assoc def Yo (R : C)(A :C) := (yoneda.obj A).obj (op R) def Yo_ (R : C) {A B : C}(φ : A ⟶ B) := ((yoneda.map φ).app (op R) : Yo R A ⟶ Yo R B) -- Good notation for yoneda stuff : -- We fix V : C and we denote by -- R[X] := yoneda.obj X).obj (op R) and φ : A ⟶ B (in C) R ⟦ φ ⟧ : R⟦ A⟧ → R⟦ B⟧ in type v notation R`⟦`A`⟧`:20 := Yo R A -- notation ?? notation R`<`φ`>`:20 := Yo_ R φ -- def Yoneda_preserve_product (Y : C)(A B : C) : Y ⟦ A ⨯ B ⟧ ≅ Y ⟦ A ⟧ ⨯ Y⟦ B ⟧ := { hom := prod.lift (λ f, f ≫ π1) (λ f, f ≫ π2), inv := λ f : (Y ⟶ A) ⨯ (Y ⟶ B), (prod.lift ((@category_theory.limits.prod.fst _ _ (Y ⟶ A) (Y ⟶ B) _ : ((Y ⟶ A) ⨯ (Y ⟶ B)) → (Y ⟶ A)) f) ((@category_theory.limits.prod.snd _ _ (Y ⟶ A) _ _ : ((Y ⟶ A) ⨯ (Y ⟶ B)) → (Y ⟶ B)) f : Y ⟶ B)), hom_inv_id' := begin ext f, cases j, { simp, refl}, { simp, refl} end, inv_hom_id' := begin apply lem.prod.hom_ext, { rw assoc, rw lem.lem.prod.lift_fst, obviously}, { rw assoc, rw lem.lem.prod.lift_snd, obviously} end } --- Here it just sugar @[PRODUCT]lemma yoneda_sugar.composition (R : C) {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) : R < f ≫ g > =( R< f >) ≫ (R < g >) := begin unfold Yo_, simp, end def yoneda_sugar.conv {R : C}{A : C}(g : R⟦ A⟧ ) : R ⟶ A := g def yoneda_sugar.prod (R : C)(A B : C) : R⟦ A ⨯ B⟧ ≅ R⟦ A⟧ ⨯ R⟦ B⟧ := begin exact Yoneda_preserve_product R A B, end @[PRODUCT]lemma yoneda_sugar.prod.hom (R : C)(A B : C) : (yoneda_sugar.prod R A B).hom = (R < (π1 : A ⨯ B ⟶ A) > | R < (π2 : A ⨯ B ⟶ B)> ) := rfl @[PRODUCT]lemma yoneda_sugar.prod.first (R : C)(A B : C) : (yoneda_sugar.prod R A B).hom ≫ π1 = (R < π1 >) := begin exact rfl, end @[PRODUCT]lemma yoneda_sugar.prod.hom_inv (R : C)(A B : C) : (yoneda_sugar.prod R A B).hom ≫ (yoneda_sugar.prod R A B).inv = 𝟙 (R⟦ A ⨯ B⟧) := (Yoneda_preserve_product R A B).hom_inv_id' @[PRODUCT]lemma yoneda_sugar.prod.inv_hom (R : C)(A B : C) : (yoneda_sugar.prod R A B).inv ≫ (yoneda_sugar.prod R A B).hom = 𝟙 (R⟦ A⟧ ⨯ R⟦ B⟧) := (Yoneda_preserve_product R A B).inv_hom_id' @[PRODUCT]lemma yoneda_sugar.prod.second (R : C)(A B : C) : (yoneda_sugar.prod R A B).hom ≫ limits.prod.snd = (R < limits.prod.snd >) := rfl @[PRODUCT]lemma yoneda_sugar.id (R : C)(A : C) : R < 𝟙 A > = 𝟙 (R⟦ A⟧ ) := begin funext, exact comp_id C g, -- have T : ((yoneda.map (𝟙 A)).app (op R)) g = (g ≫ (𝟙 A)), end lemma yoneda_sugar_prod (R : C)(A B : C)(X :C)(f : X ⟶ A)(g : X ⟶ B) : R < (f | g) > ≫ (yoneda_sugar.prod R A B).hom = (R < f > | R < g > ) := -- the ≫ is :/ begin PRODUCT_CAT, -- rw yoneda_sugar.prod.hom R A B, -- rw prod.left_composition, iterate 2 {rw ← yoneda_sugar.composition}, -- rw ← is the problem ? rw lem.lem.prod.lift_fst, rw lem.lem.prod.lift_snd, end @[PRODUCT]lemma yoneda_sugar_prod_inv (R : C)(A B : C)(X :C)(f : X ⟶ A)(g : X ⟶ B) : R < (f | g) > = (R < f > | R < g > ) ≫ (yoneda_sugar.prod R A B).inv := begin PRODUCT_CAT, -- noting rw ← yoneda_sugar_prod, rw assoc, rw yoneda_sugar.prod.hom_inv, exact rfl, end lemma yoneda_sugar.otimes (R : C){Y Z K :C}(f : X ⟶ Y )(g : Z ⟶ K) : ( R < (f ⊗ g) > ) = (yoneda_sugar.prod _ _ _).hom ≫ ((R<f>) ⊗ R<g>) ≫ (yoneda_sugar.prod _ _ _ ).inv := begin PRODUCT_CAT, -- iterate 2 {rw prod.otimes_is_prod}, -- rw yoneda_sugar.prod.hom, -- iterate 1 {rw yoneda_sugar_prod_inv}, rw ← assoc, rw prod.left_composition, rw ← assoc, rw lem.prod.lift_fst, rw ← assoc, rw lem.prod.lift_snd, -- rw yoneda_sugar.composition, -- rw yoneda_sugar.composition, end @[PRODUCT]lemma yonega_sugar.one_otimes (R :C)(X Y Z: C) (f : X ⟶ Y) : (((yoneda_sugar.prod R Z X).inv) ≫ (R <(𝟙 Z ⊗ f ) > ) ≫ (yoneda_sugar.prod R Z Y).hom) = (𝟙 (R⟦Z⟧) ⊗ R<f >) := begin rw yoneda_sugar.otimes, iterate 3 {rw ← assoc}, rw yoneda_sugar.prod.inv_hom, rw id_comp, rw assoc, rw yoneda_sugar.prod.inv_hom, rw ← yoneda_sugar.id, simp, end lemma yonega_sugar.one_otimes' (R :C)(X Y Z: C) (f : X ⟶ Y) : ( (R <(𝟙 Z ⊗ f ) > ) ≫ (yoneda_sugar.prod R Z Y).hom) = ((yoneda_sugar.prod R Z X).hom) ≫ (𝟙 (R⟦Z⟧) ⊗ R < f >) := begin iterate 2{ rw yoneda_sugar.prod.hom}, rw prod.left_composition, iterate 2{ rw ← yoneda_sugar.composition}, rw prod.map_first, rw prod.map_second, rw comp_id, rw prod.otimes_is_prod,rw prod.left_composition,rw ← assoc, rw lem.prod.lift_fst,rw ← assoc,rw lem.prod.lift_snd,rw comp_id, rw yoneda_sugar.composition, end -- def Y (R : C)(A :C) := (yoneda.obj A).obj (op R) -- def Y_ (R : C) {A B : C}(φ : A ⟶ B) := ((yoneda.map φ).app (op R) : Y R A ⟶ Y R B) -- -- Good notation for yoneda stuff : -- -- We fix V : C and we denote by -- -- R[X] := yoneda.obj X).obj (op R) and φ : A ⟶ B (in C) R ⟦ φ ⟧ : R[A] → R[B] in type v -- notation R`[`A`]`:20 := Y R A -- notation ?? -- notation R`<`φ`>`:20 := Y_ R φ -- -- def Yoneda_preserve_product (Y : C)(A B : C) : -- Y[A ⨯ B] ≅ (Y[A]) ⨯ (Y[B]) := -- { hom := prod.lift -- (λ f, f ≫ π1) -- (λ f, f ≫ π2), -- inv := λ f : (Y ⟶ A) ⨯ (Y ⟶ B), -- (prod.lift -- ((@category_theory.limits.prod.fst _ _ (Y ⟶ A) (Y ⟶ B) _ : ((Y ⟶ A) ⨯ (Y ⟶ B)) → (Y ⟶ A)) f) -- ((@category_theory.limits.prod.snd _ _ (Y ⟶ A) _ _ : ((Y ⟶ A) ⨯ (Y ⟶ B)) → (Y ⟶ B)) f : Y ⟶ B)), -- hom_inv_id' := begin -- ext f, -- cases j, -- { simp, refl}, -- { simp, refl} -- end, -- inv_hom_id' := begin -- apply lem.prod.hom_ext, -- { rw assoc, rw lem.lem.prod.lift_fst, obviously}, -- { rw assoc, rw lem.lem.prod.lift_snd, obviously} -- end -- } -- --- Here it just sugar -- @[PRODUCT,reassoc]lemma yoneda_sugar.composition (R : C) {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) : R < f ≫ g > =( R< f >) ≫ (R < g >) -- := begin -- unfold Y_, -- simp, -- end -- attribute [PRODUCT] yoneda_sugar.composition_assoc -- @[PRODUCT,reassoc]lemma yoneda_sugar.composition_rev (R : C) {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) : -- ( R< f >) ≫ (R < g >) = (R < f ≫ g > ) -- := begin -- unfold Y_, -- simp, -- end -- attribute [PRODUCT] yoneda_sugar.composition_rev_assoc -- def yoneda_sugar.conv {R : C}{A : C}(g : R[A]) : R ⟶ A := g -- def yoneda_sugar.prod (R : C)(A B : C) : R[A ⨯ B] ≅ R[A] ⨯ R[B] := begin -- exact Yoneda_preserve_product R A B, -- end -- @[PRODUCT]lemma yoneda_sugar.prod.hom (R : C)(A B : C) : -- (yoneda_sugar.prod R A B).hom = (R < (π1 : A ⨯ B ⟶ A) > | R < (π2 : A ⨯ B ⟶ B)> ) := rfl -- @[PRODUCT,reassoc]lemma yoneda_sugar.prod.first (R : C)(A B : C) : -- (yoneda_sugar.prod R A B).hom ≫ π1 = (R < π1 >) := -- begin -- exact rfl, -- end -- attribute [PRODUCT] yoneda_sugar.prod.first_assoc -- @[PRODUCT,reassoc]lemma yoneda_sugar.prod.hom_inv (R : C)(A B : C) : -- (yoneda_sugar.prod R A B).hom ≫ (yoneda_sugar.prod R A B).inv = 𝟙 (R[ A ⨯ B]) := -- (Yoneda_preserve_product R A B).hom_inv_id' -- attribute [PRODUCT] yoneda_sugar.prod.hom_inv_assoc -- @[PRODUCT,reassoc]lemma yoneda_sugar.prod.inv_hom (R : C)(A B : C) : -- (yoneda_sugar.prod R A B).inv ≫ (yoneda_sugar.prod R A B).hom = 𝟙 ( R [A] ⨯ R[B]) := -- (Yoneda_preserve_product R A B).inv_hom_id' -- attribute [PRODUCT] yoneda_sugar.prod.inv_hom_assoc -- @[PRODUCT,reassoc]lemma yoneda_sugar.prod.second (R : C)(A B : C) : -- (yoneda_sugar.prod R A B).hom ≫ π2 = (R < (π2 : A ⨯ B ⟶ B) >) := rfl -- attribute [PRODUCT] yoneda_sugar.prod.second_assoc -- @[PRODUCT]lemma yoneda_sugar.id (R : C)(A : C) : R < 𝟙 A > = 𝟙 ( R [A] ) := begin -- funext, -- exact comp_id C g, -- -- have T : ((yoneda.map (𝟙 A)).app (op R)) g = (g ≫ (𝟙 A)), -- end -- @[PRODUCT,reassoc,refl]lemma yoneda_sugar_prod (R : C)(A B : C)(X :C)(f : X ⟶ A)(g : X ⟶ B) : -- R < (f | g) > ≫ (yoneda_sugar.prod R A B).hom = (R < f > | R < g > ) := -- the ≫ is :/ -- begin -- PRODUCT_CAT, -- -- rw yoneda_sugar.prod.hom R A B, -- -- rw prod.left_composition, -- -- iterate 2 {rw ← yoneda_sugar.composition}, -- rw ← is the problem ? -- -- PRODUCT_CAT, -- -- rw lem.lem.prod.lift_fst, -- -- rw lem.lem.prod.lift_snd, -- end -- attribute [PRODUCT] yoneda_sugar_prod_assoc -- @[PRODUCT]lemma yoneda_sugar_prod_inv (R : C)(A B : C)(X :C)(f : X ⟶ A)(g : X ⟶ B) : -- R < (f | g) > = (R < f > | R < g > ) ≫ (yoneda_sugar.prod R A B).inv := -- begin -- PRODUCT_CAT, -- noting HERE PROBLEM the tatic do nothing -- rw ← yoneda_sugar_prod, -- rw assoc, -- rw yoneda_sugar.prod.hom_inv, -- exact rfl, -- end -- @[PRODUCT]lemma yoneda_sugar.otimes (R : C){Y Z K :C}(f : X ⟶ Y )(g : Z ⟶ K) : -- ( R < (f ⊗ g) > ) = (yoneda_sugar.prod _ _ _).hom ≫ ((R<f>) ⊗ R<g>) ≫ (yoneda_sugar.prod _ _ _ ).inv := begin -- -- PRODUCT_CAT, -- iterate 2 {rw prod.otimes_is_prod}, -- rw yoneda_sugar.prod.hom, -- iterate 1 {rw yoneda_sugar_prod_inv}, -- rw ← assoc, -- rw prod.left_composition, -- rw ← assoc, -- rw lem.prod.lift_fst, -- rw ← assoc, -- rw lem.prod.lift_snd, -- rw yoneda_sugar.composition, -- rw yoneda_sugar.composition, -- exact rfl, -- end -- @[PRODUCT]lemma yonega_sugar.one_otimes (R :C)(X Y Z: C) (f : X ⟶ Y) : -- (((yoneda_sugar.prod R Z X).inv) ≫ (R <(𝟙 Z ⊗ f ) > ) ≫ (yoneda_sugar.prod R Z Y).hom) = (𝟙 (R[Z]) ⊗ R < f >) := begin -- rw yoneda_sugar.otimes, -- iterate 3 {rw ← assoc}, -- rw yoneda_sugar.prod.inv_hom, -- rw id_comp, -- rw assoc, -- rw yoneda_sugar.prod.inv_hom, -- rw ← yoneda_sugar.id, -- simp, -- end -- lemma yonega_sugar.one_otimes' (R :C)(X Y Z: C) (f : X ⟶ Y) : -- ( (R <(𝟙 Z ⊗ f ) > ) ≫ (yoneda_sugar.prod R Z Y).hom) = ((yoneda_sugar.prod R Z X).hom) ≫ (𝟙 (R[Z]) ⊗ R < f >) := begin -- iterate 2{ rw yoneda_sugar.prod.hom}, -- rw prod.left_composition, -- iterate 2{ rw ← yoneda_sugar.composition}, -- rw prod.map_first, -- rw prod.map_second, -- rw comp_id, -- rw prod.otimes_is_prod,rw prod.left_composition,rw ← assoc, -- rw lem.prod.lift_fst,rw ← assoc,rw lem.prod.lift_snd,rw comp_id, -- rw yoneda_sugar.composition, -- exact rfl, -- end -- end Product_stuff
ff8a84f2d263eac829c0a78759d9b2852f3d30af
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/order/filter/pointwise.lean
93176f5304554aeb1ec07e7d60a0b2017a9e2554
[ "Apache-2.0" ]
permissive
ChrisHughes24/mathlib
98322577c460bc6b1fe5c21f42ce33ad1c3e5558
a2a867e827c2a6702beb9efc2b9282bd801d5f9a
refs/heads/master
1,583,848,251,477
1,565,164,247,000
1,565,164,247,000
129,409,993
0
1
Apache-2.0
1,565,164,817,000
1,523,628,059,000
Lean
UTF-8
Lean
false
false
9,443
lean
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou The pointwise operations on filters have nice properties, such as • map m (f₁ * f₂) = map m f₁ * map m f₂ • nhds x * nhds y = nhds (x * y) -/ import algebra.pointwise import order.filter.basic open classical set lattice universes u v w variables {α : Type u} {β : Type v} {γ : Type w} local attribute [instance] classical.prop_decidable pointwise_one pointwise_mul pointwise_add namespace filter open set @[to_additive filter.pointwise_zero] def pointwise_one [has_one α] : has_one (filter α) := ⟨principal {1}⟩ local attribute [instance] pointwise_one @[simp, to_additive filter.mem_pointwise_zero] lemma mem_pointwise_one [has_one α] (s : set α) : s ∈ (1 : filter α) ↔ (1:α) ∈ s := calc s ∈ (1:filter α) ↔ {(1:α)} ⊆ s : iff.rfl ... ↔ (1:α) ∈ s : by simp def pointwise_mul [monoid α] : has_mul (filter α) := ⟨λf g, { sets := { s | ∃t₁∈f, ∃t₂∈g, t₁ * t₂ ⊆ s }, univ_sets := begin have h₁ : (∃x, x ∈ f.sets) := ⟨univ, univ_sets f⟩, have h₂ : (∃x, x ∈ g.sets) := ⟨univ, univ_sets g⟩, simpa using and.intro h₁ h₂ end, sets_of_superset := λx y hx hxy, begin rcases hx with ⟨t₁, ht₁, t₂, ht₂, t₁t₂⟩, exact ⟨t₁, ht₁, t₂, ht₂, subset.trans t₁t₂ hxy⟩ end, inter_sets := λx y, begin simp only [exists_prop, mem_set_of_eq, subset_inter_iff], rintros ⟨s₁, hs₁, s₂, hs₂, s₁s₂⟩ ⟨t₁, ht₁, t₂, ht₂, t₁t₂⟩, exact ⟨s₁ ∩ t₁, inter_sets f hs₁ ht₁, s₂ ∩ t₂, inter_sets g hs₂ ht₂, subset.trans (pointwise_mul_subset_mul (inter_subset_left _ _) (inter_subset_left _ _)) s₁s₂, subset.trans (pointwise_mul_subset_mul (inter_subset_right _ _) (inter_subset_right _ _)) t₁t₂⟩, end }⟩ def pointwise_add [add_monoid α] : has_add (filter α) := ⟨λf g, { sets := { s | ∃t₁∈f, ∃t₂∈g, t₁ + t₂ ⊆ s }, univ_sets := begin have h₁ : (∃x, x ∈ f.sets) := ⟨univ, univ_sets f⟩, have h₂ : (∃x, x ∈ g.sets) := ⟨univ, univ_sets g⟩, simpa using and.intro h₁ h₂ end, sets_of_superset := λx y hx hxy, begin rcases hx with ⟨t₁, ht₁, t₂, ht₂, t₁t₂⟩, exact ⟨t₁, ht₁, t₂, ht₂, subset.trans t₁t₂ hxy⟩ end, inter_sets := λx y, begin simp only [exists_prop, mem_set_of_eq, subset_inter_iff], rintros ⟨s₁, hs₁, s₂, hs₂, s₁s₂⟩ ⟨t₁, ht₁, t₂, ht₂, t₁t₂⟩, exact ⟨s₁ ∩ t₁, inter_sets f hs₁ ht₁, s₂ ∩ t₂, inter_sets g hs₂ ht₂, subset.trans (pointwise_add_subset_add (inter_subset_left _ _) (inter_subset_left _ _)) s₁s₂, subset.trans (pointwise_add_subset_add (inter_subset_right _ _) (inter_subset_right _ _)) t₁t₂⟩, end }⟩ attribute [to_additive filter.pointwise_add] pointwise_mul attribute [to_additive filter.pointwise_add._proof_1] pointwise_mul._proof_1 attribute [to_additive filter.pointwise_add._proof_2] pointwise_mul._proof_2 attribute [to_additive filter.pointwise_add._proof_3] pointwise_mul._proof_3 attribute [to_additive filter.pointwise_add.equations.eqn_1] filter.pointwise_mul.equations._eqn_1 local attribute [instance] pointwise_mul pointwise_add @[to_additive filter.mem_pointwise_add] lemma mem_pointwise_mul [monoid α] {f g : filter α} {s : set α} : s ∈ f * g ↔ ∃ t₁ ∈ f, ∃ t₂ ∈ g, t₁ * t₂ ⊆ s := iff.rfl @[to_additive filter.add_mem_pointwise_add] lemma mul_mem_pointwise_mul [monoid α] {f g : filter α} {s t : set α} (hs : s ∈ f) (ht : t ∈ g) : s * t ∈ f * g := ⟨_, hs, _, ht, subset.refl _⟩ @[to_additive filter.pointwise_add_le_add] lemma pointwise_mul_le_mul [monoid α] {f₁ f₂ g₁ g₂ : filter α} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁ * g₁ ≤ f₂ * g₂ := assume _ ⟨s, hs, t, ht, hst⟩, ⟨s, hf hs, t, hg ht, hst⟩ @[to_additive filter.pointwise_add_ne_bot] lemma pointwise_mul_ne_bot [monoid α] {f g : filter α} : f ≠ ⊥ → g ≠ ⊥ → f * g ≠ ⊥ := begin simp only [forall_sets_neq_empty_iff_neq_bot.symm], rintros hf hg s ⟨a, ha, b, hb, ab⟩, rcases ne_empty_iff_exists_mem.1 (pointwise_mul_ne_empty (hf a ha) (hg b hb)) with ⟨x, hx⟩, exact ne_empty_iff_exists_mem.2 ⟨x, ab hx⟩ end @[to_additive filter.pointwise_add_assoc] lemma pointwise_mul_assoc [monoid α] (f g h : filter α) : f * g * h = f * (g * h) := begin ext s, split, { rintros ⟨a, ⟨a₁, ha₁, a₂, ha₂, a₁a₂⟩, b, hb, ab⟩, refine ⟨a₁, ha₁, a₂ * b, mul_mem_pointwise_mul ha₂ hb, _⟩, rw [← pointwise_mul_semigroup.mul_assoc], exact calc a₁ * a₂ * b ⊆ a * b : pointwise_mul_subset_mul a₁a₂ (subset.refl _) ... ⊆ s : ab }, { rintros ⟨a, ha, b, ⟨b₁, hb₁, b₂, hb₂, b₁b₂⟩, ab⟩, refine ⟨a * b₁, mul_mem_pointwise_mul ha hb₁, b₂, hb₂, _⟩, rw [pointwise_mul_semigroup.mul_assoc], exact calc a * (b₁ * b₂) ⊆ a * b : pointwise_mul_subset_mul (subset.refl _) b₁b₂ ... ⊆ s : ab } end local attribute [instance] pointwise_mul_monoid @[to_additive filter.pointwise_zero_add] lemma pointwise_one_mul [monoid α] (f : filter α) : 1 * f = f := begin ext s, split, { rintros ⟨t₁, ht₁, t₂, ht₂, t₁t₂⟩, refine mem_sets_of_superset (mem_sets_of_superset ht₂ _) t₁t₂, assume x hx, exact ⟨1, by rwa [← mem_pointwise_one], x, hx, (one_mul _).symm⟩ }, { assume hs, refine ⟨(1:set α), mem_principal_self _, s, hs, by simp only [one_mul]⟩ } end @[to_additive filter.pointwise_add_zero] lemma pointwise_mul_one [monoid α] (f : filter α) : f * 1 = f := begin ext s, split, { rintros ⟨t₁, ht₁, t₂, ht₂, t₁t₂⟩, refine mem_sets_of_superset (mem_sets_of_superset ht₁ _) t₁t₂, assume x hx, exact ⟨x, hx, 1, by rwa [← mem_pointwise_one], (mul_one _).symm⟩ }, { assume hs, refine ⟨s, hs, (1:set α), mem_principal_self _, by simp only [mul_one]⟩ } end @[to_additive filter.pointwise_add_add_monoid] def pointwise_mul_monoid [monoid α] : monoid (filter α) := { mul_assoc := pointwise_mul_assoc, one_mul := pointwise_one_mul, mul_one := pointwise_mul_one, .. pointwise_mul, .. pointwise_one } local attribute [instance] filter.pointwise_mul_monoid filter.pointwise_add_add_monoid section map open is_mul_hom variables [monoid α] [monoid β] {f : filter α} (m : α → β) @[to_additive filter.map_pointwise_add] lemma map_pointwise_mul [is_mul_hom m] {f₁ f₂ : filter α} : map m (f₁ * f₂) = map m f₁ * map m f₂ := filter_eq $ set.ext $ assume s, begin simp only [mem_pointwise_mul], split, { rintro ⟨t₁, ht₁, t₂, ht₂, t₁t₂⟩, have : m '' (t₁ * t₂) ⊆ s := subset.trans (image_subset m t₁t₂) (image_preimage_subset _ _), refine ⟨m '' t₁, image_mem_map ht₁, m '' t₂, image_mem_map ht₂, _⟩, rwa ← image_pointwise_mul m t₁ t₂ }, { rintro ⟨t₁, ht₁, t₂, ht₂, t₁t₂⟩, refine ⟨m ⁻¹' t₁, ht₁, m ⁻¹' t₂, ht₂, image_subset_iff.1 _⟩, rw image_pointwise_mul m, exact subset.trans (pointwise_mul_subset_mul (image_preimage_subset _ _) (image_preimage_subset _ _)) t₁t₂ }, end @[to_additive filter.map_pointwise_zero] lemma map_pointwise_one [is_monoid_hom m] : map m (1:filter α) = 1 := le_antisymm (le_principal_iff.2 $ mem_map_sets_iff.2 ⟨(1:set α), by simp, by { assume x, simp [is_monoid_hom.map_one m], rintros rfl, refl }⟩) (le_map $ assume s hs, begin simp only [mem_pointwise_one], exact ⟨(1:α), (mem_pointwise_one s).1 hs, is_monoid_hom.map_one _⟩ end) -- TODO: prove similar statements when `m` is group homomorphism etc. def pointwise_mul_map_is_monoid_hom [is_monoid_hom m] : is_monoid_hom (map m) := { map_one := map_pointwise_one m, map_mul := λ _ _, map_pointwise_mul m } def pointwise_add_map_is_add_monoid_hom {α : Type*} {β : Type*} [add_monoid α] [add_monoid β] (m : α → β) [is_add_monoid_hom m] : is_add_monoid_hom (map m) := { map_zero := map_pointwise_zero m, map_add := λ _ _, map_pointwise_add m } attribute [to_additive filter.pointwise_add_map_is_add_monoid_hom] pointwise_mul_map_is_monoid_hom -- The other direction does not hold in general. @[to_additive filter.comap_add_comap_le] lemma comap_mul_comap_le [is_mul_hom m] {f₁ f₂ : filter β} : comap m f₁ * comap m f₂ ≤ comap m (f₁ * f₂) := begin rintros s ⟨t, ⟨t₁, ht₁, t₂, ht₂, t₁t₂⟩, mt⟩, refine ⟨m ⁻¹' t₁, ⟨t₁, ht₁, subset.refl _⟩, m ⁻¹' t₂, ⟨t₂, ht₂, subset.refl _⟩, _⟩, have := subset.trans (preimage_mono t₁t₂) mt, exact subset.trans (preimage_pointwise_mul_preimage_subset m _ _) this end variables {m} @[to_additive filter.tendsto_add_add] lemma tendsto_mul_mul [is_mul_hom m] {f₁ g₁ : filter α} {f₂ g₂ : filter β} : tendsto m f₁ f₂ → tendsto m g₁ g₂ → tendsto m (f₁ * g₁) (f₂ * g₂) := assume hf hg, by { rw [tendsto, map_pointwise_mul m], exact pointwise_mul_le_mul hf hg } end map end filter
18c92016b8278550b68c17e30ccc4e164c1db209
d642a6b1261b2cbe691e53561ac777b924751b63
/src/topology/algebra/monoid.lean
d9b59a3e56f7a24dc751e0a37d7c1c012063dfaa
[ "Apache-2.0" ]
permissive
cipher1024/mathlib
fee56b9954e969721715e45fea8bcb95f9dc03fe
d077887141000fefa5a264e30fa57520e9f03522
refs/heads/master
1,651,806,490,504
1,573,508,694,000
1,573,508,694,000
107,216,176
0
0
Apache-2.0
1,647,363,136,000
1,508,213,014,000
Lean
UTF-8
Lean
false
false
5,314
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 Theory of topological monoids. TODO: generalize `topological_monoid` and `topological_add_monoid` to semigroups, or add a type class `topological_operator α (*)`. -/ import topology.constructions topology.continuous_on import algebra.pi_instances open classical set lattice filter topological_space open_locale classical universes u v w variables {α : Type u} {β : Type v} {γ : Type w} section topological_monoid /-- A topological monoid is a monoid in which the multiplication is continuous as a function `α × α → α`. -/ class topological_monoid (α : Type u) [topological_space α] [monoid α] : Prop := (continuous_mul : continuous (λp:α×α, p.1 * p.2)) /-- A topological (additive) monoid is a monoid in which the addition is continuous as a function `α × α → α`. -/ class topological_add_monoid (α : Type u) [topological_space α] [add_monoid α] : Prop := (continuous_add : continuous (λp:α×α, p.1 + p.2)) attribute [to_additive topological_add_monoid] topological_monoid section variables [topological_space α] [monoid α] [topological_monoid α] @[to_additive] lemma continuous_mul' : continuous (λp:α×α, p.1 * p.2) := topological_monoid.continuous_mul α @[to_additive] lemma continuous_mul [topological_space β] {f : β → α} {g : β → α} (hf : continuous f) (hg : continuous g) : continuous (λx, f x * g x) := continuous_mul'.comp (hf.prod_mk hg) @[to_additive] lemma continuous_mul_left (a : α) : continuous (λ b:α, a * b) := continuous_mul continuous_const continuous_id @[to_additive] lemma continuous_mul_right (a : α) : continuous (λ b:α, b * a) := continuous_mul continuous_id continuous_const @[to_additive] lemma continuous_on.mul [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_mul'.comp_continuous_on (hf.prod hg) : _) -- @[to_additive continuous_smul] lemma continuous_pow : ∀ n : ℕ, continuous (λ a : α, a ^ n) | 0 := by simpa using continuous_const | (k+1) := show continuous (λ (a : α), a * a ^ k), from continuous_mul continuous_id (continuous_pow _) @[to_additive] lemma tendsto_mul' {a b : α} : tendsto (λp:α×α, p.fst * p.snd) (nhds (a, b)) (nhds (a * b)) := continuous_iff_continuous_at.mp (topological_monoid.continuous_mul α) (a, b) @[to_additive] lemma tendsto_mul {f : β → α} {g : β → α} {x : filter β} {a b : α} (hf : tendsto f x (nhds a)) (hg : tendsto g x (nhds b)) : tendsto (λx, f x * g x) x (nhds (a * b)) := tendsto.comp (by rw [←nhds_prod_eq]; exact tendsto_mul') (hf.prod_mk hg) @[to_additive] lemma tendsto_list_prod {f : γ → β → α} {x : filter β} {a : γ → α} : ∀l:list γ, (∀c∈l, tendsto (f c) x (nhds (a c))) → tendsto (λb, (l.map (λc, f c b)).prod) x (nhds ((l.map a).prod)) | [] _ := by simp [tendsto_const_nhds] | (f :: l) h := begin simp, exact tendsto_mul (h f (list.mem_cons_self _ _)) (tendsto_list_prod l (assume c hc, h c (list.mem_cons_of_mem _ hc))) end @[to_additive] lemma continuous_list_prod [topological_space β] {f : γ → β → α} (l : list γ) (h : ∀c∈l, continuous (f c)) : continuous (λa, (l.map (λc, f c a)).prod) := continuous_iff_continuous_at.2 $ assume x, tendsto_list_prod l $ assume c hc, continuous_iff_continuous_at.1 (h c hc) x @[to_additive topological_add_monoid] instance [topological_space β] [monoid β] [topological_monoid β] : topological_monoid (α × β) := ⟨continuous.prod_mk (continuous_mul (continuous_fst.comp continuous_fst) (continuous_fst.comp continuous_snd)) (continuous_mul (continuous_snd.comp continuous_fst) (continuous_snd.comp continuous_snd)) ⟩ attribute [instance] prod.topological_add_monoid end section variables [topological_space α] [comm_monoid α] @[to_additive] lemma is_submonoid.mem_nhds_one (β : set α) [is_submonoid β] (oβ : is_open β) : β ∈ nhds (1 : α) := mem_nhds_sets_iff.2 ⟨β, (by refl), oβ, is_submonoid.one_mem _⟩ variable [topological_monoid α] @[to_additive] lemma tendsto_multiset_prod {f : γ → β → α} {x : filter β} {a : γ → α} (s : multiset γ) : (∀c∈s, tendsto (f c) x (nhds (a c))) → tendsto (λb, (s.map (λc, f c b)).prod) x (nhds ((s.map a).prod)) := by { rcases s with ⟨l⟩, simp, exact tendsto_list_prod l } @[to_additive] lemma tendsto_finset_prod {f : γ → β → α} {x : filter β} {a : γ → α} (s : finset γ) : (∀c∈s, tendsto (f c) x (nhds (a c))) → tendsto (λb, s.prod (λc, f c b)) x (nhds (s.prod a)) := tendsto_multiset_prod _ @[to_additive] lemma continuous_multiset_prod [topological_space β] {f : γ → β → α} (s : multiset γ) : (∀c∈s, continuous (f c)) → continuous (λa, (s.map (λc, f c a)).prod) := by { rcases s with ⟨l⟩, simp, exact continuous_list_prod l } @[to_additive] lemma continuous_finset_prod [topological_space β] {f : γ → β → α} (s : finset γ) : (∀c∈s, continuous (f c)) → continuous (λa, s.prod (λc, f c a)) := continuous_multiset_prod _ end end topological_monoid
d4fdc17ed8b504f908e0e08c8d0e52d1f6f3951c
c3f2fcd060adfa2ca29f924839d2d925e8f2c685
/library/data/prod.lean
f43ff7e62be29b992db03d358e3cb07c30216dac
[ "Apache-2.0" ]
permissive
respu/lean
6582d19a2f2838a28ecd2b3c6f81c32d07b5341d
8c76419c60b63d0d9f7bc04ebb0b99812d0ec654
refs/heads/master
1,610,882,451,231
1,427,747,084,000
1,427,747,429,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,235
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: data.prod Author: Leonardo de Moura, Jeremy Avigad -/ import logic.eq open inhabited decidable eq.ops namespace prod variables {A B : Type} {a₁ a₂ : A} {b₁ b₂ : B} {u : A × B} theorem pair_eq : a₁ = a₂ → b₁ = b₂ → (a₁, b₁) = (a₂, b₂) := assume H1 H2, H1 ▸ H2 ▸ rfl protected theorem equal {p₁ p₂ : prod A B} : pr₁ p₁ = pr₁ p₂ → pr₂ p₁ = pr₂ p₂ → p₁ = p₂ := destruct p₁ (take a₁ b₁, destruct p₂ (take a₂ b₂ H₁ H₂, pair_eq H₁ H₂)) protected definition is_inhabited [instance] [h₁ : inhabited A] [h₂ : inhabited B] : inhabited (prod A B) := inhabited.mk (default A, default B) protected definition has_decidable_eq [instance] [h₁ : decidable_eq A] [h₂ : decidable_eq B] : decidable_eq (A × B) := take (u v : A × B), have H₃ : u = v ↔ (pr₁ u = pr₁ v) ∧ (pr₂ u = pr₂ v), from iff.intro (assume H, H ▸ and.intro rfl rfl) (assume H, and.elim H (assume H₄ H₅, equal H₄ H₅)), decidable_of_decidable_of_iff _ (iff.symm H₃) end prod
75ee134936aa6c868ab43975623ab2406397d292
3af272061d36e7f3f0521cceaa3a847ed4e03af9
/src/SL2Z_generators.lean
88b4a2bc59f581d475bf9927eb15db0f3aaa4bd0
[]
no_license
semorrison/kbb
fdab0929d21dca880d835081814225a95f946187
229bd06e840bc7a7438b8fee6802a4f8024419e3
refs/heads/master
1,585,351,834,355
1,539,848,241,000
1,539,848,241,000
147,323,315
2
1
null
null
null
null
UTF-8
Lean
false
false
15,221
lean
import .modular_group import .action lemma mul_pos_iff {α : Type*} [linear_ordered_ring α] (a b : α) : 0 < a * b ↔ (0 < a ∧ 0 < b) ∨ (a < 0 ∧ b < 0) := iff.intro pos_and_pos_or_neg_and_neg_of_mul_pos $ assume h, match h with | or.inl ⟨ha, hb⟩ := mul_pos ha hb | or.inr ⟨ha, hb⟩ := mul_pos_of_neg_of_neg ha hb end @[simp] lemma not_one_lt_zero {α : Type*} [linear_ordered_semiring α] : ¬ (1:α) < 0 := not_lt_of_gt zero_lt_one namespace int theorem mul_eq_one {m n : ℤ} : m * n = 1 ↔ m = 1 ∧ n = 1 ∨ m = -1 ∧ n = -1 := ⟨λ H, or.cases_on (int.units_eq_one_or ⟨m, n, H, by rwa [mul_comm] at H⟩) (λ H1, have H2 : m = 1, from units.ext_iff.1 H1, or.inl ⟨H2, by rwa [H2, one_mul] at H⟩) (λ H1, have H2 : m = -1, from units.ext_iff.1 H1, or.inr ⟨H2, by rwa [H2, neg_one_mul, neg_eq_iff_neg_eq, eq_comm] at H⟩), by simp [or_imp_distrib] {contextual := tt}⟩ lemma nat_abs_lt_nat_abs (i k : ℤ) (hi : 0 ≤ i) (h : i < abs k) : nat_abs i < nat_abs k := coe_nat_lt.1 $ by rwa [nat_abs_of_nonneg hi, ← int.abs_eq_nat_abs] end int namespace SL2Z_M def S : SL2Z := ⟨0, -1, 1, 0, rfl⟩ def T : SL2Z := ⟨1, 1, 0, 1, rfl⟩ @[simp, SL2Z] lemma S_a : S.a = 0 := rfl @[simp, SL2Z] lemma S_b : S.b = -1 := rfl @[simp, SL2Z] lemma S_c : S.c = 1 := rfl @[simp, SL2Z] lemma S_d : S.d = 0 := rfl @[simp, SL2Z] lemma T_a : T.a = 1 := rfl @[simp, SL2Z] lemma T_b : T.b = 1 := rfl @[simp, SL2Z] lemma T_c : T.c = 0 := rfl @[simp, SL2Z] lemma T_d : T.d = 1 := rfl variable {m : ℤ} local notation `Mat` := integral_matrices_with_determinant @[simp, SL2Z] lemma S_mul_a (A : Mat m) : (SL2Z_M m S A).a = -A.c := by simp [SL2Z_M] @[simp, SL2Z] lemma S_mul_b (A : Mat m) : (SL2Z_M m S A).b = -A.d := by simp [SL2Z_M] @[simp, SL2Z] lemma S_mul_c (A : Mat m) : (SL2Z_M m S A).c = A.a := by simp [SL2Z_M] @[simp, SL2Z] lemma S_mul_d (A : Mat m) : (SL2Z_M m S A).d = A.b := by simp [SL2Z_M] @[simp, SL2Z] lemma T_mul_a (A : Mat m) : (SL2Z_M m T A).a = A.a + A.c := by simp [SL2Z_M] @[simp, SL2Z] lemma T_mul_b (A : Mat m) : (SL2Z_M m T A).b = A.b + A.d := by simp [SL2Z_M] @[simp, SL2Z] lemma T_mul_c (A : Mat m) : (SL2Z_M m T A).c = A.c := by simp [SL2Z_M] @[simp, SL2Z] lemma T_mul_d (A : Mat m) : (SL2Z_M m T A).d = A.d := by simp [SL2Z_M] lemma T_pow_aux (n : ℤ) : (T^n).a = 1 ∧ (T^n).b = n ∧ (T^n).c = 0 ∧ (T^n).d = 1 := int.induction_on n dec_trivial (λ i, by simp [gpow_add] {contextual:=tt}) (λ i, by simp [gpow_add] {contextual:=tt}) @[simp, SL2Z] lemma T_pow_a (n : ℤ) : (T^n).a = 1 := (T_pow_aux n).1 @[simp, SL2Z] lemma T_pow_b (n : ℤ) : (T^n).b = n := (T_pow_aux n).2.1 @[simp, SL2Z] lemma T_pow_c (n : ℤ) : (T^n).c = 0 := (T_pow_aux n).2.2.1 @[simp, SL2Z] lemma T_pow_d (n : ℤ) : (T^n).d = 1 := (T_pow_aux n).2.2.2 @[simp, SL2Z] lemma S_mul_S : S * S = -1 := rfl attribute [elab_as_eliminator] nat.strong_induction_on def reps (m : ℤ) : set (Mat m) := {A : Mat m | A.c = 0 ∧ 0 < A.a ∧ 0 ≤ A.b ∧ int.nat_abs A.b < int.nat_abs A.d } theorem reduce_aux (m : ℤ) (A : Mat m) (H : int.nat_abs (A.c) ≠ 0) : int.nat_abs (SL2Z_M m S (SL2Z_M m (T^(-(A.a/A.c))) A)).c < int.nat_abs A.c := begin have H2 : A.c ≠ 0, from mt (λ H2, show int.nat_abs (A.c) = 0, by rw H2; refl) H, simp only [one_mul, zero_mul, add_zero] with SL2Z, rw [neg_mul_eq_neg_mul_symm, mul_comm, ← sub_eq_add_neg, ← int.mod_def], rw [← int.coe_nat_lt, int.nat_abs_of_nonneg (int.mod_nonneg _ H2)], rw [← int.abs_eq_nat_abs], exact int.mod_lt _ H2 end def reduce_step (A : Mat m) : Mat m := SL2Z_M m S (SL2Z_M m (T^(-(A.a/A.c))) A) @[elab_as_eliminator] def reduce_rec (m : ℤ) {C : Mat m → Sort*} (h₀ : ∀A:Mat m, A.c = 0 → C A) (h₁ : ∀A:Mat m, int.nat_abs A.c ≠ 0 → C (reduce_step A) → C A) : ∀A, C A | A := if hc : int.nat_abs A.c = 0 then h₀ A (int.eq_zero_of_nat_abs_eq_zero hc) else have int.nat_abs (reduce_step A).c < int.nat_abs A.c, from reduce_aux m A hc, h₁ A hc (reduce_rec (reduce_step A)) using_well_founded { rel_tac := λ _ _, `[exact ⟨_, measure_wf (int.nat_abs ∘ integral_matrices_with_determinant.c)⟩]} /-- correct if m ≠ 0 -/ def reduce (m : ℤ) : Mat m → Mat m | A := if hc : int.nat_abs A.c = 0 then if ha : 0 < A.a then SL2Z_M m (T^(-(A.b/A.d))) A else SL2Z_M m (T^(-(-A.b/ -A.d))) (SL2Z_M m S (SL2Z_M m S A)) else have int.nat_abs (reduce_step A).c < int.nat_abs A.c, from reduce_aux m A hc, reduce (reduce_step A) using_well_founded { rel_tac := λ _ _, `[exact ⟨_, measure_wf (int.nat_abs ∘ integral_matrices_with_determinant.c)⟩]} @[simp] theorem reduce_eq1 (m : ℤ) {A : Mat m} (hc : int.nat_abs A.c = 0) (ha : 0 < A.a) : reduce m A = SL2Z_M m (T^(-(A.b/A.d))) A := by rw [reduce.equations._eqn_1 _ _, if_pos hc, if_pos ha]; refl @[simp] theorem reduce_eq2 (m : ℤ) {A : Mat m} (hc : int.nat_abs A.c = 0) (ha : ¬ 0 < A.a) : reduce m A = SL2Z_M m (T^(-(-A.b/ -A.d))) (SL2Z_M m S (SL2Z_M m S A)) := by rw [reduce.equations._eqn_1 _ _, if_pos hc, if_neg ha]; refl @[simp] theorem reduce_eq3 (m : ℤ) {A : Mat m} (h : int.nat_abs A.c ≠ 0) : reduce m A = reduce m (reduce_step A) := by rw [reduce.equations._eqn_1 _ _, if_neg h] theorem reduce_spec (m : ℤ) : ∀A : Mat m, ∃ S, SL2Z_M m S A = reduce m A := begin refine reduce_rec m _ _, { intros A hc, by_cases ha : 0 < A.a, { simp [*], exact ⟨_, rfl⟩ }, { simp [*, (is_monoid_action.mul (SL2Z_M m) _ _ _).symm], exact ⟨_, rfl⟩ } }, { rintros A hc ⟨S, eq⟩, rw [reduce_eq3 m hc, ← eq, reduce_step, ← is_monoid_action.mul (SL2Z_M m), ← is_monoid_action.mul (SL2Z_M m)], exact ⟨_, rfl⟩ } end theorem reduce_mem_reps (m : ℤ) (hm : m ≠ 0) : ∀(A : Mat m), reduce m A ∈ reps m := begin refine reduce_rec m (assume A (c_eq : A.c = 0), _) (assume A hc ih, _), { have hd : A.d ≠ 0, { intro d_eq, apply hm, rw [← A.det, d_eq, c_eq, mul_zero, mul_zero, sub_zero] }, have eq : ∀b d, b + -(b / d * d) = b % d, { intros, rw [← sub_eq_add_neg, mul_comm, ← int.mod_def] }, have h : ∀(a b : ℤ), 0 < a → 0 < a ∧ 0 ≤ b % A.d ∧ int.nat_abs (b % A.d) < int.nat_abs A.d := assume a b ha, ⟨ha, int.mod_nonneg _ hd, int.nat_abs_lt_nat_abs _ _ (int.mod_nonneg _ hd) (int.mod_lt _ hd)⟩, by_cases ha : 0 < A.a, { simpa [reduce_eq1, reps, c_eq, ha, eq] using h _ _ ha }, { have a_ne : A.a ≠ 0, { intro a_eq, apply hm, rw [← A.det, a_eq, c_eq, zero_mul, mul_zero, sub_zero] }, have a_pos : -A.a > 0 := neg_pos_of_neg (lt_of_le_of_ne (le_of_not_gt ha) a_ne), simpa [reduce_eq2, reps, c_eq, ha, eq] using h _ _ a_pos } }, { rwa [reduce_eq3 m hc] } end @[elab_as_eliminator] protected theorem induction_on {C : Mat m → Prop} (A : Mat m) (mne0 : m ≠ 0) (h0 : ∀{A:Mat m}, A.c = 0 → A.a * A.d = m → 0 < A.a → 0 ≤ A.b → int.nat_abs A.b < int.nat_abs A.d → C A) (hS : ∀ B, C B → C (SL2Z_M m S B)) (hT : ∀ B, C B → C (SL2Z_M m T B)) : C A := have S_eq : ∀ B, (SL2Z_M m S (SL2Z_M m S (SL2Z_M m S (SL2Z_M m S B)))) = B, by intro b; ext; simp, have hS' : ∀{B}, C (SL2Z_M m S B) → C B, from λ B ih, have h : _ := (hS _ $ hS _ $ hS _ ih), by rwa S_eq B at h, have eq : ∀ B, (SL2Z_M m S $ SL2Z_M m S $ SL2Z_M m S $ SL2Z_M m T $ SL2Z_M m S $ SL2Z_M m T $ SL2Z_M m S B) = SL2Z_M m T⁻¹ B, by intro b; repeat {rw [←is_monoid_action.mul (SL2Z_M m)]}; congr, have hT_inv : ∀ B, C B → C (SL2Z_M m T⁻¹ B), from λ B ih, have h : _ := (hS _ $ hS _ $ hS _ $ hT _ $ hS _ $ hT _ $ hS _ ih), by rwa eq at h, have hT' : ∀B, C (SL2Z_M m T B) → C B, { assume B ih, have h := hT_inv (SL2Z_M m T B) ih, rwa [←is_monoid_action.mul (SL2Z_M m), mul_left_inv, is_monoid_action.one (SL2Z_M m)] at h }, have hT_inv' : ∀ B, C (SL2Z_M m T⁻¹ B) → C B, { assume B ih, have H := hT (SL2Z_M m T⁻¹ B) ih, rwa [←is_monoid_action.mul (SL2Z_M m), mul_right_inv, is_monoid_action.one (SL2Z_M m)] at H }, have hTpow' : ∀{B} {n:ℤ}, C (SL2Z_M m (T^n) B) → C B, { refine assume B n, int.induction_on n (λh, _) (λi ih1 ih2, ih1 $ hT' _ _) (λi ih1 ih2, ih1 $ hT_inv' _ _), { rwa [gpow_zero, is_monoid_action.one (SL2Z_M m)] at h }, { rwa [add_comm, gpow_add, gpow_one, is_monoid_action.mul (SL2Z_M m)] at ih2 }, { rwa [sub_eq_neg_add, gpow_add, gpow_neg_one, is_monoid_action.mul (SL2Z_M m)] at ih2 } }, have h_reduce : C (reduce m A), { rcases reduce_mem_reps m mne0 A with ⟨H1, H2, H3, H4⟩, refine h0 H1 _ H2 H3 H4, simpa only [H1, mul_zero, sub_zero] using (reduce m A).det }, suffices ∀A : Mat m, C (reduce m A) → C A, from this _ h_reduce, begin refine reduce_rec m _ _, { assume A c_eq ih, by_cases ha : 0 < A.a, { simp [reduce_eq1, c_eq, ha, -gpow_neg] at ih, exact hTpow' ih }, { simp [reduce_eq2, c_eq, ha] at ih, exact (hS' $ hS' $ hTpow' ih) } }, { assume A hc ih hA, rw [reduce_eq3 m hc] at hA, exact (hTpow' $ hS' $ ih hA) } end theorem reps_unique (m : ℤ) (hm : m ≠ 0) : ∀(M : SL2Z) (A B : Mat m), A ∈ reps m → B ∈ reps m → SL2Z_M m M A = B → A = B := begin rintros ⟨a, b, c, d, _⟩ ⟨e, f, g, h, _⟩ ⟨i, j, k, l, _⟩ ⟨g_eq, e_pos, f_nonneg, f_bound⟩ ⟨k_eq, H6, f'_nonneg, f'_bound⟩ B_eq, rcases integral_matrices_with_determinant.mk.inj B_eq with ⟨i_eq, j_eq, ce_0, _⟩, clear B_eq, dsimp only at *, subst g_eq, subst k_eq, subst j_eq, subst i_eq, have : c = 0, { simp at ce_0, rcases ce_0 with rfl | rfl, { refl }, exact (irrefl _ e_pos).elim }, subst this, have : a = 1, { by_contradiction, simp [*, int.mul_eq_one, mul_pos_iff, neg_pos, not_lt_of_gt e_pos] at * }, subst this, by_cases hb : b ≠ 0; by_cases hh : h ≠ 0; cases_matching* [_ ∧ _, _ ∨ _]; subst_vars; simp [*, neg_pos, int.coe_nat_lt.symm, (int.abs_eq_nat_abs _).symm] at *, { rw [abs_of_nonneg f_nonneg] at f_bound, rw [abs_of_nonneg f'_nonneg] at f'_bound, rw [← int.mod_eq_of_lt f'_nonneg f'_bound, ← int.mod_eq_of_lt f_nonneg f_bound], simp } end variable (m) instance reps.fintype_pos (m:ℕ+) : fintype (reps m) := fintype.of_equiv {v : fin (m+1) × fin (m+1) × fin (m+1) // v.1.1 * v.2.2.1 = m ∧ v.2.1.1 < v.2.2.1} { to_fun := λ A, ⟨⟨A.1.1.1, A.1.2.1.1, 0, A.1.2.2.1, by rw [mul_zero, sub_zero, ← int.coe_nat_mul, A.2.1, coe_coe]⟩, rfl, int.coe_nat_pos.2 $ nat.pos_of_ne_zero $ λ H, ne_of_gt m.2 $ A.2.1.symm.trans $ by rw [H, zero_mul], trivial, by simp only [int.nat_abs_of_nat, A.2.2]⟩, inv_fun := λ A, ⟨(⟨int.nat_abs A.1.a, nat.lt_succ_of_le $ nat.le_of_dvd m.2 ⟨int.nat_abs A.1.d, by have := A.1.det; simp only [A.2.1, mul_zero, sub_zero] at this; rw [← int.nat_abs_mul, this, coe_coe, int.nat_abs_of_nat]⟩⟩, ⟨int.nat_abs A.1.b, nat.lt_succ_of_le $ le_trans (le_of_lt A.2.2.2.2) $ nat.le_of_dvd m.2 ⟨int.nat_abs A.1.a, by have := A.1.det; simp only [A.2.1, mul_zero, sub_zero] at this; rw [mul_comm, ← int.nat_abs_mul, this, coe_coe, int.nat_abs_of_nat]⟩⟩, ⟨int.nat_abs A.1.d, nat.lt_succ_of_le $ nat.le_of_dvd m.2 ⟨int.nat_abs A.1.a, by have := A.1.det; simp only [A.2.1, mul_zero, sub_zero] at this; rw [mul_comm, ← int.nat_abs_mul, this, coe_coe, int.nat_abs_of_nat]⟩⟩), by have := A.1.det; simp only [A.2.1, mul_zero, sub_zero] at this; rw [← int.nat_abs_mul, this, coe_coe, int.nat_abs_of_nat], A.2.2.2.2⟩, left_inv := λ ⟨⟨⟨a, ha⟩, ⟨b, hb⟩, ⟨d, hd⟩⟩, H1, H2⟩, subtype.eq $ prod.ext (fin.eq_of_veq $ int.nat_abs_of_nat _) $ prod.ext (fin.eq_of_veq $ int.nat_abs_of_nat _) (fin.eq_of_veq $ int.nat_abs_of_nat _), right_inv := λ ⟨⟨a, b, c, d, H1⟩, H2, H3, H4, H5⟩, subtype.eq $ integral_matrices_with_determinant.ext _ _ _ (int.nat_abs_of_nonneg $ le_of_lt H3) (int.nat_abs_of_nonneg H4) (eq.symm H2) $ int.nat_abs_of_nonneg $ le_of_not_lt $ λ H6, not_le_of_lt m.2 $ int.coe_nat_le.1 $ show (m:ℤ) ≤ 0, by dsimp only at H2 H3 H4 H5; rw [H2, mul_zero, sub_zero] at H1; rw ← H1; from mul_nonpos_of_nonneg_of_nonpos (le_of_lt H3) (le_of_lt H6), } def reps.fintype : Π m : ℤ, m ≠ 0 → fintype (reps m) | (int.of_nat $ n+1) H := reps.fintype_pos ⟨n+1, nat.zero_lt_succ n⟩ | 0 H := (H rfl).elim | -[1+ n] H := fintype.of_equiv (reps (⟨n+1, nat.zero_lt_succ _⟩:pnat)) { to_fun := λ A, ⟨⟨A.1.a, A.1.b, A.1.c, -A.1.d, by have := A.1.det; rw [A.2.1, mul_zero, sub_zero] at this ⊢; rw [mul_neg_eq_neg_mul_symm, this]; refl⟩, A.2.1, A.2.2.1, A.2.2.2.1, trans_rel_left _ A.2.2.2.2 $ eq.symm $ int.nat_abs_neg _⟩, inv_fun := λ A, ⟨⟨A.1.a, A.1.b, A.1.c, -A.1.d, by have := A.1.det; rw [A.2.1, mul_zero, sub_zero] at this ⊢; rw [mul_neg_eq_neg_mul_symm, this]; refl⟩, A.2.1, A.2.2.1, A.2.2.2.1, trans_rel_left _ A.2.2.2.2 $ eq.symm $ int.nat_abs_neg _⟩, left_inv := λ ⟨⟨a, b, c, d, H1⟩, H2⟩, subtype.eq $ integral_matrices_with_determinant.ext _ _ _ rfl rfl rfl (neg_neg _), right_inv := λ ⟨⟨a, b, c, d, H1⟩, H2⟩, subtype.eq $ integral_matrices_with_determinant.ext _ _ _ rfl rfl rfl (neg_neg _) } def π : reps m → quotient (action_rel $ SL2Z_M m) := λ A, (@quotient.mk _ (action_rel $ SL2Z_M m)) A section set_option eqn_compiler.zeta true def reps_equiv (hm : m ≠ 0) : quotient (action_rel (SL2Z_M m)) ≃ reps m := by letI := action_rel (SL2Z_M m); from { to_fun := λ x, quotient.lift_on x (λ A, (⟨reduce m A, reduce_mem_reps m hm A⟩ : reps m)) $ λ A B ⟨M, H⟩, let ⟨MA, HA⟩ := reduce_spec m A in let ⟨MB, HB⟩ := reduce_spec m B in subtype.eq $ reps_unique m hm (MB * M * MA⁻¹) _ _ (reduce_mem_reps m hm A) (reduce_mem_reps m hm B) $ by simp only [is_monoid_action.mul (SL2Z_M m)]; rw [← HA, ← is_monoid_action.mul (SL2Z_M m) MA⁻¹, inv_mul_self]; rw [is_monoid_action.one (SL2Z_M m), H, HB], inv_fun := λ A, ⟦A.1⟧, left_inv := λ x, quotient.induction_on x $ λ A, quotient.sound $ let ⟨MA, HA⟩ := reduce_spec m A in ⟨MA⁻¹, show SL2Z_M m MA⁻¹ (reduce m A) = A, by rw [← HA, ← is_monoid_action.mul (SL2Z_M m) MA⁻¹, inv_mul_self]; rw [is_monoid_action.one (SL2Z_M m)]⟩, right_inv := λ A, subtype.eq $ let ⟨MA, HA⟩ := reduce_spec m A in reps_unique m hm MA⁻¹ _ _ (reduce_mem_reps m hm A) A.2 $ show SL2Z_M m MA⁻¹ (reduce m A) = A, by rw [← HA, ← is_monoid_action.mul (SL2Z_M m) MA⁻¹, inv_mul_self]; rw [is_monoid_action.one (SL2Z_M m)] } end protected def decidable_eq (hm : m ≠ 0) : decidable_eq (quotient (action_rel (SL2Z_M m))) := equiv.decidable_eq (reps_equiv m hm) def finiteness (hm : m ≠ 0) : fintype (quotient $ action_rel $ SL2Z_M m) := @fintype.of_equiv _ _ (reps.fintype m hm) (reps_equiv m hm).symm end SL2Z_M
a9fa639413602ea380668d9bc422976be8d5be68
f083c4ed5d443659f3ed9b43b1ca5bb037ddeb58
/algebra/gcd_domain.lean
80dfa090ab3ca68d619b05e7e74af58f7b3bdccc
[ "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
13,884
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.ring variables {α : Type*} set_option old_structure_cmd true /-- Normalization domain: multiplying with `norm_unit` gives a normal form for associated elements. -/ 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⁻¹) 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 α] @[simp] theorem norm_unit_one : norm_unit (1:α) = 1 := norm_unit_coe_units 1 theorem norm_unit_mul_norm_unit (a : α) : norm_unit (a * norm_unit a) = 1 := classical.by_cases (assume : a = 0, by simp [this]) $ assume h, by rw [norm_unit_mul _ _ h (units.ne_zero _), norm_unit_coe_units, mul_inv_eq_one] theorem associated_of_dvd_of_dvd : ∀{a b : α}, a ∣ b → b ∣ a → ∃u:units α, a * u = b | a b ⟨c, rfl⟩ ⟨d, hd⟩ := classical.by_cases (assume : c = 0, ⟨1, by simp * at *⟩) $ assume hc : c ≠ 0, classical.by_cases (assume : a = 0, ⟨1, by simp * at *⟩) $ assume ha : a ≠ 0, have a * 1 = a * (c * d), by simpa [mul_assoc] using hd, have 1 = c * d, from eq_of_mul_eq_mul_left ha this, ⟨units.mk_of_mul_eq_one c d this.symm, rfl⟩ theorem mul_norm_unit_eq_mul_norm_unit {a b : α} (hab : a ∣ b) (hba : b ∣ a) : a * norm_unit a = b * norm_unit b := begin rcases associated_of_dvd_of_dvd hab hba with ⟨u, rfl⟩, refine classical.by_cases (assume : a = 0, by simp [this] at *) (assume ha : a ≠ 0, _), suffices : a * ↑(norm_unit a) = a * ↑u * ↑(norm_unit a) * ↑u⁻¹, by simpa [ha, mul_assoc], calc a * ↑(norm_unit a) = a * ↑(norm_unit a) * ↑ u * ↑u⁻¹: by simp ... = a * ↑u * ↑(norm_unit a) * ↑u⁻¹ : by ac_refl end theorem dvd_antisymm_of_norm {a b : α} (ha : norm_unit a = 1) (hb : norm_unit b = 1) (hab : a ∣ b) (hba : b ∣ a) : a = b := have a * norm_unit a = b * norm_unit b, from mul_norm_unit_eq_mul_norm_unit hab hba, by simpa [ha, hb] end normalization_domain /-- 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`. -/ 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) (norm_unit_gcd : ∀a b, norm_unit (gcd a b) = 1) (gcd_mul_lcm : ∀a b, gcd a b * lcm a b = a * b * norm_unit (a * b)) (lcm_zero_left : ∀a, lcm 0 a = 0) (lcm_zero_right : ∀a, lcm a 0 = 0) 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 norm_unit_gcd : ∀a b:α, norm_unit (gcd a b) = 1 := gcd_domain.norm_unit_gcd @[simp] theorem gcd_mul_lcm : ∀a b:α, gcd a b * lcm a b = a * b * norm_unit (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_norm (norm_unit_gcd _ _) (norm_unit_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_norm (norm_unit_gcd _ _) (norm_unit_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_mul_norm_unit {a b c : α} (habc : gcd a b ∣ c) (hcab : c ∣ gcd a b) : gcd a b = c * norm_unit c := suffices gcd a b * norm_unit (gcd a b) = c * norm_unit c, by simpa, mul_norm_unit_eq_mul_norm_unit habc hcab @[simp] theorem gcd_zero_left (a : α) : gcd 0 a = a * norm_unit a := gcd_eq_mul_norm_unit (gcd_dvd_right 0 a) (dvd_gcd (dvd_zero _) (dvd_refl a)) @[simp] theorem gcd_zero_right (a : α) : gcd a 0 = a * norm_unit a := gcd_eq_mul_norm_unit (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 simp [h] at ha hb; exact ⟨ha, hb⟩) (assume ⟨ha, hb⟩, by simp [ha, hb]) @[simp] theorem gcd_one_left (a : α) : gcd 1 a = 1 := dvd_antisymm_of_norm (norm_unit_gcd _ _) norm_unit_one (gcd_dvd_left _ _) (dvd_gcd (dvd_refl 1) (one_dvd _)) @[simp] theorem gcd_one_right (a : α) : gcd a 1 = 1 := dvd_antisymm_of_norm (norm_unit_gcd _ _) norm_unit_one (gcd_dvd_right _ _) (dvd_gcd (one_dvd _) (dvd_refl 1)) 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 = a * norm_unit a := gcd_eq_mul_norm_unit (gcd_dvd_left _ _) (dvd_gcd (dvd_refl a) (dvd_refl a)) @[simp] theorem gcd_mul_left (a b c : α) : gcd (a * b) (a * c) = (a * norm_unit a) * gcd b c := classical.by_cases (assume h : a = 0, by simp [h]) $ assume ha : a ≠ 0, classical.by_cases (assume h : gcd b c = 0, by simp * at *) $ assume hbc : gcd b c ≠ 0, suffices gcd (a * b) (a * c) = a * gcd b c * norm_unit (a * gcd b c), by simpa [mul_comm, mul_assoc, mul_left_comm, norm_unit_mul a _ ha hbc], let ⟨d, eq⟩ := dvd_gcd (dvd_mul_right a b) (dvd_mul_right a c) in gcd_eq_mul_norm_unit (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 * (a * norm_unit a) := by simpa [mul_comm] using gcd_mul_left a b c theorem gcd_eq_left_iff (a b : α) (h : norm_unit a = 1) : gcd a b = a ↔ a ∣ b := iff.intro (assume eq, eq ▸ gcd_dvd_right _ _) $ assume hab, dvd_antisymm_of_norm (norm_unit_gcd _ _) h (gcd_dvd_left _ _) (dvd_gcd (dvd_refl a) hab) theorem gcd_eq_right_iff (a b : α) (h : norm_unit b = 1) : gcd a b = b ↔ b ∣ a := by simpa [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 cases this with h h; simp [h, iff_def] {contextual := tt}) (assume this : ¬ (a = 0 ∨ b = 0), have a ≠ 0 ∧ b ≠ 0, by simpa [not_or_distrib] using this, have h : gcd a b ≠ 0, by simp [gcd_eq_zero_iff, this], by rw [← mul_dvd_mul_iff_left h, gcd_mul_lcm, units.coe_mul_dvd, ← units.dvd_coe_mul _ _ (norm_unit c), mul_assoc, mul_comm (gcd a b), ← gcd_mul_left, dvd_gcd_iff, mul_comm c a, mul_dvd_mul_iff_left this.1, mul_dvd_mul_iff_right this.2, and_comm]) lemma dvd_lcm_left (a b : α) : a ∣ lcm a b := have a ∣ lcm a b ∧ b ∣ lcm a b, from (lcm_dvd_iff _ _ _).1 (dvd_refl _), this.1 lemma dvd_lcm_right (a b : α) : b ∣ lcm a b := have a ∣ lcm a b ∧ b ∣ lcm a b, from (lcm_dvd_iff _ _ _).1 (dvd_refl _), this.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 a * b * norm_unit (a * b) = 0, by rw [← gcd_mul_lcm _ _, h, mul_zero], by simpa [mul_eq_zero]) (by simp [or_imp_distrib] {contextual := tt}) @[simp] lemma norm_unit_lcm (a b : α) : norm_unit (lcm a b) = 1 := classical.by_cases (assume : lcm a b = 0, by simp [this]) $ assume h_lcm : lcm a b ≠ 0, have gcd a b ≠ 0, by simp [*, not_or_distrib] at *, have norm_unit (gcd a b * lcm a b) = 1, by rw [gcd_mul_lcm, norm_unit_mul_norm_unit], by simp [norm_unit_mul, *, -gcd_mul_lcm] at * theorem lcm_comm (a b : α) : lcm a b = lcm b a := dvd_antisymm_of_norm (norm_unit_lcm _ _) (norm_unit_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_norm (norm_unit_lcm _ _) (norm_unit_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_mul_norm_unit {a b c : α} (habc : lcm a b ∣ c) (hcab : c ∣ lcm a b) : lcm a b = c * norm_unit c := dvd_antisymm_of_norm (norm_unit_lcm _ _) (norm_unit_mul_norm_unit _) ((units.dvd_coe_mul _ _ _).2 $ habc) ((units.coe_mul_dvd _ _ _).2 $ 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 = a * norm_unit a := lcm_eq_mul_norm_unit (lcm_dvd (units.coe_dvd _ _) (dvd_refl _)) (dvd_lcm_right _ _) @[simp] theorem lcm_units_coe_right (a : α) (u : units α) : lcm a ↑u = a * norm_unit a := by rw [lcm_comm a, lcm_units_coe_left] @[simp] theorem lcm_one_left (a : α) : lcm 1 a = a * norm_unit a := lcm_units_coe_left 1 a @[simp] theorem lcm_one_right (a : α) : lcm a 1 = a * norm_unit a := lcm_units_coe_right a 1 @[simp] theorem lcm_same (a : α) : lcm a a = a * norm_unit a := lcm_eq_mul_norm_unit (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 simp) @[simp] theorem lcm_mul_left (a b c : α) : lcm (a * b) (a * c) = (a * norm_unit a) * lcm b c := classical.by_cases (assume : a = 0, by simp * at *) $ assume ha : a ≠ 0, classical.by_cases (assume : lcm b c = 0, by simp [*, mul_eq_zero] at *) $ assume hbc : lcm b c ≠ 0, suffices lcm (a * b) (a * c) = a * lcm b c * norm_unit (a * lcm b c), by simpa [ha, hbc, norm_unit_mul, mul_assoc, mul_comm, mul_left_comm], have a ∣ lcm (a * b) (a * c), from dvd.trans (dvd_mul_right _ _) (dvd_lcm_left _ _), let ⟨d, eq⟩ := this in lcm_eq_mul_norm_unit (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 * (a * norm_unit a) := by simpa [mul_comm] using lcm_mul_left a b c theorem lcm_eq_left_iff (a b : α) (h : norm_unit a = 1) : lcm a b = a ↔ b ∣ a := iff.intro (assume eq, eq ▸ dvd_lcm_right _ _) $ assume hab, dvd_antisymm_of_norm (norm_unit_lcm _ _) h (lcm_dvd (dvd_refl a) hab) (dvd_lcm_left _ _) theorem lcm_eq_right_iff (a b : α) (h : norm_unit b = 1) : lcm a b = b ↔ a ∣ b := by simpa [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
51f2b6bf04bfe1203207faf8dd12a2564d4e5877
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/topology/metric_space/emetric_space.lean
eab0aab89d6714aff6ac5a63e5faa8dec30f735b
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
46,747
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.nat.interval import data.real.ennreal import topology.uniform_space.pi import topology.uniform_space.uniform_convergence import topology.uniform_space.uniform_embedding /-! # 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`). Since a lot of elementary properties don't require `eq_of_edist_eq_zero` we start setting up the theory of `pseudo_emetric_space`, where we don't require `edist x y = 0 → x = y` and we specialize to `emetric_space` at the end. -/ 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} /-- 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_of_mem ε $ mem_infi_of_mem ε0 $ mem_principal.2 $ λ ⟨a, b⟩, h) /-- `has_edist α` means that `α` is equipped with an extended distance. -/ 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_of_mem (ε / 2) $ mem_infi_of_mem 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 (pseudo) metric spaces, with an extended distance `edist` possibly taking the value ∞ Each pseudo_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 a `pseudo_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 a `pseudo_emetric_space` structure on a product. Continuity of `edist` is proved in `topology.instances.ennreal` -/ class pseudo_emetric_space (α : Type u) extends has_edist α : Type u := (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) (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) /- Pseudoemetric 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 [pseudo_emetric_space α] @[priority 100] -- see Note [lower instance priority] instance pseudo_emetric_space.to_uniform_space' : uniform_space α := pseudo_emetric_space.to_uniform_space export pseudo_emetric_space (edist_self edist_comm edist_triangle) attribute [simp] edist_self /-- 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, 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_rfl ... = ∑ i in finset.Ico m (n+1), _ : by rw [nat.Ico_succ_right_eq_insert_Ico hn, finset.sum_insert, add_comm]; simp } end /-- The triangle (polygon) inequality for sequences of points; `finset.range` version. -/ lemma edist_le_range_sum_edist (f : ℕ → α) (n : ℕ) : edist (f 0) (f n) ≤ ∑ i in finset.range n, edist (f i) (f (i + 1)) := nat.Ico_zero_eq_range 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.mem_Ico.1 hk).1 (finset.mem_Ico.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 := nat.Ico_zero_eq_range n ▸ edist_le_Ico_sum_of_edist_le (zero_le n) (λ _ _, hd) /-- Reformulation of the uniform structure in terms of the extended distance -/ theorem uniformity_pseudoedist : 𝓤 α = ⨅ ε>0, 𝓟 {p:α×α | edist p.1 p.2 < ε} := pseudo_emetric_space.uniformity_edist theorem uniformity_basis_edist : (𝓤 α).has_basis (λ ε : ℝ≥0∞, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 < ε}) := (@uniformity_pseudoedist α _).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 pseudoemetric spaces -/ theorem uniform_continuous_on_iff [pseudo_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 pseudoemetric spaces -/ theorem uniform_continuous_iff [pseudo_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 pseudoemetric spaces -/ theorem uniform_embedding_iff [pseudo_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)⟩⟩ /-- If a map between pseudoemetric spaces is a uniform embedding then the edistance between `f x` and `f y` is controlled in terms of the distance between `x` and `y`. -/ theorem controlled_of_uniform_embedding [pseudo_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 assume h, exact ⟨uniform_continuous_iff.1 (uniform_embedding_iff.1 h).2.1, (uniform_embedding_iff.1 h).2.2⟩, end /-- ε-δ characterization of Cauchy sequences on pseudoemetric 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 pseudoemetric 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 /-- Auxiliary function to replace the uniformity on a pseudoemetric space with a uniformity which is equal to the original one, but maybe not defeq. This is useful if one wants to construct a pseudoemetric space with a specified uniformity. See Note [forgetful inheritance] explaining why having definitionally the right uniformity is often important. -/ def pseudo_emetric_space.replace_uniformity {α} [U : uniform_space α] (m : pseudo_emetric_space α) (H : @uniformity _ U = @uniformity _ pseudo_emetric_space.to_uniform_space) : pseudo_emetric_space α := { edist := @edist _ m.to_has_edist, edist_self := edist_self, edist_comm := edist_comm, edist_triangle := edist_triangle, to_uniform_space := U, uniformity_edist := H.trans (@pseudo_emetric_space.uniformity_edist α _) } /-- The extended pseudometric induced by a function taking values in a pseudoemetric space. -/ def pseudo_emetric_space.induced {α β} (f : α → β) (m : pseudo_emetric_space β) : pseudo_emetric_space α := { edist := λ x y, edist (f x) (f y), edist_self := λ x, edist_self _, 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.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 } /-- Pseudoemetric space instance on subsets of pseudoemetric spaces -/ instance {α : Type*} {p : α → Prop} [t : pseudo_emetric_space α] : pseudo_emetric_space (subtype p) := t.induced coe /-- The extended psuedodistance on a subset of a pseudoemetric space is the restriction of the original pseudodistance, by definition -/ theorem subtype.edist_eq {p : α → Prop} (x y : subtype p) : edist x y = edist (x : α) y := rfl /-- The product of two pseudoemetric spaces, with the max distance, is an extended pseudometric 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.pseudo_emetric_space_max [pseudo_emetric_space β] : pseudo_emetric_space (α × β) := { edist := λ x y, max (edist x.1 y.1) (edist x.2 y.2), edist_self := λ x, by simp, 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 [pseudo_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 [pseudo_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 pseudoemetric spaces, with the max distance, is still a pseudoemetric 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 pseudo_emetric_space_pi [∀b, pseudo_emetric_space (π b)] : pseudo_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, to_uniform_space := Pi.uniform_space _, uniformity_edist := begin simp only [Pi.uniformity, pseudo_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, pseudo_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) lemma edist_le_pi_edist [Π b, pseudo_emetric_space (π b)] (f g : Π b, π b) (b : β) : edist (f b) (g b) ≤ edist f g := finset.le_sup (finset.mem_univ b) lemma edist_pi_le_iff [Π b, pseudo_emetric_space (π b)] {f g : Π b, π b} {d : ℝ≥0∞} : edist f g ≤ d ↔ ∀ b, edist (f b) (g b) ≤ d := finset.sup_le_iff.trans $ by simp only [finset.mem_univ, forall_const] 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 @[simp] theorem closed_ball_top (x : α) : closed_ball x ∞ = univ := eq_univ_of_forall $ λ y, @le_top _ _ (edist y x) theorem ball_subset_closed_ball : ball x ε ⊆ closed_ball x ε := assume y hy, le_of_lt hy 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_left h' 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 _ (ne_top_of_lt h)⟩, rw ennreal.add_sub_cancel_of_le (le_of_lt h), exact le_refl ε 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 := is_open_ball.mem_nhds (mem_ball_self ε0) theorem closed_ball_mem_nhds (x : α) {ε : ℝ≥0∞} (ε0 : 0 < ε) : closed_ball x ε ∈ 𝓝 x := mem_of_superset (ball_mem_nhds x ε0) ball_subset_closed_ball theorem ball_prod_same [pseudo_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 [pseudo_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 pseudoemetric 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 a pseudoemetric space, Cauchy sequences are characterized by the fact that, eventually, the pseudoedistance 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 first_countable @[priority 100] -- see Note [lower instance priority] instance (α : Type u) [pseudo_emetric_space α] : topological_space.first_countable_topology α := uniform_space.first_countable_topology uniformity_has_countable_basis end first_countable section compact /-- For a set `s` in a pseudo emetric space, if for every `ε > 0` there exists a countable set that is `ε`-dense in `s`, then there exists a countable subset `t ⊆ s` that is dense in `s`. -/ lemma subset_countable_closure_of_almost_dense_set (s : set α) (hs : ∀ ε > 0, ∃ t : set α, countable t ∧ s ⊆ ⋃ x ∈ t, closed_ball x ε) : ∃ t ⊆ s, (countable t ∧ s ⊆ closure t) := begin rcases s.eq_empty_or_nonempty with rfl|⟨x₀, hx₀⟩, { exact ⟨∅, empty_subset _, countable_empty, empty_subset _⟩ }, choose! T hTc hsT using (λ n : ℕ, hs n⁻¹ (by simp)), have : ∀ r x, ∃ y ∈ s, closed_ball x r ∩ s ⊆ closed_ball y (r * 2), { intros r x, rcases (closed_ball x r ∩ s).eq_empty_or_nonempty with he|⟨y, hxy, hys⟩, { refine ⟨x₀, hx₀, _⟩, rw he, exact empty_subset _ }, { refine ⟨y, hys, λ z hz, _⟩, calc edist z y ≤ edist z x + edist y x : edist_triangle_right _ _ _ ... ≤ r + r : add_le_add hz.1 hxy ... = r * 2 : (mul_two r).symm } }, choose f hfs hf, refine ⟨⋃ n : ℕ, (f n⁻¹) '' (T n), Union_subset $ λ n, image_subset_iff.2 (λ z hz, hfs _ _), countable_Union $ λ n, (hTc n).image _, _⟩, refine λ x hx, mem_closure_iff.2 (λ ε ε0, _), rcases ennreal.exists_inv_nat_lt (ennreal.half_pos ε0.lt.ne').ne' with ⟨n, hn⟩, rcases mem_bUnion_iff.1 (hsT n hx) with ⟨y, hyn, hyx⟩, refine ⟨f n⁻¹ y, mem_Union.2 ⟨n, mem_image_of_mem _ hyn⟩, _⟩, calc edist x (f n⁻¹ y) ≤ n⁻¹ * 2 : hf _ _ ⟨hyx, hx⟩ ... < ε : ennreal.mul_lt_of_lt_div hn end /-- A compact set in a pseudo emetric space is separable, i.e., it is a subset of the closure of a countable set. -/ lemma subset_countable_closure_of_compact {s : set α} (hs : is_compact s) : ∃ t ⊆ s, (countable t ∧ s ⊆ closure t) := begin refine subset_countable_closure_of_almost_dense_set s (λ ε hε, _), rcases totally_bounded_iff'.1 hs.totally_bounded ε hε with ⟨t, hts, htf, hst⟩, exact ⟨t, htf.countable, subset.trans hst (bUnion_mono $ λ _ _, ball_subset_closed_ball)⟩ end end compact section second_countable open topological_space variables (α) /-- A separable pseudoemetric 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 [separable_space α] : second_countable_topology α := uniform_space.second_countable_of_separable uniformity_has_countable_basis /-- A sigma compact pseudo emetric space has second countable topology. This is not an instance to avoid a loop with `sigma_compact_space_of_locally_compact_second_countable`. -/ lemma second_countable_of_sigma_compact [sigma_compact_space α] : second_countable_topology α := begin suffices : separable_space α, by exactI second_countable_of_separable α, choose T hTsub hTc hsubT using λ n, subset_countable_closure_of_compact (is_compact_compact_covering α n), refine ⟨⟨⋃ n, T n, countable_Union hTc, λ x, _⟩⟩, rcases Union_eq_univ_iff.1 (Union_compact_covering α) x with ⟨n, hn⟩, exact closure_mono (subset_Union _ n) (hsubT _ hn) end variable {α} lemma second_countable_of_almost_dense_set (hs : ∀ ε > 0, ∃ t : set α, countable t ∧ (⋃ x ∈ t, closed_ball x ε) = univ) : second_countable_topology α := begin suffices : separable_space α, by exactI second_countable_of_separable α, rcases subset_countable_closure_of_almost_dense_set (univ : set α) (λ ε ε0, _) with ⟨t, -, htc, ht⟩, { exact ⟨⟨t, htc, λ x, ht (mem_univ x)⟩⟩ }, { rcases hs ε ε0 with ⟨t, htc, ht⟩, exact ⟨t, htc, univ_subset_iff.2 ht⟩ } end end second_countable section diam /-- The diameter of a set in a pseudoemetric space, named `emetric.diam` -/ def diam (s : set α) := ⨆ (x ∈ s) (y ∈ s), edist x y lemma diam_le_iff {d : ℝ≥0∞} : diam s ≤ d ↔ ∀ (x ∈ s) (y ∈ s), edist x y ≤ d := by simp only [diam, supr_le_iff] lemma diam_image_le_iff {d : ℝ≥0∞} {f : β → α} {s : set β} : diam (f '' s) ≤ d ↔ ∀ (x ∈ s) (y ∈ s), edist (f x) (f y) ≤ d := by simp only [diam_le_iff, ball_image_iff] lemma edist_le_of_diam_le {d} (hx : x ∈ s) (hy : y ∈ s) (hd : diam s ≤ d) : edist x y ≤ d := diam_le_iff.1 hd x hx y hy /-- 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 := edist_le_of_diam_le hx hy le_rfl /-- If the distance between any two points in a set is bounded by some constant, this constant bounds the diameter. -/ lemma diam_le {d : ℝ≥0∞} (h : ∀ (x ∈ s) (y ∈ s), edist x y ≤ d) : diam s ≤ d := diam_le_iff.2 h /-- The diameter of a subsingleton vanishes. -/ lemma diam_subsingleton (hs : s.subsingleton) : diam s = 0 := nonpos_iff_eq_zero.1 $ diam_le $ λ x hx y hy, (hs hx hy).symm ▸ edist_self y ▸ le_rfl /-- 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_Union_mem_option {ι : Type*} (o : option ι) (s : ι → set α) : diam (⋃ i ∈ o, s i) = ⨆ i ∈ o, diam (s i) := by cases o; simp 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, 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 $ λ 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 (λ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_self_add ... = diam s + edist x y + diam t : (add_assoc _ _ _).symm }, { 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_self } 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 $ λ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 : (two_mul r).symm lemma diam_ball {r : ℝ≥0∞} : diam (ball x r) ≤ 2 * r := le_trans (diam_mono ball_subset_closed_ball) diam_closed_ball lemma diam_pi_le_of_le {π : β → Type*} [fintype β] [∀ b, pseudo_emetric_space (π b)] {s : Π (b : β), set (π b)} {c : ℝ≥0∞} (h : ∀ b, diam (s b) ≤ c) : diam (set.pi univ s) ≤ c := begin apply diam_le (λ x hx y hy, edist_pi_le_iff.mpr _), rw [mem_univ_pi] at hx hy, exact λ b, diam_le_iff.1 (h b) (x b) (hx b) (y b) (hy b), end end diam end emetric --namespace /-- We now define `emetric_space`, extending `pseudo_emetric_space`. -/ class emetric_space (α : Type u) extends pseudo_emetric_space α : Type u := (eq_of_edist_eq_zero : ∀ {x y : α}, edist x y = 0 → x = y) variables {γ : Type w} [emetric_space γ] @[priority 100] -- see Note [lower instance priority] instance emetric_space.to_uniform_space' : uniform_space γ := pseudo_emetric_space.to_uniform_space export emetric_space (eq_of_edist_eq_zero) /-- 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 @[simp] theorem edist_pos {x y : γ} : 0 < edist x y ↔ x ≠ y := by simp [← not_le] /-- 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) /-- 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 ⟨emetric.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 ⟨_, emetric.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 /-- 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)) /-- If a `pseudo_emetric_space` is separated, then it is an `emetric_space`. -/ def emetric_of_t2_pseudo_emetric_space {α : Type*} [pseudo_emetric_space α] (h : separated_space α) : emetric_space α := { eq_of_edist_eq_zero := λ x y hdist, begin refine separated_def.1 h x y (λ s hs, _), obtain ⟨ε, hε, H⟩ := mem_uniformity_edist.1 hs, exact H (show edist x y < ε, by rwa [hdist]) end ..‹pseudo_emetric_space α› } /-- 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 _ pseudo_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 (@pseudo_emetric_space.uniformity_edist γ _) } /-- The extended metric induced by an injective function taking values in a 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.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 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 (γ × β) := { 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, ..prod.pseudo_emetric_space_max } /-- Reformulation of the uniform structure in terms of the extended distance -/ theorem uniformity_edist : 𝓤 γ = ⨅ ε>0, 𝓟 {p:γ×γ | edist p.1 p.2 < ε} := pseudo_emetric_space.uniformity_edist 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) := { 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, ..pseudo_emetric_space_pi } end pi namespace emetric /-- A compact set in an emetric space is separable, i.e., it is the closure of a countable set. -/ lemma countable_closure_of_compact {s : set γ} (hs : is_compact s) : ∃ t ⊆ s, (countable t ∧ s = closure t) := begin rcases subset_countable_closure_of_compact hs with ⟨t, hts, htc, hsub⟩, exact ⟨t, hts, htc, subset.antisymm hsub (closure_minimal hts hs.is_closed)⟩ end section diam variables {s : set γ} 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 end diam end emetric
e86e7985ae521012d0c258a8638250493d22fa8d
9c1ad797ec8a5eddb37d34806c543602d9a6bf70
/monoidal_categories/monoidal_structure_from_products.lean
db196b82935d1af572ade38f1475812382eb42c0
[]
no_license
timjb/lean-category-theory
816eefc3a0582c22c05f4ee1c57ed04e57c0982f
12916cce261d08bb8740bc85e0175b75fb2a60f4
refs/heads/master
1,611,078,926,765
1,492,080,000,000
1,492,080,000,000
88,348,246
0
0
null
1,492,262,499,000
1,492,262,498,000
null
UTF-8
Lean
false
false
4,978
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison import .braided_monoidal_category import ..universal.universal open tqft.categories open tqft.categories.functor open tqft.categories.products open tqft.categories.natural_transformation open tqft.categories.monoidal_category open tqft.categories.universal namespace tqft.categories.monoidal_category -- PROJECT @[pointwise] definition left_associated_triple_Product_projection_1 { C : Category } [ has_FiniteProducts C ] { X Y Z : C.Obj } : C.Hom (product (product X Y).product Z).product X := C.compose (Product.left_projection _) (Product.left_projection _) @[pointwise] definition left_associated_triple_Product_projection_2 { C : Category } [ has_FiniteProducts C ] { X Y Z : C.Obj } : C.Hom (product (product X Y).product Z).product Y := C.compose (Product.left_projection _) (Product.right_projection _) @[pointwise] definition right_associated_triple_Product_projection_2 { C : Category } [ has_FiniteProducts C ] { X Y Z : C.Obj } : C.Hom (product X (product Y Z).product).product Y := C.compose (Product.right_projection _) (Product.left_projection _) @[pointwise] definition right_associated_triple_Product_projection_3 { C : Category } [ has_FiniteProducts C ] { X Y Z : C.Obj } : C.Hom (product X (product Y Z).product).product Z := C.compose (Product.right_projection _) (Product.right_projection _) @[simp] lemma left_factorisation_associated_1 { C : Category } [ has_FiniteProducts C ] { W X Y Z : C.Obj } ( h : C.Hom W Z ) ( f : C.Hom Z X ) ( g : C.Hom Z Y ) : C.compose (C.compose h ((product X Y).map f g)) (product X Y).left_projection = C.compose h f := begin rewrite C.associativity, simp end @[simp] lemma left_factorisation_associated_2 { C : Category } [ has_FiniteProducts C ] { W X Y Z : C.Obj } ( h : C.Hom X W ) ( f : C.Hom Z X ) ( g : C.Hom Z Y ) : C.compose ((product X Y).map f g) (C.compose (product X Y).left_projection h) = C.compose f h := begin rewrite - C.associativity, simp end @[simp] lemma right_factorisation_associated_1 { C : Category } [ has_FiniteProducts C ] { W X Y Z : C.Obj } ( h : C.Hom W Z ) ( f : C.Hom Z X ) ( g : C.Hom Z Y ) : C.compose (C.compose h ((product X Y).map f g)) (product X Y).right_projection = C.compose h g := begin rewrite C.associativity, simp end @[simp] lemma right_factorisation_associated_2 { C : Category } [ has_FiniteProducts C ] { W X Y Z : C.Obj } ( h : C.Hom Y W ) ( f : C.Hom Z X ) ( g : C.Hom Z Y ) : C.compose ((product X Y).map f g) (C.compose (product X Y).right_projection h) = C.compose g h := begin rewrite - C.associativity, simp end open tactic namespace tactic meta def erewrite (th_name : name) : tactic unit := do th ← mk_const th_name, rewrite_core semireducible tt tt occurrences.all ff th, trace ("successful ewrite along " ++ to_string th_name), try (reflexivity reducible) meta def trace_number_of_goals : tactic unit := do goals ← get_goals, trace (list.length goals) meta def factorisation : tactic unit := repeat ( trace_number_of_goals >> ( simp <|> tactic.rewrite ``Category.associativity) <|> (erewrite ``left_factorisation_associated_1) <|> (erewrite ``left_factorisation_associated_2) <|> (erewrite ``right_factorisation_associated_1) <|> (erewrite ``right_factorisation_associated_2)) meta def foo : tactic unit := trace_number_of_goals >> intros >> ( (tactic.interactive.force dsimp) <|> (tactic.interactive.force (pointwise tactic.skip)) <|> (tactic.interactive.force tactic.factorisation) <|> (tactic.interactive.force dunfold_everything) ) end tactic -- set_option pp.implicit true definition TensorProduct_from_Products ( C : Category ) [ has_FiniteProducts C ] : TensorProduct C := { onObjects := λ p, (product p.1 p.2).product, onMorphisms := λ X Y f, ((product Y.1 Y.2).map (C.compose (product X.1 X.2).left_projection (f.1)) (C.compose (product X.1 X.2).right_projection (f.2)) ), identities := ♯, functoriality := ♯ } -- FIXME this apparently gets stuck. :-( -- definition Associator_for_Products ( C : Category ) [ has_FiniteProducts C ] : Associator (TensorProduct_from_Products C) := -- begin -- repeat { tactic.foo }, -- end -- definition LeftUnitor_for_Products ( C : Category ) [ has_FiniteProducts C ] : LeftUnitor terminal_object (TensorProduct_from_Products C) := -- begin -- repeat { tactic.foo }, -- end -- definition RightUnitor_for_Products ( C : Category ) [ has_FiniteProducts C ] : RightUnitor terminal_object (TensorProduct_from_Products C) := -- begin -- repeat { tactic.foo }, -- end -- PROJECT show that this monoidal structure is uniquely braided -- PROJECT and that braiding is symmetric end tqft.categories.monoidal_category
11863a9238c9cdc6d9b1318e981a04858874e546
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/linear_algebra/matrix/block.lean
d7fce563c677247e7a699e646b0234a7f5f23fac
[ "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,914
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Patrick Massot, Casper Putz, Anne Baanen -/ import linear_algebra.matrix.determinant /-! # Block matrices and their determinant This file defines a predicate `matrix.block_triangular_matrix` saying a matrix is block triangular, and proves the value of the determinant for various matrices built out of blocks. ## Main definitions * `matrix.block_triangular_matrix` expresses that a `o` by `o` matrix is block triangular, if the rows and columns are ordered according to some order `b : o → ℕ` ## Main results * `det_of_block_triangular_matrix`: the determinant of a block triangular matrix is equal to the product of the determinants of all the blocks * `det_of_upper_triangular` and `det_of_lower_triangular`: the determinant of a triangular matrix is the product of the entries along the diagonal ## Tags matrix, diagonal, det, block triangular -/ open_locale big_operators universes v variables {m n : Type*} [decidable_eq n] [fintype n] [decidable_eq m] [fintype m] variables {R : Type v} [comm_ring R] namespace matrix lemma det_to_block (M : matrix m m R) (p : m → Prop) [decidable_pred p] : M.det = (matrix.from_blocks (to_block M p p) (to_block M p (λ j, ¬p j)) (to_block M (λ j, ¬p j) p) (to_block M (λ j, ¬p j) (λ j, ¬p j))).det := begin rw ← matrix.det_reindex_self (equiv.sum_compl p).symm M, rw [det_apply', det_apply'], congr, ext σ, congr, ext, generalize hy : σ x = y, cases x; cases y; simp only [matrix.reindex_apply, to_block_apply, equiv.symm_symm, equiv.sum_compl_apply_inr, equiv.sum_compl_apply_inl, from_blocks_apply₁₁, from_blocks_apply₁₂, from_blocks_apply₂₁, from_blocks_apply₂₂, matrix.minor_apply], end lemma det_to_square_block (M : matrix m m R) {n : nat} (b : m → fin n) (k : fin n) : (to_square_block M b k).det = (to_square_block_prop M (λ i, b i = k)).det := by simp lemma det_to_square_block' (M : matrix m m R) (b : m → ℕ) (k : ℕ) : (to_square_block' M b k).det = (to_square_block_prop M (λ i, b i = k)).det := by simp lemma two_block_triangular_det (M : matrix m m R) (p : m → Prop) [decidable_pred p] (h : ∀ i (h1 : ¬p i) j (h2 : p j), M i j = 0) : M.det = (to_square_block_prop M p).det * (to_square_block_prop M (λ i, ¬p i)).det := begin rw det_to_block M p, convert upper_two_block_triangular_det (to_block M p p) (to_block M p (λ j, ¬p j)) (to_block M (λ j, ¬p j) (λ j, ¬p j)), ext, exact h ↑i i.2 ↑j j.2 end lemma equiv_block_det (M : matrix m m R) {p q : m → Prop} [decidable_pred p] [decidable_pred q] (e : ∀x, q x ↔ p x) : (to_square_block_prop M p).det = (to_square_block_prop M q).det := by convert matrix.det_reindex_self (equiv.subtype_equiv_right e) (to_square_block_prop M q) lemma to_square_block_det'' (M : matrix m m R) {n : nat} (b : m → fin n) (k : fin n) : (to_square_block M b k).det = (to_square_block' M (λ i, ↑(b i)) ↑k).det := begin rw [to_square_block_def', to_square_block_def], apply equiv_block_det, intro x, apply (fin.ext_iff _ _).symm end /-- Let `b` map rows and columns of a square matrix `M` to `n` blocks. Then `block_triangular_matrix' M n b` says the matrix is block triangular. -/ def block_triangular_matrix' {o : Type*} [fintype o] (M : matrix o o R) {n : ℕ} (b : o → fin n) : Prop := ∀ i j, b j < b i → M i j = 0 lemma upper_two_block_triangular' {m n : Type*} [fintype m] [fintype n] (A : matrix m m R) (B : matrix m n R) (D : matrix n n R) : block_triangular_matrix' (from_blocks A B 0 D) (sum.elim (λ i, (0 : fin 2)) (λ j, 1)) := begin intros k1 k2 hk12, have h0 : ∀ (k : m ⊕ n), sum.elim (λ i, (0 : fin 2)) (λ j, 1) k = 0 → ∃ i, k = sum.inl i, { simp }, have h1 : ∀ (k : m ⊕ n), sum.elim (λ i, (0 : fin 2)) (λ j, 1) k = 1 → ∃ j, k = sum.inr j, { simp }, set mk1 := (sum.elim (λ i, (0 : fin 2)) (λ j, 1)) k1 with hmk1, set mk2 := (sum.elim (λ i, (0 : fin 2)) (λ j, 1)) k2 with hmk2, fin_cases mk1; fin_cases mk2; rw [h, h_1] at hk12, { exact absurd hk12 (nat.not_lt_zero 0) }, { exact absurd hk12 (by norm_num) }, { rw hmk1 at h, obtain ⟨i, hi⟩ := h1 k1 h, rw hmk2 at h_1, obtain ⟨j, hj⟩ := h0 k2 h_1, rw [hi, hj], simp }, { exact absurd hk12 (irrefl 1) } end /-- Let `b` map rows and columns of a square matrix `M` to blocks indexed by `ℕ`s. Then `block_triangular_matrix M n b` says the matrix is block triangular. -/ def block_triangular_matrix {o : Type*} [fintype o] (M : matrix o o R) (b : o → ℕ) : Prop := ∀ i j, b j < b i → M i j = 0 lemma upper_two_block_triangular {m n : Type*} [fintype m] [fintype n] (A : matrix m m R) (B : matrix m n R) (D : matrix n n R) : block_triangular_matrix (from_blocks A B 0 D) (sum.elim (λ i, 0) (λ j, 1)) := begin intros k1 k2 hk12, have h01 : ∀ (k : m ⊕ n), sum.elim (λ i, 0) (λ j, 1) k = 0 ∨ sum.elim (λ i, 0) (λ j, 1) k = 1, { simp }, have h0 : ∀ (k : m ⊕ n), sum.elim (λ i, 0) (λ j, 1) k = 0 → ∃ i, k = sum.inl i, { simp }, have h1 : ∀ (k : m ⊕ n), sum.elim (λ i, 0) (λ j, 1) k = 1 → ∃ j, k = sum.inr j, { simp }, cases (h01 k1) with hk1 hk1; cases (h01 k2) with hk2 hk2; rw [hk1, hk2] at hk12, { exact absurd hk12 (nat.not_lt_zero 0) }, { exact absurd hk12 (nat.not_lt_zero 1) }, { obtain ⟨i, hi⟩ := h1 k1 hk1, obtain ⟨j, hj⟩ := h0 k2 hk2, rw [hi, hj], simp }, { exact absurd hk12 (irrefl 1) } end lemma det_of_block_triangular_matrix (M : matrix m m R) (b : m → ℕ) (h : block_triangular_matrix M b) : ∀ (n : ℕ) (hn : ∀ i, b i < n), M.det = ∏ k in finset.range n, (to_square_block' M b k).det := begin intros n hn, tactic.unfreeze_local_instances, induction n with n hi generalizing m M b, { rw finset.prod_range_zero, apply det_eq_one_of_card_eq_zero, apply fintype.card_eq_zero_iff.mpr, exact ⟨λ i, nat.not_lt_zero (b i) (hn i)⟩ }, { rw [finset.prod_range_succ_comm], have h2 : (M.to_square_block_prop (λ (i : m), b i = n.succ)).det = (M.to_square_block' b n.succ).det, { dunfold to_square_block', dunfold to_square_block_prop, refl }, rw two_block_triangular_det M (λ i, ¬(b i = n)), { rw mul_comm, apply congr (congr_arg has_mul.mul _), { let m' := {a // ¬b a = n }, let b' := (λ (i : m'), b ↑i), have h' : block_triangular_matrix (M.to_square_block_prop (λ (i : m), ¬b i = n)) b', { intros i j, apply h ↑i ↑j }, have hni : ∀ (i : {a // ¬b a = n}), b' i < n, { exact λ i, (ne.le_iff_lt i.property).mp (nat.lt_succ_iff.mp (hn ↑i)) }, have h1 := hi (M.to_square_block_prop (λ (i : m), ¬b i = n)) b' h' hni, rw ←fin.prod_univ_eq_prod_range at h1 ⊢, convert h1, ext k, simp only [to_square_block_def', to_square_block_def], let he : {a // b' a = ↑k} ≃ {a // b a = ↑k}, { have hc : ∀ (i : m), (λ a, b a = ↑k) i → (λ a, ¬b a = n) i, { intros i hbi, rw hbi, exact ne_of_lt (fin.is_lt k) }, exact equiv.subtype_subtype_equiv_subtype hc }, exact matrix.det_reindex_self he (λ (i j : {a // b' a = ↑k}), M ↑i ↑j) }, { rw det_to_square_block' M b n, have hh : ∀ a, b a = n ↔ ¬(λ (i : m), ¬b i = n) a, { intro i, simp only [not_not] }, exact equiv_block_det M hh }}, { intros i hi j hj, apply (h i), simp only [not_not] at hi, rw hi, exact (ne.le_iff_lt hj).mp (nat.lt_succ_iff.mp (hn j)) }} end lemma det_of_block_triangular_matrix'' (M : matrix m m R) (b : m → ℕ) (h : block_triangular_matrix M b) : M.det = ∏ k in finset.image b finset.univ, (to_square_block' M b k).det := begin let n : ℕ := (Sup (finset.image b finset.univ : set ℕ)).succ, have hn : ∀ i, b i < n, { have hbi : ∀ i, b i ∈ finset.image b finset.univ, { simp }, intro i, dsimp only [n], apply nat.lt_succ_iff.mpr, exact le_cSup (finset.bdd_above _) (hbi i) }, rw det_of_block_triangular_matrix M b h n hn, refine (finset.prod_subset _ _).symm, { intros a ha, apply finset.mem_range.mpr, obtain ⟨i, ⟨hi, hbi⟩⟩ := finset.mem_image.mp ha, rw ←hbi, exact hn i }, { intros k hk hbk, apply det_eq_one_of_card_eq_zero, apply fintype.card_eq_zero_iff.mpr, constructor, simp only [subtype.forall], intros a hba, apply hbk, apply finset.mem_image.mpr, use a, exact ⟨finset.mem_univ a, hba⟩ } end lemma det_of_block_triangular_matrix' (M : matrix m m R) {n : ℕ} (b : m → fin n) (h : block_triangular_matrix' M b) : M.det = ∏ (k : fin n), (to_square_block M b k).det := begin let b2 : m → ℕ := λ i, ↑(b i), simp_rw to_square_block_det'', rw fin.prod_univ_eq_prod_range (λ (k : ℕ), (M.to_square_block' b2 k).det) n, apply det_of_block_triangular_matrix, { intros i j hij, exact h i j (fin.coe_fin_lt.mp hij) }, { intro i, exact fin.is_lt (b i) } end lemma det_of_upper_triangular {n : ℕ} (M : matrix (fin n) (fin n) R) (h : ∀ (i j : fin n), j < i → M i j = 0) : M.det = ∏ i : (fin n), M i i := begin convert det_of_block_triangular_matrix' M id h, ext i, have h2 : ∀ (j : {a // id a = i}), j = ⟨i, rfl⟩ := λ (j : {a // id a = i}), subtype.ext j.property, haveI : unique {a // id a = i} := ⟨⟨⟨i, rfl⟩⟩, h2⟩, simp [h2 (default {a // id a = i})] end lemma det_of_lower_triangular {n : ℕ} (M : matrix (fin n) (fin n) R) (h : ∀ (i j : fin n), i < j → M i j = 0) : M.det = ∏ i : (fin n), M i i := begin rw ← det_transpose, exact det_of_upper_triangular _ (λ (i j : fin n) (hji : j < i), h j i hji) end end matrix
ae717d27b6090e7a8c4fa17d8d5d9fdf3d20fb54
3c9dc4ea6cc92e02634ef557110bde9eae393338
/src/Lean/Elab/Util.lean
6994b63425968e83706df5784d26fd1b1f1ebad9
[ "Apache-2.0" ]
permissive
shingtaklam1324/lean4
3d7efe0c8743a4e33d3c6f4adbe1300df2e71492
351285a2e8ad0cef37af05851cfabf31edfb5970
refs/heads/master
1,676,827,679,740
1,610,462,623,000
1,610,552,340,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,596
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Util.Trace import Lean.Parser.Syntax import Lean.Parser.Extension import Lean.KeyedDeclsAttribute import Lean.Elab.Exception namespace Lean def Syntax.prettyPrint (stx : Syntax) : Format := match stx.unsetTrailing.reprint with -- TODO use syntax pretty printer | some str => format str.toFormat | none => format stx def MacroScopesView.format (view : MacroScopesView) (mainModule : Name) : Format := fmt $ if view.scopes.isEmpty then view.name else if view.mainModule == mainModule then view.scopes.foldl Name.mkNum (view.name ++ view.imported) else view.scopes.foldl Name.mkNum (view.name ++ view.imported ++ view.mainModule) namespace Elab def expandOptNamedPrio (stx : Syntax) : MacroM Nat := if stx.isNone then return evalPrio! default else match stx[0] with | `(Parser.Command.namedPrio| (priority := $prio)) => evalPrio prio | _ => Macro.throwUnsupported def expandOptNamedName (stx : Syntax) : MacroM (Option Name) := do if stx.isNone then return none else match stx[0] with | `(Parser.Command.namedName| (name := $name)) => return name.getId | _ => Macro.throwUnsupported structure MacroStackElem where before : Syntax after : Syntax abbrev MacroStack := List MacroStackElem /- If `ref` does not have position information, then try to use macroStack -/ def getBetterRef (ref : Syntax) (macroStack : MacroStack) : Syntax := match ref.getPos with | some _ => ref | none => match macroStack.find? (·.before.getPos != none) with | some elem => elem.before | none => ref def ppMacroStackDefault := false def getMacroStackOption (o : Options) : Bool:= o.get `pp.macroStack ppMacroStackDefault def setMacroStackOption (o : Options) (flag : Bool) : Options := o.setBool `pp.macroStack flag builtin_initialize registerOption `pp.macroStack { defValue := ppMacroStackDefault, group := "pp", descr := "dispaly macro expansion stack" } def addMacroStack {m} [Monad m] [MonadOptions m] (msgData : MessageData) (macroStack : MacroStack) : m MessageData := do if !getMacroStackOption (← getOptions) then pure msgData else match macroStack with | [] => pure msgData | stack@(top::_) => let msgData := msgData ++ Format.line ++ "with resulting expansion" ++ indentD top.after pure $ stack.foldl (fun (msgData : MessageData) (elem : MacroStackElem) => msgData ++ Format.line ++ "while expanding" ++ indentD elem.before) msgData def checkSyntaxNodeKind (k : Name) : AttrM Name := do if Parser.isValidSyntaxNodeKind (← getEnv) k then pure k else throwError "failed" def checkSyntaxNodeKindAtNamespacesAux (k : Name) : Name → AttrM Name | n@(Name.str p _ _) => checkSyntaxNodeKind (n ++ k) <|> checkSyntaxNodeKindAtNamespacesAux k p | _ => throwError "failed" def checkSyntaxNodeKindAtNamespaces (k : Name) : AttrM Name := do let ctx ← read checkSyntaxNodeKindAtNamespacesAux k ctx.currNamespace def syntaxNodeKindOfAttrParam (defaultParserNamespace : Name) (stx : Syntax) : AttrM SyntaxNodeKind := do let k ← Attribute.Builtin.getId stx checkSyntaxNodeKind k <|> checkSyntaxNodeKindAtNamespaces k <|> checkSyntaxNodeKind (defaultParserNamespace ++ k) <|> throwError! "invalid syntax node kind '{k}'" private unsafe def evalSyntaxConstantUnsafe (env : Environment) (opts : Options) (constName : Name) : ExceptT String Id Syntax := env.evalConstCheck Syntax opts `Lean.Syntax constName @[implementedBy evalSyntaxConstantUnsafe] constant evalSyntaxConstant (env : Environment) (opts : Options) (constName : Name) : ExceptT String Id Syntax := throw "" unsafe def mkElabAttribute (γ) (attrDeclName attrBuiltinName attrName : Name) (parserNamespace : Name) (typeName : Name) (kind : String) : IO (KeyedDeclsAttribute γ) := KeyedDeclsAttribute.init { builtinName := attrBuiltinName name := attrName descr := kind ++ " elaborator" valueTypeName := typeName evalKey := fun _ stx => syntaxNodeKindOfAttrParam parserNamespace stx } attrDeclName unsafe def mkMacroAttributeUnsafe : IO (KeyedDeclsAttribute Macro) := mkElabAttribute Macro `Lean.Elab.macroAttribute `builtinMacro `macro Name.anonymous `Lean.Macro "macro" @[implementedBy mkMacroAttributeUnsafe] constant mkMacroAttribute : IO (KeyedDeclsAttribute Macro) builtin_initialize macroAttribute : KeyedDeclsAttribute Macro ← mkMacroAttribute private def expandMacroFns (stx : Syntax) : List Macro → MacroM Syntax | [] => throw Macro.Exception.unsupportedSyntax | m::ms => do try m stx catch | Macro.Exception.unsupportedSyntax => expandMacroFns stx ms | ex => throw ex def getMacros (env : Environment) : Macro := fun stx => let k := stx.getKind let table := (macroAttribute.ext.getState env).table match table.find? k with | some macroFns => expandMacroFns stx macroFns | none => throw Macro.Exception.unsupportedSyntax class MonadMacroAdapter (m : Type → Type) where getCurrMacroScope : m MacroScope getNextMacroScope : m MacroScope setNextMacroScope : MacroScope → m Unit instance (m n) [MonadMacroAdapter m] [MonadLift m n] : MonadMacroAdapter n := { getCurrMacroScope := liftM (MonadMacroAdapter.getCurrMacroScope : m _), getNextMacroScope := liftM (MonadMacroAdapter.getNextMacroScope : m _), setNextMacroScope := fun s => liftM (MonadMacroAdapter.setNextMacroScope s : m _) } private def expandMacro? (env : Environment) (stx : Syntax) : MacroM (Option Syntax) := do try let newStx ← getMacros env stx pure (some newStx) catch | Macro.Exception.unsupportedSyntax => pure none | ex => throw ex @[inline] def liftMacroM {α} {m : Type → Type} [Monad m] [MonadMacroAdapter m] [MonadEnv m] [MonadRecDepth m] [MonadError m] (x : MacroM α) : m α := do let env ← getEnv match x { macroEnv := Macro.mkMacroEnv (expandMacro? env), ref := ← getRef, currMacroScope := ← MonadMacroAdapter.getCurrMacroScope, mainModule := env.mainModule, currRecDepth := ← MonadRecDepth.getRecDepth, maxRecDepth := ← MonadRecDepth.getMaxRecDepth } (← MonadMacroAdapter.getNextMacroScope) with | EStateM.Result.error Macro.Exception.unsupportedSyntax _ => throwUnsupportedSyntax | EStateM.Result.error (Macro.Exception.error ref msg) _ => throwErrorAt ref msg | EStateM.Result.ok a nextMacroScope => MonadMacroAdapter.setNextMacroScope nextMacroScope; pure a @[inline] def adaptMacro {m : Type → Type} [Monad m] [MonadMacroAdapter m] [MonadEnv m] [MonadRecDepth m] [MonadError m] (x : Macro) (stx : Syntax) : m Syntax := liftMacroM (x stx) partial def mkUnusedBaseName [Monad m] [MonadEnv m] [MonadResolveName m] (baseName : Name) : m Name := do let currNamespace ← getCurrNamespace let env ← getEnv if env.contains (currNamespace ++ baseName) then let rec loop (idx : Nat) := let name := baseName.appendIndexAfter idx if env.contains (currNamespace ++ name) then loop (idx+1) else name return loop 1 else return baseName builtin_initialize registerTraceClass `Elab registerTraceClass `Elab.step end Lean.Elab
76700c1232d87a33d2b094551979608fa45951ea
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/geometry/euclidean/monge_point.lean
b5713ba092a1579c2ce4f6cd12dc6d313cdebf84
[ "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
38,061
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers -/ import geometry.euclidean.circumcenter /-! # Monge point and orthocenter This file defines the orthocenter of a triangle, via its n-dimensional generalization, the Monge point of a simplex. ## Main definitions * `monge_point` is the Monge point of a simplex, defined in terms of its position on the Euler line and then shown to be the point of concurrence of the Monge planes. * `monge_plane` is a Monge plane of an (n+2)-simplex, which is the (n+1)-dimensional affine subspace of the subspace spanned by the simplex that passes through the centroid of an n-dimensional face and is orthogonal to the opposite edge (in 2 dimensions, this is the same as an altitude). * `altitude` is the line that passes through a vertex of a simplex and is orthogonal to the opposite face. * `orthocenter` is defined, for the case of a triangle, to be the same as its Monge point, then shown to be the point of concurrence of the altitudes. * `orthocentric_system` is a predicate on sets of points that says whether they are four points, one of which is the orthocenter of the other three (in which case various other properties hold, including that each is the orthocenter of the other three). ## References * <https://en.wikipedia.org/wiki/Altitude_(triangle)> * <https://en.wikipedia.org/wiki/Monge_point> * <https://en.wikipedia.org/wiki/Orthocentric_system> * Małgorzata Buba-Brzozowa, [The Monge Point and the 3(n+1) Point Sphere of an n-Simplex](https://pdfs.semanticscholar.org/6f8b/0f623459c76dac2e49255737f8f0f4725d16.pdf) -/ noncomputable theory open_locale big_operators open_locale classical open_locale real_inner_product_space namespace affine namespace simplex open finset affine_subspace euclidean_geometry points_with_circumcenter_index variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] include V /-- The Monge point of a simplex (in 2 or more dimensions) is a generalization of the orthocenter of a triangle. It is defined to be the intersection of the Monge planes, where a Monge plane is the (n-1)-dimensional affine subspace of the subspace spanned by the simplex that passes through the centroid of an (n-2)-dimensional face and is orthogonal to the opposite edge (in 2 dimensions, this is the same as an altitude). The circumcenter O, centroid G and Monge point M are collinear in that order on the Euler line, with OG : GM = (n-1) : 2. Here, we use that ratio to define the Monge point (so resulting in a point that equals the centroid in 0 or 1 dimensions), and then show in subsequent lemmas that the point so defined lies in the Monge planes and is their unique point of intersection. -/ def monge_point {n : ℕ} (s : simplex ℝ P n) : P := (((n + 1 : ℕ) : ℝ) / (((n - 1) : ℕ) : ℝ)) • ((univ : finset (fin (n + 1))).centroid ℝ s.points -ᵥ s.circumcenter) +ᵥ s.circumcenter /-- The position of the Monge point in relation to the circumcenter and centroid. -/ lemma monge_point_eq_smul_vsub_vadd_circumcenter {n : ℕ} (s : simplex ℝ P n) : s.monge_point = (((n + 1 : ℕ) : ℝ) / (((n - 1) : ℕ) : ℝ)) • ((univ : finset (fin (n + 1))).centroid ℝ s.points -ᵥ s.circumcenter) +ᵥ s.circumcenter := rfl /-- The Monge point lies in the affine span. -/ lemma monge_point_mem_affine_span {n : ℕ} (s : simplex ℝ P n) : s.monge_point ∈ affine_span ℝ (set.range s.points) := smul_vsub_vadd_mem _ _ (centroid_mem_affine_span_of_card_eq_add_one ℝ _ (card_fin (n + 1))) s.circumcenter_mem_affine_span s.circumcenter_mem_affine_span /-- Two simplices with the same points have the same Monge point. -/ lemma monge_point_eq_of_range_eq {n : ℕ} {s₁ s₂ : simplex ℝ P n} (h : set.range s₁.points = set.range s₂.points) : s₁.monge_point = s₂.monge_point := by simp_rw [monge_point_eq_smul_vsub_vadd_circumcenter, centroid_eq_of_range_eq h, circumcenter_eq_of_range_eq h] omit V /-- The weights for the Monge point of an (n+2)-simplex, in terms of `points_with_circumcenter`. -/ def monge_point_weights_with_circumcenter (n : ℕ) : points_with_circumcenter_index (n + 2) → ℝ | (point_index i) := (((n + 1) : ℕ) : ℝ)⁻¹ | circumcenter_index := (-2 / (((n + 1) : ℕ) : ℝ)) /-- `monge_point_weights_with_circumcenter` sums to 1. -/ @[simp] lemma sum_monge_point_weights_with_circumcenter (n : ℕ) : ∑ i, monge_point_weights_with_circumcenter n i = 1 := begin simp_rw [sum_points_with_circumcenter, monge_point_weights_with_circumcenter, sum_const, card_fin, nsmul_eq_mul], have hn1 : (n + 1 : ℝ) ≠ 0, { exact_mod_cast nat.succ_ne_zero _ }, field_simp [hn1], ring end include V /-- The Monge point of an (n+2)-simplex, in terms of `points_with_circumcenter`. -/ lemma monge_point_eq_affine_combination_of_points_with_circumcenter {n : ℕ} (s : simplex ℝ P (n + 2)) : s.monge_point = (univ : finset (points_with_circumcenter_index (n + 2))).affine_combination s.points_with_circumcenter (monge_point_weights_with_circumcenter n) := begin rw [monge_point_eq_smul_vsub_vadd_circumcenter, centroid_eq_affine_combination_of_points_with_circumcenter, circumcenter_eq_affine_combination_of_points_with_circumcenter, affine_combination_vsub, ←linear_map.map_smul, weighted_vsub_vadd_affine_combination], congr' with i, rw [pi.add_apply, pi.smul_apply, smul_eq_mul, pi.sub_apply], have hn1 : (n + 1 : ℝ) ≠ 0, { exact_mod_cast nat.succ_ne_zero _ }, cases i; simp_rw [centroid_weights_with_circumcenter, circumcenter_weights_with_circumcenter, monge_point_weights_with_circumcenter]; rw [add_tsub_assoc_of_le (dec_trivial : 1 ≤ 2), (dec_trivial : 2 - 1 = 1)], { rw [if_pos (mem_univ _), sub_zero, add_zero, card_fin], have hn3 : (n + 2 + 1 : ℝ) ≠ 0, { exact_mod_cast nat.succ_ne_zero _ }, field_simp [hn1, hn3, mul_comm] }, { field_simp [hn1], ring } end omit V /-- The weights for the Monge point of an (n+2)-simplex, minus the centroid of an n-dimensional face, in terms of `points_with_circumcenter`. This definition is only valid when `i₁ ≠ i₂`. -/ def monge_point_vsub_face_centroid_weights_with_circumcenter {n : ℕ} (i₁ i₂ : fin (n + 3)) : points_with_circumcenter_index (n + 2) → ℝ | (point_index i) := if i = i₁ ∨ i = i₂ then (((n + 1) : ℕ) : ℝ)⁻¹ else 0 | circumcenter_index := (-2 / (((n + 1) : ℕ) : ℝ)) /-- `monge_point_vsub_face_centroid_weights_with_circumcenter` is the result of subtracting `centroid_weights_with_circumcenter` from `monge_point_weights_with_circumcenter`. -/ lemma monge_point_vsub_face_centroid_weights_with_circumcenter_eq_sub {n : ℕ} {i₁ i₂ : fin (n + 3)} (h : i₁ ≠ i₂) : monge_point_vsub_face_centroid_weights_with_circumcenter i₁ i₂ = monge_point_weights_with_circumcenter n - centroid_weights_with_circumcenter ({i₁, i₂}ᶜ) := begin ext i, cases i, { rw [pi.sub_apply, monge_point_weights_with_circumcenter, centroid_weights_with_circumcenter, monge_point_vsub_face_centroid_weights_with_circumcenter], have hu : card ({i₁, i₂}ᶜ : finset (fin (n + 3))) = n + 1, { simp [card_compl, fintype.card_fin, h] }, rw hu, by_cases hi : i = i₁ ∨ i = i₂; simp [compl_eq_univ_sdiff, hi] }, { simp [monge_point_weights_with_circumcenter, centroid_weights_with_circumcenter, monge_point_vsub_face_centroid_weights_with_circumcenter] } end /-- `monge_point_vsub_face_centroid_weights_with_circumcenter` sums to 0. -/ @[simp] lemma sum_monge_point_vsub_face_centroid_weights_with_circumcenter {n : ℕ} {i₁ i₂ : fin (n + 3)} (h : i₁ ≠ i₂) : ∑ i, monge_point_vsub_face_centroid_weights_with_circumcenter i₁ i₂ i = 0 := begin rw monge_point_vsub_face_centroid_weights_with_circumcenter_eq_sub h, simp_rw [pi.sub_apply, sum_sub_distrib, sum_monge_point_weights_with_circumcenter], rw [sum_centroid_weights_with_circumcenter, sub_self], simp [←card_pos, card_compl, h] end include V /-- The Monge point of an (n+2)-simplex, minus the centroid of an n-dimensional face, in terms of `points_with_circumcenter`. -/ lemma monge_point_vsub_face_centroid_eq_weighted_vsub_of_points_with_circumcenter {n : ℕ} (s : simplex ℝ P (n + 2)) {i₁ i₂ : fin (n + 3)} (h : i₁ ≠ i₂) : s.monge_point -ᵥ ({i₁, i₂}ᶜ : finset (fin (n + 3))).centroid ℝ s.points = (univ : finset (points_with_circumcenter_index (n + 2))).weighted_vsub s.points_with_circumcenter (monge_point_vsub_face_centroid_weights_with_circumcenter i₁ i₂) := by simp_rw [monge_point_eq_affine_combination_of_points_with_circumcenter, centroid_eq_affine_combination_of_points_with_circumcenter, affine_combination_vsub, monge_point_vsub_face_centroid_weights_with_circumcenter_eq_sub h] /-- The Monge point of an (n+2)-simplex, minus the centroid of an n-dimensional face, is orthogonal to the difference of the two vertices not in that face. -/ lemma inner_monge_point_vsub_face_centroid_vsub {n : ℕ} (s : simplex ℝ P (n + 2)) {i₁ i₂ : fin (n + 3)} : ⟪s.monge_point -ᵥ ({i₁, i₂}ᶜ : finset (fin (n + 3))).centroid ℝ s.points, s.points i₁ -ᵥ s.points i₂⟫ = 0 := begin by_cases h : i₁ = i₂, { simp [h], }, simp_rw [monge_point_vsub_face_centroid_eq_weighted_vsub_of_points_with_circumcenter s h, point_eq_affine_combination_of_points_with_circumcenter, affine_combination_vsub], have hs : ∑ i, (point_weights_with_circumcenter i₁ - point_weights_with_circumcenter i₂) i = 0, { simp }, rw [inner_weighted_vsub _ (sum_monge_point_vsub_face_centroid_weights_with_circumcenter h) _ hs, sum_points_with_circumcenter, points_with_circumcenter_eq_circumcenter], simp only [monge_point_vsub_face_centroid_weights_with_circumcenter, points_with_circumcenter_point], let fs : finset (fin (n + 3)) := {i₁, i₂}, have hfs : ∀ i : fin (n + 3), i ∉ fs → (i ≠ i₁ ∧ i ≠ i₂), { intros i hi, split ; { intro hj, simpa [←hj] using hi } }, rw ←sum_subset fs.subset_univ _, { simp_rw [sum_points_with_circumcenter, points_with_circumcenter_eq_circumcenter, points_with_circumcenter_point, pi.sub_apply, point_weights_with_circumcenter], rw [←sum_subset fs.subset_univ _], { simp_rw [sum_insert (not_mem_singleton.2 h), sum_singleton], repeat { rw ←sum_subset fs.subset_univ _ }, { simp_rw [sum_insert (not_mem_singleton.2 h), sum_singleton], simp [h, ne.symm h, dist_comm (s.points i₁)] }, all_goals { intros i hu hi, simp [hfs i hi] } }, { intros i hu hi, simp [hfs i hi, point_weights_with_circumcenter] } }, { intros i hu hi, simp [hfs i hi] } end /-- A Monge plane of an (n+2)-simplex is the (n+1)-dimensional affine subspace of the subspace spanned by the simplex that passes through the centroid of an n-dimensional face and is orthogonal to the opposite edge (in 2 dimensions, this is the same as an altitude). This definition is only intended to be used when `i₁ ≠ i₂`. -/ def monge_plane {n : ℕ} (s : simplex ℝ P (n + 2)) (i₁ i₂ : fin (n + 3)) : affine_subspace ℝ P := mk' (({i₁, i₂}ᶜ : finset (fin (n + 3))).centroid ℝ s.points) (ℝ ∙ (s.points i₁ -ᵥ s.points i₂))ᗮ ⊓ affine_span ℝ (set.range s.points) /-- The definition of a Monge plane. -/ lemma monge_plane_def {n : ℕ} (s : simplex ℝ P (n + 2)) (i₁ i₂ : fin (n + 3)) : s.monge_plane i₁ i₂ = mk' (({i₁, i₂}ᶜ : finset (fin (n + 3))).centroid ℝ s.points) (ℝ ∙ (s.points i₁ -ᵥ s.points i₂))ᗮ ⊓ affine_span ℝ (set.range s.points) := rfl /-- The Monge plane associated with vertices `i₁` and `i₂` equals that associated with `i₂` and `i₁`. -/ lemma monge_plane_comm {n : ℕ} (s : simplex ℝ P (n + 2)) (i₁ i₂ : fin (n + 3)) : s.monge_plane i₁ i₂ = s.monge_plane i₂ i₁ := begin simp_rw monge_plane_def, congr' 3, { congr' 1, exact pair_comm _ _ }, { ext, simp_rw submodule.mem_span_singleton, split, all_goals { rintros ⟨r, rfl⟩, use -r, rw [neg_smul, ←smul_neg, neg_vsub_eq_vsub_rev] } } end /-- The Monge point lies in the Monge planes. -/ lemma monge_point_mem_monge_plane {n : ℕ} (s : simplex ℝ P (n + 2)) {i₁ i₂ : fin (n + 3)} : s.monge_point ∈ s.monge_plane i₁ i₂ := begin rw [monge_plane_def, mem_inf_iff, ←vsub_right_mem_direction_iff_mem (self_mem_mk' _ _), direction_mk', submodule.mem_orthogonal'], refine ⟨_, s.monge_point_mem_affine_span⟩, intros v hv, rcases submodule.mem_span_singleton.mp hv with ⟨r, rfl⟩, rw [inner_smul_right, s.inner_monge_point_vsub_face_centroid_vsub, mul_zero] end /-- The direction of a Monge plane. -/ lemma direction_monge_plane {n : ℕ} (s : simplex ℝ P (n + 2)) {i₁ i₂ : fin (n + 3)} : (s.monge_plane i₁ i₂).direction = (ℝ ∙ (s.points i₁ -ᵥ s.points i₂))ᗮ ⊓ vector_span ℝ (set.range s.points) := by rw [monge_plane_def, direction_inf_of_mem_inf s.monge_point_mem_monge_plane, direction_mk', direction_affine_span] /-- The Monge point is the only point in all the Monge planes from any one vertex. -/ lemma eq_monge_point_of_forall_mem_monge_plane {n : ℕ} {s : simplex ℝ P (n + 2)} {i₁ : fin (n + 3)} {p : P} (h : ∀ i₂, i₁ ≠ i₂ → p ∈ s.monge_plane i₁ i₂) : p = s.monge_point := begin rw ←@vsub_eq_zero_iff_eq V, have h' : ∀ i₂, i₁ ≠ i₂ → p -ᵥ s.monge_point ∈ (ℝ ∙ (s.points i₁ -ᵥ s.points i₂))ᗮ ⊓ vector_span ℝ (set.range s.points), { intros i₂ hne, rw [←s.direction_monge_plane, vsub_right_mem_direction_iff_mem s.monge_point_mem_monge_plane], exact h i₂ hne }, have hi : p -ᵥ s.monge_point ∈ ⨅ (i₂ : {i // i₁ ≠ i}), (ℝ ∙ (s.points i₁ -ᵥ s.points i₂))ᗮ, { rw submodule.mem_infi, exact λ i, (submodule.mem_inf.1 (h' i i.property)).1 }, rw [submodule.infi_orthogonal, ←submodule.span_Union] at hi, have hu : (⋃ (i : {i // i₁ ≠ i}), ({s.points i₁ -ᵥ s.points i} : set V)) = (-ᵥ) (s.points i₁) '' (s.points '' (set.univ \ {i₁})), { rw [set.image_image], ext x, simp_rw [set.mem_Union, set.mem_image, set.mem_singleton_iff, set.mem_diff_singleton], split, { rintros ⟨i, rfl⟩, use [i, ⟨set.mem_univ _, i.property.symm⟩] }, { rintros ⟨i, ⟨hiu, hi⟩, rfl⟩, use [⟨i, hi.symm⟩, rfl] } }, rw [hu, ←vector_span_image_eq_span_vsub_set_left_ne ℝ _ (set.mem_univ _), set.image_univ] at hi, have hv : p -ᵥ s.monge_point ∈ vector_span ℝ (set.range s.points), { let s₁ : finset (fin (n + 3)) := univ.erase i₁, obtain ⟨i₂, h₂⟩ := card_pos.1 (show 0 < card s₁, by simp [card_erase_of_mem]), have h₁₂ : i₁ ≠ i₂ := (ne_of_mem_erase h₂).symm, exact (submodule.mem_inf.1 (h' i₂ h₁₂)).2 }, exact submodule.disjoint_def.1 ((vector_span ℝ (set.range s.points)).orthogonal_disjoint) _ hv hi, end /-- An altitude of a simplex is the line that passes through a vertex and is orthogonal to the opposite face. -/ def altitude {n : ℕ} (s : simplex ℝ P (n + 1)) (i : fin (n + 2)) : affine_subspace ℝ P := mk' (s.points i) (affine_span ℝ (s.points '' ↑(univ.erase i))).directionᗮ ⊓ affine_span ℝ (set.range s.points) /-- The definition of an altitude. -/ lemma altitude_def {n : ℕ} (s : simplex ℝ P (n + 1)) (i : fin (n + 2)) : s.altitude i = mk' (s.points i) (affine_span ℝ (s.points '' ↑(univ.erase i))).directionᗮ ⊓ affine_span ℝ (set.range s.points) := rfl /-- A vertex lies in the corresponding altitude. -/ lemma mem_altitude {n : ℕ} (s : simplex ℝ P (n + 1)) (i : fin (n + 2)) : s.points i ∈ s.altitude i := (mem_inf_iff _ _ _).2 ⟨self_mem_mk' _ _, mem_affine_span ℝ (set.mem_range_self _)⟩ /-- The direction of an altitude. -/ lemma direction_altitude {n : ℕ} (s : simplex ℝ P (n + 1)) (i : fin (n + 2)) : (s.altitude i).direction = (vector_span ℝ (s.points '' ↑(finset.univ.erase i)))ᗮ ⊓ vector_span ℝ (set.range s.points) := by rw [altitude_def, direction_inf_of_mem (self_mem_mk' (s.points i) _) (mem_affine_span ℝ (set.mem_range_self _)), direction_mk', direction_affine_span, direction_affine_span] /-- The vector span of the opposite face lies in the direction orthogonal to an altitude. -/ lemma vector_span_le_altitude_direction_orthogonal {n : ℕ} (s : simplex ℝ P (n + 1)) (i : fin (n + 2)) : vector_span ℝ (s.points '' ↑(finset.univ.erase i)) ≤ (s.altitude i).directionᗮ := begin rw direction_altitude, exact le_trans (vector_span ℝ (s.points '' ↑(finset.univ.erase i))).le_orthogonal_orthogonal (submodule.orthogonal_le inf_le_left) end open finite_dimensional /-- An altitude is finite-dimensional. -/ instance finite_dimensional_direction_altitude {n : ℕ} (s : simplex ℝ P (n + 1)) (i : fin (n + 2)) : finite_dimensional ℝ ((s.altitude i).direction) := begin rw direction_altitude, apply_instance end /-- An altitude is one-dimensional (i.e., a line). -/ @[simp] lemma finrank_direction_altitude {n : ℕ} (s : simplex ℝ P (n + 1)) (i : fin (n + 2)) : finrank ℝ ((s.altitude i).direction) = 1 := begin rw direction_altitude, have h := submodule.finrank_add_inf_finrank_orthogonal (vector_span_mono ℝ (set.image_subset_range s.points ↑(univ.erase i))), have hc : card (univ.erase i) = n + 1, { rw card_erase_of_mem (mem_univ _), simp }, refine add_left_cancel (trans h _), rw [s.independent.finrank_vector_span (fintype.card_fin _), ← finset.coe_image, s.independent.finrank_vector_span_image_finset hc] end /-- A line through a vertex is the altitude through that vertex if and only if it is orthogonal to the opposite face. -/ lemma affine_span_pair_eq_altitude_iff {n : ℕ} (s : simplex ℝ P (n + 1)) (i : fin (n + 2)) (p : P) : line[ℝ, p, s.points i] = s.altitude i ↔ (p ≠ s.points i ∧ p ∈ affine_span ℝ (set.range s.points) ∧ p -ᵥ s.points i ∈ (affine_span ℝ (s.points '' ↑(finset.univ.erase i))).directionᗮ) := begin rw [eq_iff_direction_eq_of_mem (mem_affine_span ℝ (set.mem_insert_of_mem _ (set.mem_singleton _))) (s.mem_altitude _), ←vsub_right_mem_direction_iff_mem (mem_affine_span ℝ (set.mem_range_self i)) p, direction_affine_span, direction_affine_span, direction_affine_span], split, { intro h, split, { intro heq, rw [heq, set.pair_eq_singleton, vector_span_singleton] at h, have hd : finrank ℝ (s.altitude i).direction = 0, { rw [←h, finrank_bot] }, simpa using hd }, { rw [←submodule.mem_inf, _root_.inf_comm, ←direction_altitude, ←h], exact vsub_mem_vector_span ℝ (set.mem_insert _ _) (set.mem_insert_of_mem _ (set.mem_singleton _)) } }, { rintro ⟨hne, h⟩, rw [←submodule.mem_inf, _root_.inf_comm, ←direction_altitude] at h, rw [vector_span_eq_span_vsub_set_left_ne ℝ (set.mem_insert _ _), set.insert_diff_of_mem _ (set.mem_singleton _), set.diff_singleton_eq_self (λ h, hne (set.mem_singleton_iff.1 h)), set.image_singleton], refine eq_of_le_of_finrank_eq _ _, { rw submodule.span_le, simpa using h }, { rw [finrank_direction_altitude, finrank_span_set_eq_card], { simp }, { refine linear_independent_singleton _, simpa using hne } } } end end simplex namespace triangle open euclidean_geometry finset simplex affine_subspace finite_dimensional variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] include V /-- The orthocenter of a triangle is the intersection of its altitudes. It is defined here as the 2-dimensional case of the Monge point. -/ def orthocenter (t : triangle ℝ P) : P := t.monge_point /-- The orthocenter equals the Monge point. -/ lemma orthocenter_eq_monge_point (t : triangle ℝ P) : t.orthocenter = t.monge_point := rfl /-- The position of the orthocenter in relation to the circumcenter and centroid. -/ lemma orthocenter_eq_smul_vsub_vadd_circumcenter (t : triangle ℝ P) : t.orthocenter = (3 : ℝ) • ((univ : finset (fin 3)).centroid ℝ t.points -ᵥ t.circumcenter : V) +ᵥ t.circumcenter := begin rw [orthocenter_eq_monge_point, monge_point_eq_smul_vsub_vadd_circumcenter], norm_num end /-- The orthocenter lies in the affine span. -/ lemma orthocenter_mem_affine_span (t : triangle ℝ P) : t.orthocenter ∈ affine_span ℝ (set.range t.points) := t.monge_point_mem_affine_span /-- Two triangles with the same points have the same orthocenter. -/ lemma orthocenter_eq_of_range_eq {t₁ t₂ : triangle ℝ P} (h : set.range t₁.points = set.range t₂.points) : t₁.orthocenter = t₂.orthocenter := monge_point_eq_of_range_eq h /-- In the case of a triangle, altitudes are the same thing as Monge planes. -/ lemma altitude_eq_monge_plane (t : triangle ℝ P) {i₁ i₂ i₃ : fin 3} (h₁₂ : i₁ ≠ i₂) (h₁₃ : i₁ ≠ i₃) (h₂₃ : i₂ ≠ i₃) : t.altitude i₁ = t.monge_plane i₂ i₃ := begin have hs : ({i₂, i₃}ᶜ : finset (fin 3)) = {i₁}, by dec_trivial!, have he : univ.erase i₁ = {i₂, i₃}, by dec_trivial!, rw [monge_plane_def, altitude_def, direction_affine_span, hs, he, centroid_singleton, coe_insert, coe_singleton, vector_span_image_eq_span_vsub_set_left_ne ℝ _ (set.mem_insert i₂ _)], simp [h₂₃, submodule.span_insert_eq_span] end /-- The orthocenter lies in the altitudes. -/ lemma orthocenter_mem_altitude (t : triangle ℝ P) {i₁ : fin 3} : t.orthocenter ∈ t.altitude i₁ := begin obtain ⟨i₂, i₃, h₁₂, h₂₃, h₁₃⟩ : ∃ i₂ i₃, i₁ ≠ i₂ ∧ i₂ ≠ i₃ ∧ i₁ ≠ i₃, by dec_trivial!, rw [orthocenter_eq_monge_point, t.altitude_eq_monge_plane h₁₂ h₁₃ h₂₃], exact t.monge_point_mem_monge_plane end /-- The orthocenter is the only point lying in any two of the altitudes. -/ lemma eq_orthocenter_of_forall_mem_altitude {t : triangle ℝ P} {i₁ i₂ : fin 3} {p : P} (h₁₂ : i₁ ≠ i₂) (h₁ : p ∈ t.altitude i₁) (h₂ : p ∈ t.altitude i₂) : p = t.orthocenter := begin obtain ⟨i₃, h₂₃, h₁₃⟩ : ∃ i₃, i₂ ≠ i₃ ∧ i₁ ≠ i₃, { clear h₁ h₂, dec_trivial! }, rw t.altitude_eq_monge_plane h₁₃ h₁₂ h₂₃.symm at h₁, rw t.altitude_eq_monge_plane h₂₃ h₁₂.symm h₁₃.symm at h₂, rw orthocenter_eq_monge_point, have ha : ∀ i, i₃ ≠ i → p ∈ t.monge_plane i₃ i, { intros i hi, have hi₁₂ : i₁ = i ∨ i₂ = i, { clear h₁ h₂, dec_trivial! }, cases hi₁₂, { exact hi₁₂ ▸ h₂ }, { exact hi₁₂ ▸ h₁ } }, exact eq_monge_point_of_forall_mem_monge_plane ha end /-- The distance from the orthocenter to the reflection of the circumcenter in a side equals the circumradius. -/ lemma dist_orthocenter_reflection_circumcenter (t : triangle ℝ P) {i₁ i₂ : fin 3} (h : i₁ ≠ i₂) : dist t.orthocenter (reflection (affine_span ℝ (t.points '' {i₁, i₂})) t.circumcenter) = t.circumradius := begin rw [←mul_self_inj_of_nonneg dist_nonneg t.circumradius_nonneg, t.reflection_circumcenter_eq_affine_combination_of_points_with_circumcenter h, t.orthocenter_eq_monge_point, monge_point_eq_affine_combination_of_points_with_circumcenter, dist_affine_combination t.points_with_circumcenter (sum_monge_point_weights_with_circumcenter _) (sum_reflection_circumcenter_weights_with_circumcenter h)], simp_rw [sum_points_with_circumcenter, pi.sub_apply, monge_point_weights_with_circumcenter, reflection_circumcenter_weights_with_circumcenter], have hu : ({i₁, i₂} : finset (fin 3)) ⊆ univ := subset_univ _, obtain ⟨i₃, hi₃, hi₃₁, hi₃₂⟩ : ∃ i₃, univ \ ({i₁, i₂} : finset (fin 3)) = {i₃} ∧ i₃ ≠ i₁ ∧ i₃ ≠ i₂, by dec_trivial!, simp_rw [←sum_sdiff hu, hi₃], simp [hi₃₁, hi₃₂], norm_num end /-- The distance from the orthocenter to the reflection of the circumcenter in a side equals the circumradius, variant using a `finset`. -/ lemma dist_orthocenter_reflection_circumcenter_finset (t : triangle ℝ P) {i₁ i₂ : fin 3} (h : i₁ ≠ i₂) : dist t.orthocenter (reflection (affine_span ℝ (t.points '' ↑({i₁, i₂} : finset (fin 3)))) t.circumcenter) = t.circumradius := by { convert dist_orthocenter_reflection_circumcenter _ h, simp } /-- The affine span of the orthocenter and a vertex is contained in the altitude. -/ lemma affine_span_orthocenter_point_le_altitude (t : triangle ℝ P) (i : fin 3) : line[ℝ, t.orthocenter, t.points i] ≤ t.altitude i := begin refine span_points_subset_coe_of_subset_coe _, rw [set.insert_subset, set.singleton_subset_iff], exact ⟨t.orthocenter_mem_altitude, t.mem_altitude i⟩ end /-- Suppose we are given a triangle `t₁`, and replace one of its vertices by its orthocenter, yielding triangle `t₂` (with vertices not necessarily listed in the same order). Then an altitude of `t₂` from a vertex that was not replaced is the corresponding side of `t₁`. -/ lemma altitude_replace_orthocenter_eq_affine_span {t₁ t₂ : triangle ℝ P} {i₁ i₂ i₃ j₁ j₂ j₃ : fin 3} (hi₁₂ : i₁ ≠ i₂) (hi₁₃ : i₁ ≠ i₃) (hi₂₃ : i₂ ≠ i₃) (hj₁₂ : j₁ ≠ j₂) (hj₁₃ : j₁ ≠ j₃) (hj₂₃ : j₂ ≠ j₃) (h₁ : t₂.points j₁ = t₁.orthocenter) (h₂ : t₂.points j₂ = t₁.points i₂) (h₃ : t₂.points j₃ = t₁.points i₃) : t₂.altitude j₂ = line[ℝ, t₁.points i₁, t₁.points i₂] := begin symmetry, rw [←h₂, t₂.affine_span_pair_eq_altitude_iff], rw [h₂], use t₁.independent.injective.ne hi₁₂, have he : affine_span ℝ (set.range t₂.points) = affine_span ℝ (set.range t₁.points), { refine ext_of_direction_eq _ ⟨t₁.points i₃, mem_affine_span ℝ ⟨j₃, h₃⟩, mem_affine_span ℝ (set.mem_range_self _)⟩, refine eq_of_le_of_finrank_eq (direction_le (span_points_subset_coe_of_subset_coe _)) _, { have hu : (finset.univ : finset (fin 3)) = {j₁, j₂, j₃}, { clear h₁ h₂ h₃, dec_trivial! }, rw [←set.image_univ, ←finset.coe_univ, hu, finset.coe_insert, finset.coe_insert, finset.coe_singleton, set.image_insert_eq, set.image_insert_eq, set.image_singleton, h₁, h₂, h₃, set.insert_subset, set.insert_subset, set.singleton_subset_iff], exact ⟨t₁.orthocenter_mem_affine_span, mem_affine_span ℝ (set.mem_range_self _), mem_affine_span ℝ (set.mem_range_self _)⟩ }, { rw [direction_affine_span, direction_affine_span, t₁.independent.finrank_vector_span (fintype.card_fin _), t₂.independent.finrank_vector_span (fintype.card_fin _)] } }, rw he, use mem_affine_span ℝ (set.mem_range_self _), have hu : finset.univ.erase j₂ = {j₁, j₃}, { clear h₁ h₂ h₃, dec_trivial! }, rw [hu, finset.coe_insert, finset.coe_singleton, set.image_insert_eq, set.image_singleton, h₁, h₃], have hle : (t₁.altitude i₃).directionᗮ ≤ line[ℝ, t₁.orthocenter, t₁.points i₃].directionᗮ := submodule.orthogonal_le (direction_le (affine_span_orthocenter_point_le_altitude _ _)), refine hle ((t₁.vector_span_le_altitude_direction_orthogonal i₃) _), have hui : finset.univ.erase i₃ = {i₁, i₂}, { clear hle h₂ h₃, dec_trivial! }, rw [hui, finset.coe_insert, finset.coe_singleton, set.image_insert_eq, set.image_singleton], refine vsub_mem_vector_span ℝ (set.mem_insert _ _) (set.mem_insert_of_mem _ (set.mem_singleton _)) end /-- Suppose we are given a triangle `t₁`, and replace one of its vertices by its orthocenter, yielding triangle `t₂` (with vertices not necessarily listed in the same order). Then the orthocenter of `t₂` is the vertex of `t₁` that was replaced. -/ lemma orthocenter_replace_orthocenter_eq_point {t₁ t₂ : triangle ℝ P} {i₁ i₂ i₃ j₁ j₂ j₃ : fin 3} (hi₁₂ : i₁ ≠ i₂) (hi₁₃ : i₁ ≠ i₃) (hi₂₃ : i₂ ≠ i₃) (hj₁₂ : j₁ ≠ j₂) (hj₁₃ : j₁ ≠ j₃) (hj₂₃ : j₂ ≠ j₃) (h₁ : t₂.points j₁ = t₁.orthocenter) (h₂ : t₂.points j₂ = t₁.points i₂) (h₃ : t₂.points j₃ = t₁.points i₃) : t₂.orthocenter = t₁.points i₁ := begin refine (triangle.eq_orthocenter_of_forall_mem_altitude hj₂₃ _ _).symm, { rw altitude_replace_orthocenter_eq_affine_span hi₁₂ hi₁₃ hi₂₃ hj₁₂ hj₁₃ hj₂₃ h₁ h₂ h₃, exact mem_affine_span ℝ (set.mem_insert _ _) }, { rw altitude_replace_orthocenter_eq_affine_span hi₁₃ hi₁₂ hi₂₃.symm hj₁₃ hj₁₂ hj₂₃.symm h₁ h₃ h₂, exact mem_affine_span ℝ (set.mem_insert _ _) } end end triangle end affine namespace euclidean_geometry open affine affine_subspace finite_dimensional variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] include V /-- Four points form an orthocentric system if they consist of the vertices of a triangle and its orthocenter. -/ def orthocentric_system (s : set P) : Prop := ∃ t : triangle ℝ P, t.orthocenter ∉ set.range t.points ∧ s = insert t.orthocenter (set.range t.points) /-- This is an auxiliary lemma giving information about the relation of two triangles in an orthocentric system; it abstracts some reasoning, with no geometric content, that is common to some other lemmas. Suppose the orthocentric system is generated by triangle `t`, and we are given three points `p` in the orthocentric system. Then either we can find indices `i₁`, `i₂` and `i₃` for `p` such that `p i₁` is the orthocenter of `t` and `p i₂` and `p i₃` are points `j₂` and `j₃` of `t`, or `p` has the same points as `t`. -/ lemma exists_of_range_subset_orthocentric_system {t : triangle ℝ P} (ho : t.orthocenter ∉ set.range t.points) {p : fin 3 → P} (hps : set.range p ⊆ insert t.orthocenter (set.range t.points)) (hpi : function.injective p) : (∃ (i₁ i₂ i₃ j₂ j₃ : fin 3), i₁ ≠ i₂ ∧ i₁ ≠ i₃ ∧ i₂ ≠ i₃ ∧ (∀ i : fin 3, i = i₁ ∨ i = i₂ ∨ i = i₃) ∧ p i₁ = t.orthocenter ∧ j₂ ≠ j₃ ∧ t.points j₂ = p i₂ ∧ t.points j₃ = p i₃) ∨ set.range p = set.range t.points := begin by_cases h : t.orthocenter ∈ set.range p, { left, rcases h with ⟨i₁, h₁⟩, obtain ⟨i₂, i₃, h₁₂, h₁₃, h₂₃, h₁₂₃⟩ : ∃ (i₂ i₃ : fin 3), i₁ ≠ i₂ ∧ i₁ ≠ i₃ ∧ i₂ ≠ i₃ ∧ ∀ i : fin 3, i = i₁ ∨ i = i₂ ∨ i = i₃, { clear h₁, dec_trivial! }, have h : ∀ i, i₁ ≠ i → ∃ (j : fin 3), t.points j = p i, { intros i hi, replace hps := set.mem_of_mem_insert_of_ne (set.mem_of_mem_of_subset (set.mem_range_self i) hps) (h₁ ▸ hpi.ne hi.symm), exact hps }, rcases h i₂ h₁₂ with ⟨j₂, h₂⟩, rcases h i₃ h₁₃ with ⟨j₃, h₃⟩, have hj₂₃ : j₂ ≠ j₃, { intro he, rw [he, h₃] at h₂, exact h₂₃.symm (hpi h₂) }, exact ⟨i₁, i₂, i₃, j₂, j₃, h₁₂, h₁₃, h₂₃, h₁₂₃, h₁, hj₂₃, h₂, h₃⟩ }, { right, have hs := set.subset_diff_singleton hps h, rw set.insert_diff_self_of_not_mem ho at hs, refine set.eq_of_subset_of_card_le hs _, rw [set.card_range_of_injective hpi, set.card_range_of_injective t.independent.injective] } end /-- For any three points in an orthocentric system generated by triangle `t`, there is a point in the subspace spanned by the triangle from which the distance of all those three points equals the circumradius. -/ lemma exists_dist_eq_circumradius_of_subset_insert_orthocenter {t : triangle ℝ P} (ho : t.orthocenter ∉ set.range t.points) {p : fin 3 → P} (hps : set.range p ⊆ insert t.orthocenter (set.range t.points)) (hpi : function.injective p) : ∃ c ∈ affine_span ℝ (set.range t.points), ∀ p₁ ∈ set.range p, dist p₁ c = t.circumradius := begin rcases exists_of_range_subset_orthocentric_system ho hps hpi with ⟨i₁, i₂, i₃, j₂, j₃, h₁₂, h₁₃, h₂₃, h₁₂₃, h₁, hj₂₃, h₂, h₃⟩ | hs, { use [reflection (affine_span ℝ (t.points '' {j₂, j₃})) t.circumcenter, reflection_mem_of_le_of_mem (affine_span_mono ℝ (set.image_subset_range _ _)) t.circumcenter_mem_affine_span], intros p₁ hp₁, rcases hp₁ with ⟨i, rfl⟩, replace h₁₂₃ := h₁₂₃ i, repeat { cases h₁₂₃ }, { rw h₁, exact triangle.dist_orthocenter_reflection_circumcenter t hj₂₃ }, { rw [←h₂, dist_reflection_eq_of_mem _ (mem_affine_span ℝ (set.mem_image_of_mem _ (set.mem_insert _ _)))], exact t.dist_circumcenter_eq_circumradius _ }, { rw [←h₃, dist_reflection_eq_of_mem _ (mem_affine_span ℝ (set.mem_image_of_mem _ (set.mem_insert_of_mem _ (set.mem_singleton _))))], exact t.dist_circumcenter_eq_circumradius _ } }, { use [t.circumcenter, t.circumcenter_mem_affine_span], intros p₁ hp₁, rw hs at hp₁, rcases hp₁ with ⟨i, rfl⟩, exact t.dist_circumcenter_eq_circumradius _ } end /-- Any three points in an orthocentric system are affinely independent. -/ lemma orthocentric_system.affine_independent {s : set P} (ho : orthocentric_system s) {p : fin 3 → P} (hps : set.range p ⊆ s) (hpi : function.injective p) : affine_independent ℝ p := begin rcases ho with ⟨t, hto, hst⟩, rw hst at hps, rcases exists_dist_eq_circumradius_of_subset_insert_orthocenter hto hps hpi with ⟨c, hcs, hc⟩, exact cospherical.affine_independent ⟨c, t.circumradius, hc⟩ set.subset.rfl hpi end /-- Any three points in an orthocentric system span the same subspace as the whole orthocentric system. -/ lemma affine_span_of_orthocentric_system {s : set P} (ho : orthocentric_system s) {p : fin 3 → P} (hps : set.range p ⊆ s) (hpi : function.injective p) : affine_span ℝ (set.range p) = affine_span ℝ s := begin have ha := ho.affine_independent hps hpi, rcases ho with ⟨t, hto, hts⟩, have hs : affine_span ℝ s = affine_span ℝ (set.range t.points), { rw [hts, affine_span_insert_eq_affine_span ℝ t.orthocenter_mem_affine_span] }, refine ext_of_direction_eq _ ⟨p 0, mem_affine_span ℝ (set.mem_range_self _), mem_affine_span ℝ (hps (set.mem_range_self _))⟩, have hfd : finite_dimensional ℝ (affine_span ℝ s).direction, { rw hs, apply_instance }, haveI := hfd, refine eq_of_le_of_finrank_eq (direction_le (affine_span_mono ℝ hps)) _, rw [hs, direction_affine_span, direction_affine_span, ha.finrank_vector_span (fintype.card_fin _), t.independent.finrank_vector_span (fintype.card_fin _)] end /-- All triangles in an orthocentric system have the same circumradius. -/ lemma orthocentric_system.exists_circumradius_eq {s : set P} (ho : orthocentric_system s) : ∃ r : ℝ, ∀ t : triangle ℝ P, set.range t.points ⊆ s → t.circumradius = r := begin rcases ho with ⟨t, hto, hts⟩, use t.circumradius, intros t₂ ht₂, have ht₂s := ht₂, rw hts at ht₂, rcases exists_dist_eq_circumradius_of_subset_insert_orthocenter hto ht₂ t₂.independent.injective with ⟨c, hc, h⟩, rw set.forall_range_iff at h, have hs : set.range t.points ⊆ s, { rw hts, exact set.subset_insert _ _ }, rw [affine_span_of_orthocentric_system ⟨t, hto, hts⟩ hs t.independent.injective, ←affine_span_of_orthocentric_system ⟨t, hto, hts⟩ ht₂s t₂.independent.injective] at hc, exact (t₂.eq_circumradius_of_dist_eq hc h).symm end /-- Given any triangle in an orthocentric system, the fourth point is its orthocenter. -/ lemma orthocentric_system.eq_insert_orthocenter {s : set P} (ho : orthocentric_system s) {t : triangle ℝ P} (ht : set.range t.points ⊆ s) : s = insert t.orthocenter (set.range t.points) := begin rcases ho with ⟨t₀, ht₀o, ht₀s⟩, rw ht₀s at ht, rcases exists_of_range_subset_orthocentric_system ht₀o ht t.independent.injective with ⟨i₁, i₂, i₃, j₂, j₃, h₁₂, h₁₃, h₂₃, h₁₂₃, h₁, hj₂₃, h₂, h₃⟩ | hs, { obtain ⟨j₁, hj₁₂, hj₁₃, hj₁₂₃⟩ : ∃ j₁ : fin 3, j₁ ≠ j₂ ∧ j₁ ≠ j₃ ∧ ∀ j : fin 3, j = j₁ ∨ j = j₂ ∨ j = j₃, { clear h₂ h₃, dec_trivial! }, suffices h : t₀.points j₁ = t.orthocenter, { have hui : (set.univ : set (fin 3)) = {i₁, i₂, i₃}, { ext x, simpa using h₁₂₃ x }, have huj : (set.univ : set (fin 3)) = {j₁, j₂, j₃}, { ext x, simpa using hj₁₂₃ x }, rw [←h, ht₀s, ←set.image_univ, huj, ←set.image_univ, hui], simp_rw [set.image_insert_eq, set.image_singleton, h₁, ←h₂, ←h₃], rw set.insert_comm }, exact (triangle.orthocenter_replace_orthocenter_eq_point hj₁₂ hj₁₃ hj₂₃ h₁₂ h₁₃ h₂₃ h₁ h₂.symm h₃.symm).symm }, { rw hs, convert ht₀s using 2, exact triangle.orthocenter_eq_of_range_eq hs } end end euclidean_geometry
b438bbf187d01025d512cd26bf29e1c06f7edc63
9dc8cecdf3c4634764a18254e94d43da07142918
/src/geometry/euclidean/circumcenter.lean
69ada84e2f8bfa60914850b0611b983814bba714
[ "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
40,655
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers -/ import geometry.euclidean.basic import linear_algebra.affine_space.finite_dimensional import tactic.derive_fintype /-! # Circumcenter and circumradius This file proves some lemmas on points equidistant from a set of points, and defines the circumradius and circumcenter of a simplex. There are also some definitions for use in calculations where it is convenient to work with affine combinations of vertices together with the circumcenter. ## Main definitions * `circumcenter` and `circumradius` are the circumcenter and circumradius of a simplex. ## References * https://en.wikipedia.org/wiki/Circumscribed_circle -/ noncomputable theory open_locale big_operators open_locale classical open_locale real open_locale real_inner_product_space namespace euclidean_geometry open inner_product_geometry variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] include V open affine_subspace /-- `p` is equidistant from two points in `s` if and only if its `orthogonal_projection` is. -/ lemma dist_eq_iff_dist_orthogonal_projection_eq {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p1 p2 : P} (p3 : P) (hp1 : p1 ∈ s) (hp2 : p2 ∈ s) : dist p1 p3 = dist p2 p3 ↔ dist p1 (orthogonal_projection s p3) = dist p2 (orthogonal_projection s p3) := begin rw [←mul_self_inj_of_nonneg dist_nonneg dist_nonneg, ←mul_self_inj_of_nonneg dist_nonneg dist_nonneg, dist_sq_eq_dist_orthogonal_projection_sq_add_dist_orthogonal_projection_sq p3 hp1, dist_sq_eq_dist_orthogonal_projection_sq_add_dist_orthogonal_projection_sq p3 hp2], simp end /-- `p` is equidistant from a set of points in `s` if and only if its `orthogonal_projection` is. -/ lemma dist_set_eq_iff_dist_orthogonal_projection_eq {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {ps : set P} (hps : ps ⊆ s) (p : P) : set.pairwise ps (λ p1 p2, dist p1 p = dist p2 p) ↔ (set.pairwise ps (λ p1 p2, dist p1 (orthogonal_projection s p) = dist p2 (orthogonal_projection s p))) := ⟨λ h p1 hp1 p2 hp2 hne, (dist_eq_iff_dist_orthogonal_projection_eq p (hps hp1) (hps hp2)).1 (h hp1 hp2 hne), λ h p1 hp1 p2 hp2 hne, (dist_eq_iff_dist_orthogonal_projection_eq p (hps hp1) (hps hp2)).2 (h hp1 hp2 hne)⟩ /-- There exists `r` such that `p` has distance `r` from all the points of a set of points in `s` if and only if there exists (possibly different) `r` such that its `orthogonal_projection` has that distance from all the points in that set. -/ lemma exists_dist_eq_iff_exists_dist_orthogonal_projection_eq {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {ps : set P} (hps : ps ⊆ s) (p : P) : (∃ r, ∀ p1 ∈ ps, dist p1 p = r) ↔ ∃ r, ∀ p1 ∈ ps, dist p1 ↑(orthogonal_projection s p) = r := begin have h := dist_set_eq_iff_dist_orthogonal_projection_eq hps p, simp_rw set.pairwise_eq_iff_exists_eq at h, exact h end /-- The induction step for the existence and uniqueness of the circumcenter. Given a nonempty set of points in a nonempty affine subspace whose direction is complete, such that there is a unique (circumcenter, circumradius) pair for those points in that subspace, and a point `p` not in that subspace, there is a unique (circumcenter, circumradius) pair for the set with `p` added, in the span of the subspace with `p` added. -/ lemma exists_unique_dist_eq_of_insert {s : affine_subspace ℝ P} [complete_space s.direction] {ps : set P} (hnps : ps.nonempty) {p : P} (hps : ps ⊆ s) (hp : p ∉ s) (hu : ∃! cccr : (P × ℝ), cccr.fst ∈ s ∧ ∀ p1 ∈ ps, dist p1 cccr.fst = cccr.snd) : ∃! cccr₂ : (P × ℝ), cccr₂.fst ∈ affine_span ℝ (insert p (s : set P)) ∧ ∀ p1 ∈ insert p ps, dist p1 cccr₂.fst = cccr₂.snd := begin haveI : nonempty s := set.nonempty.to_subtype (hnps.mono hps), rcases hu with ⟨⟨cc, cr⟩, ⟨hcc, hcr⟩, hcccru⟩, simp only [prod.fst, prod.snd] at hcc hcr hcccru, let x := dist cc (orthogonal_projection s p), let y := dist p (orthogonal_projection s p), have hy0 : y ≠ 0 := dist_orthogonal_projection_ne_zero_of_not_mem hp, let ycc₂ := (x * x + y * y - cr * cr) / (2 * y), let cc₂ := (ycc₂ / y) • (p -ᵥ orthogonal_projection s p : V) +ᵥ cc, let cr₂ := real.sqrt (cr * cr + ycc₂ * ycc₂), use (cc₂, cr₂), simp only [prod.fst, prod.snd], have hpo : p = (1 : ℝ) • (p -ᵥ orthogonal_projection s p : V) +ᵥ orthogonal_projection s p, { simp }, split, { split, { refine vadd_mem_of_mem_direction _ (mem_affine_span ℝ (set.mem_insert_of_mem _ hcc)), rw direction_affine_span, exact submodule.smul_mem _ _ (vsub_mem_vector_span ℝ (set.mem_insert _ _) (set.mem_insert_of_mem _ (orthogonal_projection_mem _))) }, { intros p1 hp1, rw [←mul_self_inj_of_nonneg dist_nonneg (real.sqrt_nonneg _), real.mul_self_sqrt (add_nonneg (mul_self_nonneg _) (mul_self_nonneg _))], cases hp1, { rw hp1, rw [hpo, dist_sq_smul_orthogonal_vadd_smul_orthogonal_vadd (orthogonal_projection_mem p) hcc _ _ (vsub_orthogonal_projection_mem_direction_orthogonal s p), ←dist_eq_norm_vsub V p, dist_comm _ cc], field_simp [hy0], ring }, { rw [dist_sq_eq_dist_orthogonal_projection_sq_add_dist_orthogonal_projection_sq _ (hps hp1), orthogonal_projection_vadd_smul_vsub_orthogonal_projection _ _ hcc, subtype.coe_mk, hcr _ hp1, dist_eq_norm_vsub V cc₂ cc, vadd_vsub, norm_smul, ←dist_eq_norm_vsub V, real.norm_eq_abs, abs_div, abs_of_nonneg dist_nonneg, div_mul_cancel _ hy0, abs_mul_abs_self] } } }, { rintros ⟨cc₃, cr₃⟩ ⟨hcc₃, hcr₃⟩, simp only [prod.fst, prod.snd] at hcc₃ hcr₃, obtain ⟨t₃, cc₃', hcc₃', hcc₃''⟩ : ∃ (r : ℝ) (p0 : P) (hp0 : p0 ∈ s), cc₃ = r • (p -ᵥ ↑((orthogonal_projection s) p)) +ᵥ p0, { rwa mem_affine_span_insert_iff (orthogonal_projection_mem p) at hcc₃ }, have hcr₃' : ∃ r, ∀ p1 ∈ ps, dist p1 cc₃ = r := ⟨cr₃, λ p1 hp1, hcr₃ p1 (set.mem_insert_of_mem _ hp1)⟩, rw [exists_dist_eq_iff_exists_dist_orthogonal_projection_eq hps cc₃, hcc₃'', orthogonal_projection_vadd_smul_vsub_orthogonal_projection _ _ hcc₃'] at hcr₃', cases hcr₃' with cr₃' hcr₃', have hu := hcccru (cc₃', cr₃'), simp only [prod.fst, prod.snd] at hu, replace hu := hu ⟨hcc₃', hcr₃'⟩, rw prod.ext_iff at hu, simp only [prod.fst, prod.snd] at hu, cases hu with hucc hucr, substs hucc hucr, have hcr₃val : cr₃ = real.sqrt (cr₃' * cr₃' + (t₃ * y) * (t₃ * y)), { cases hnps with p0 hp0, have h' : ↑(⟨cc₃', hcc₃'⟩ : s) = cc₃' := rfl, rw [←hcr₃ p0 (set.mem_insert_of_mem _ hp0), hcc₃'', ←mul_self_inj_of_nonneg dist_nonneg (real.sqrt_nonneg _), real.mul_self_sqrt (add_nonneg (mul_self_nonneg _) (mul_self_nonneg _)), dist_sq_eq_dist_orthogonal_projection_sq_add_dist_orthogonal_projection_sq _ (hps hp0), orthogonal_projection_vadd_smul_vsub_orthogonal_projection _ _ hcc₃', h', hcr p0 hp0, dist_eq_norm_vsub V _ cc₃', vadd_vsub, norm_smul, ←dist_eq_norm_vsub V p, real.norm_eq_abs, ←mul_assoc, mul_comm _ (|t₃|), ←mul_assoc, abs_mul_abs_self], ring }, replace hcr₃ := hcr₃ p (set.mem_insert _ _), rw [hpo, hcc₃'', hcr₃val, ←mul_self_inj_of_nonneg dist_nonneg (real.sqrt_nonneg _), dist_sq_smul_orthogonal_vadd_smul_orthogonal_vadd (orthogonal_projection_mem p) hcc₃' _ _ (vsub_orthogonal_projection_mem_direction_orthogonal s p), dist_comm, ←dist_eq_norm_vsub V p, real.mul_self_sqrt (add_nonneg (mul_self_nonneg _) (mul_self_nonneg _))] at hcr₃, change x * x + _ * (y * y) = _ at hcr₃, rw [(show x * x + (1 - t₃) * (1 - t₃) * (y * y) = x * x + y * y - 2 * y * (t₃ * y) + t₃ * y * (t₃ * y), by ring), add_left_inj] at hcr₃, have ht₃ : t₃ = ycc₂ / y, { field_simp [←hcr₃, hy0], ring }, subst ht₃, change cc₃ = cc₂ at hcc₃'', congr', rw hcr₃val, congr' 2, field_simp [hy0], ring } end /-- Given a finite nonempty affinely independent family of points, there is a unique (circumcenter, circumradius) pair for those points in the affine subspace they span. -/ lemma _root_.affine_independent.exists_unique_dist_eq {ι : Type*} [hne : nonempty ι] [fintype ι] {p : ι → P} (ha : affine_independent ℝ p) : ∃! cccr : (P × ℝ), cccr.fst ∈ affine_span ℝ (set.range p) ∧ ∀ i, dist (p i) cccr.fst = cccr.snd := begin unfreezingI { induction hn : fintype.card ι with m hm generalizing ι }, { exfalso, have h := fintype.card_pos_iff.2 hne, rw hn at h, exact lt_irrefl 0 h }, { cases m, { rw fintype.card_eq_one_iff at hn, cases hn with i hi, haveI : unique ι := ⟨⟨i⟩, hi⟩, use (p i, 0), simp only [prod.fst, prod.snd, set.range_unique, affine_subspace.mem_affine_span_singleton], split, { simp_rw [hi default], use rfl, intro i1, rw hi i1, exact dist_self _ }, { rintros ⟨cc, cr⟩, simp only [prod.fst, prod.snd], rintros ⟨rfl, hdist⟩, rw hi default, congr', rw ←hdist default, exact dist_self _ } }, { have i := hne.some, let ι2 := {x // x ≠ i}, have hc : fintype.card ι2 = m + 1, { rw fintype.card_of_subtype (finset.univ.filter (λ x, x ≠ i)), { rw finset.filter_not, simp_rw eq_comm, rw [finset.filter_eq, if_pos (finset.mem_univ _), finset.card_sdiff (finset.subset_univ _), finset.card_singleton, finset.card_univ, hn], simp }, { simp } }, haveI : nonempty ι2 := fintype.card_pos_iff.1 (hc.symm ▸ nat.zero_lt_succ _), have ha2 : affine_independent ℝ (λ i2 : ι2, p i2) := ha.subtype _, replace hm := hm ha2 hc, have hr : set.range p = insert (p i) (set.range (λ i2 : ι2, p i2)), { change _ = insert _ (set.range (λ i2 : {x | x ≠ i}, p i2)), rw [←set.image_eq_range, ←set.image_univ, ←set.image_insert_eq], congr' with j, simp [classical.em] }, change ∃! (cccr : P × ℝ), (_ ∧ ∀ i2, (λ q, dist q cccr.fst = cccr.snd) (p i2)), conv { congr, funext, conv { congr, skip, rw ←set.forall_range_iff } }, dsimp only, rw hr, change ∃! (cccr : P × ℝ), (_ ∧ ∀ (i2 : ι2), (λ q, dist q cccr.fst = cccr.snd) (p i2)) at hm, conv at hm { congr, funext, conv { congr, skip, rw ←set.forall_range_iff } }, rw ←affine_span_insert_affine_span, refine exists_unique_dist_eq_of_insert (set.range_nonempty _) (subset_span_points ℝ _) _ hm, convert ha.not_mem_affine_span_diff i set.univ, change set.range (λ i2 : {x | x ≠ i}, p i2) = _, rw ←set.image_eq_range, congr' with j, simp, refl } } end end euclidean_geometry namespace affine namespace simplex open finset affine_subspace euclidean_geometry variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] include V /-- The pair (circumcenter, circumradius) of a simplex. -/ def circumcenter_circumradius {n : ℕ} (s : simplex ℝ P n) : (P × ℝ) := s.independent.exists_unique_dist_eq.some /-- The property satisfied by the (circumcenter, circumradius) pair. -/ lemma circumcenter_circumradius_unique_dist_eq {n : ℕ} (s : simplex ℝ P n) : (s.circumcenter_circumradius.fst ∈ affine_span ℝ (set.range s.points) ∧ ∀ i, dist (s.points i) s.circumcenter_circumradius.fst = s.circumcenter_circumradius.snd) ∧ (∀ cccr : (P × ℝ), (cccr.fst ∈ affine_span ℝ (set.range s.points) ∧ ∀ i, dist (s.points i) cccr.fst = cccr.snd) → cccr = s.circumcenter_circumradius) := s.independent.exists_unique_dist_eq.some_spec /-- The circumcenter of a simplex. -/ def circumcenter {n : ℕ} (s : simplex ℝ P n) : P := s.circumcenter_circumradius.fst /-- The circumradius of a simplex. -/ def circumradius {n : ℕ} (s : simplex ℝ P n) : ℝ := s.circumcenter_circumradius.snd /-- The circumcenter lies in the affine span. -/ lemma circumcenter_mem_affine_span {n : ℕ} (s : simplex ℝ P n) : s.circumcenter ∈ affine_span ℝ (set.range s.points) := s.circumcenter_circumradius_unique_dist_eq.1.1 /-- All points have distance from the circumcenter equal to the circumradius. -/ @[simp] lemma dist_circumcenter_eq_circumradius {n : ℕ} (s : simplex ℝ P n) : ∀ i, dist (s.points i) s.circumcenter = s.circumradius := s.circumcenter_circumradius_unique_dist_eq.1.2 /-- All points have distance to the circumcenter equal to the circumradius. -/ @[simp] lemma dist_circumcenter_eq_circumradius' {n : ℕ} (s : simplex ℝ P n) : ∀ i, dist s.circumcenter (s.points i) = s.circumradius := begin intro i, rw dist_comm, exact dist_circumcenter_eq_circumradius _ _ end /-- Given a point in the affine span from which all the points are equidistant, that point is the circumcenter. -/ lemma eq_circumcenter_of_dist_eq {n : ℕ} (s : simplex ℝ P n) {p : P} (hp : p ∈ affine_span ℝ (set.range s.points)) {r : ℝ} (hr : ∀ i, dist (s.points i) p = r) : p = s.circumcenter := begin have h := s.circumcenter_circumradius_unique_dist_eq.2 (p, r), simp only [hp, hr, forall_const, eq_self_iff_true, and_self, prod.ext_iff] at h, exact h.1 end /-- Given a point in the affine span from which all the points are equidistant, that distance is the circumradius. -/ lemma eq_circumradius_of_dist_eq {n : ℕ} (s : simplex ℝ P n) {p : P} (hp : p ∈ affine_span ℝ (set.range s.points)) {r : ℝ} (hr : ∀ i, dist (s.points i) p = r) : r = s.circumradius := begin have h := s.circumcenter_circumradius_unique_dist_eq.2 (p, r), simp only [hp, hr, forall_const, eq_self_iff_true, and_self, prod.ext_iff] at h, exact h.2 end /-- The circumradius is non-negative. -/ lemma circumradius_nonneg {n : ℕ} (s : simplex ℝ P n) : 0 ≤ s.circumradius := s.dist_circumcenter_eq_circumradius 0 ▸ dist_nonneg /-- The circumradius of a simplex with at least two points is positive. -/ lemma circumradius_pos {n : ℕ} (s : simplex ℝ P (n + 1)) : 0 < s.circumradius := begin refine lt_of_le_of_ne s.circumradius_nonneg _, intro h, have hr := s.dist_circumcenter_eq_circumradius, simp_rw [←h, dist_eq_zero] at hr, have h01 := s.independent.injective.ne (dec_trivial : (0 : fin (n + 2)) ≠ 1), simpa [hr] using h01 end /-- The circumcenter of a 0-simplex equals its unique point. -/ lemma circumcenter_eq_point (s : simplex ℝ P 0) (i : fin 1) : s.circumcenter = s.points i := begin have h := s.circumcenter_mem_affine_span, rw [set.range_unique, mem_affine_span_singleton] at h, rw h, congr end /-- The circumcenter of a 1-simplex equals its centroid. -/ lemma circumcenter_eq_centroid (s : simplex ℝ P 1) : s.circumcenter = finset.univ.centroid ℝ s.points := begin have hr : set.pairwise set.univ (λ i j : fin 2, dist (s.points i) (finset.univ.centroid ℝ s.points) = dist (s.points j) (finset.univ.centroid ℝ s.points)), { intros i hi j hj hij, rw [finset.centroid_pair_fin, dist_eq_norm_vsub V (s.points i), dist_eq_norm_vsub V (s.points j), vsub_vadd_eq_vsub_sub, vsub_vadd_eq_vsub_sub, ←one_smul ℝ (s.points i -ᵥ s.points 0), ←one_smul ℝ (s.points j -ᵥ s.points 0)], fin_cases i; fin_cases j; simp [-one_smul, ←sub_smul]; norm_num }, rw set.pairwise_eq_iff_exists_eq at hr, cases hr with r hr, exact (s.eq_circumcenter_of_dist_eq (centroid_mem_affine_span_of_card_eq_add_one ℝ _ (finset.card_fin 2)) (λ i, hr i (set.mem_univ _))).symm end local attribute [instance] affine_subspace.to_add_torsor /-- The orthogonal projection of a point `p` onto the hyperplane spanned by the simplex's points. -/ def orthogonal_projection_span {n : ℕ} (s : simplex ℝ P n) : P →ᵃ[ℝ] affine_span ℝ (set.range s.points) := orthogonal_projection (affine_span ℝ (set.range s.points)) /-- Adding a vector to a point in the given subspace, then taking the orthogonal projection, produces the original point if the vector is a multiple of the result of subtracting a point's orthogonal projection from that point. -/ lemma orthogonal_projection_vadd_smul_vsub_orthogonal_projection {n : ℕ} (s : simplex ℝ P n) {p1 : P} (p2 : P) (r : ℝ) (hp : p1 ∈ affine_span ℝ (set.range s.points)) : s.orthogonal_projection_span (r • (p2 -ᵥ s.orthogonal_projection_span p2 : V) +ᵥ p1) = ⟨p1, hp⟩ := orthogonal_projection_vadd_smul_vsub_orthogonal_projection _ _ _ lemma coe_orthogonal_projection_vadd_smul_vsub_orthogonal_projection {n : ℕ} {r₁ : ℝ} (s : simplex ℝ P n) {p p₁o : P} (hp₁o : p₁o ∈ affine_span ℝ (set.range s.points)) : ↑(s.orthogonal_projection_span (r₁ • (p -ᵥ ↑(s.orthogonal_projection_span p)) +ᵥ p₁o)) = p₁o := congr_arg coe (orthogonal_projection_vadd_smul_vsub_orthogonal_projection _ _ _ hp₁o) lemma dist_sq_eq_dist_orthogonal_projection_sq_add_dist_orthogonal_projection_sq {n : ℕ} (s : simplex ℝ P n) {p1 : P} (p2 : P) (hp1 : p1 ∈ affine_span ℝ (set.range s.points)) : dist p1 p2 * dist p1 p2 = dist p1 (s.orthogonal_projection_span p2) * dist p1 (s.orthogonal_projection_span p2) + dist p2 (s.orthogonal_projection_span p2) * dist p2 (s.orthogonal_projection_span p2) := begin rw [pseudo_metric_space.dist_comm p2 _, dist_eq_norm_vsub V p1 _, dist_eq_norm_vsub V p1 _, dist_eq_norm_vsub V _ p2, ← vsub_add_vsub_cancel p1 (s.orthogonal_projection_span p2) p2, norm_add_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero], exact submodule.inner_right_of_mem_orthogonal (vsub_orthogonal_projection_mem_direction p2 hp1) (orthogonal_projection_vsub_mem_direction_orthogonal _ p2), end lemma dist_circumcenter_sq_eq_sq_sub_circumradius {n : ℕ} {r : ℝ} (s : simplex ℝ P n) {p₁ : P} (h₁ : ∀ (i : fin (n + 1)), dist (s.points i) p₁ = r) (h₁' : ↑((s.orthogonal_projection_span) p₁) = s.circumcenter) (h : s.points 0 ∈ affine_span ℝ (set.range s.points)) : dist p₁ s.circumcenter * dist p₁ s.circumcenter = r * r - s.circumradius * s.circumradius := begin rw [dist_comm, ←h₁ 0, s.dist_sq_eq_dist_orthogonal_projection_sq_add_dist_orthogonal_projection_sq p₁ h], simp only [h₁', dist_comm p₁, add_sub_cancel', simplex.dist_circumcenter_eq_circumradius], end /-- If there exists a distance that a point has from all vertices of a simplex, the orthogonal projection of that point onto the subspace spanned by that simplex is its circumcenter. -/ lemma orthogonal_projection_eq_circumcenter_of_exists_dist_eq {n : ℕ} (s : simplex ℝ P n) {p : P} (hr : ∃ r, ∀ i, dist (s.points i) p = r) : ↑(s.orthogonal_projection_span p) = s.circumcenter := begin change ∃ r : ℝ, ∀ i, (λ x, dist x p = r) (s.points i) at hr, conv at hr { congr, funext, rw ←set.forall_range_iff }, rw exists_dist_eq_iff_exists_dist_orthogonal_projection_eq (subset_affine_span ℝ _) p at hr, cases hr with r hr, exact s.eq_circumcenter_of_dist_eq (orthogonal_projection_mem p) (λ i, hr _ (set.mem_range_self i)), end /-- If a point has the same distance from all vertices of a simplex, the orthogonal projection of that point onto the subspace spanned by that simplex is its circumcenter. -/ lemma orthogonal_projection_eq_circumcenter_of_dist_eq {n : ℕ} (s : simplex ℝ P n) {p : P} {r : ℝ} (hr : ∀ i, dist (s.points i) p = r) : ↑(s.orthogonal_projection_span p) = s.circumcenter := s.orthogonal_projection_eq_circumcenter_of_exists_dist_eq ⟨r, hr⟩ /-- The orthogonal projection of the circumcenter onto a face is the circumcenter of that face. -/ lemma orthogonal_projection_circumcenter {n : ℕ} (s : simplex ℝ P n) {fs : finset (fin (n + 1))} {m : ℕ} (h : fs.card = m + 1) : ↑((s.face h).orthogonal_projection_span s.circumcenter) = (s.face h).circumcenter := begin have hr : ∃ r, ∀ i, dist ((s.face h).points i) s.circumcenter = r, { use s.circumradius, simp [face_points] }, exact orthogonal_projection_eq_circumcenter_of_exists_dist_eq _ hr end /-- Two simplices with the same points have the same circumcenter. -/ lemma circumcenter_eq_of_range_eq {n : ℕ} {s₁ s₂ : simplex ℝ P n} (h : set.range s₁.points = set.range s₂.points) : s₁.circumcenter = s₂.circumcenter := begin have hs : s₁.circumcenter ∈ affine_span ℝ (set.range s₂.points) := h ▸ s₁.circumcenter_mem_affine_span, have hr : ∀ i, dist (s₂.points i) s₁.circumcenter = s₁.circumradius, { intro i, have hi : s₂.points i ∈ set.range s₂.points := set.mem_range_self _, rw [←h, set.mem_range] at hi, rcases hi with ⟨j, hj⟩, rw [←hj, s₁.dist_circumcenter_eq_circumradius j] }, exact s₂.eq_circumcenter_of_dist_eq hs hr end omit V /-- An index type for the vertices of a simplex plus its circumcenter. This is for use in calculations where it is convenient to work with affine combinations of vertices together with the circumcenter. (An equivalent form sometimes used in the literature is placing the circumcenter at the origin and working with vectors for the vertices.) -/ @[derive fintype] inductive points_with_circumcenter_index (n : ℕ) | point_index : fin (n + 1) → points_with_circumcenter_index | circumcenter_index : points_with_circumcenter_index open points_with_circumcenter_index instance points_with_circumcenter_index_inhabited (n : ℕ) : inhabited (points_with_circumcenter_index n) := ⟨circumcenter_index⟩ /-- `point_index` as an embedding. -/ def point_index_embedding (n : ℕ) : fin (n + 1) ↪ points_with_circumcenter_index n := ⟨λ i, point_index i, λ _ _ h, by injection h⟩ /-- The sum of a function over `points_with_circumcenter_index`. -/ lemma sum_points_with_circumcenter {α : Type*} [add_comm_monoid α] {n : ℕ} (f : points_with_circumcenter_index n → α) : ∑ i, f i = (∑ (i : fin (n + 1)), f (point_index i)) + f circumcenter_index := begin have h : univ = insert circumcenter_index (univ.map (point_index_embedding n)), { ext x, refine ⟨λ h, _, λ _, mem_univ _⟩, cases x with i, { exact mem_insert_of_mem (mem_map_of_mem _ (mem_univ i)) }, { exact mem_insert_self _ _ } }, change _ = ∑ i, f (point_index_embedding n i) + _, rw [add_comm, h, ←sum_map, sum_insert], simp_rw [finset.mem_map, not_exists], intros x hx h, injection h end include V /-- The vertices of a simplex plus its circumcenter. -/ def points_with_circumcenter {n : ℕ} (s : simplex ℝ P n) : points_with_circumcenter_index n → P | (point_index i) := s.points i | circumcenter_index := s.circumcenter /-- `points_with_circumcenter`, applied to a `point_index` value, equals `points` applied to that value. -/ @[simp] lemma points_with_circumcenter_point {n : ℕ} (s : simplex ℝ P n) (i : fin (n + 1)) : s.points_with_circumcenter (point_index i) = s.points i := rfl /-- `points_with_circumcenter`, applied to `circumcenter_index`, equals the circumcenter. -/ @[simp] lemma points_with_circumcenter_eq_circumcenter {n : ℕ} (s : simplex ℝ P n) : s.points_with_circumcenter circumcenter_index = s.circumcenter := rfl omit V /-- The weights for a single vertex of a simplex, in terms of `points_with_circumcenter`. -/ def point_weights_with_circumcenter {n : ℕ} (i : fin (n + 1)) : points_with_circumcenter_index n → ℝ | (point_index j) := if j = i then 1 else 0 | circumcenter_index := 0 /-- `point_weights_with_circumcenter` sums to 1. -/ @[simp] lemma sum_point_weights_with_circumcenter {n : ℕ} (i : fin (n + 1)) : ∑ j, point_weights_with_circumcenter i j = 1 := begin convert sum_ite_eq' univ (point_index i) (function.const _ (1 : ℝ)), { ext j, cases j ; simp [point_weights_with_circumcenter] }, { simp } end include V /-- A single vertex, in terms of `points_with_circumcenter`. -/ lemma point_eq_affine_combination_of_points_with_circumcenter {n : ℕ} (s : simplex ℝ P n) (i : fin (n + 1)) : s.points i = (univ : finset (points_with_circumcenter_index n)).affine_combination s.points_with_circumcenter (point_weights_with_circumcenter i) := begin rw ←points_with_circumcenter_point, symmetry, refine affine_combination_of_eq_one_of_eq_zero _ _ _ (mem_univ _) (by simp [point_weights_with_circumcenter]) _, intros i hi hn, cases i, { have h : i_1 ≠ i := λ h, hn (h ▸ rfl), simp [point_weights_with_circumcenter, h] }, { refl } end omit V /-- The weights for the centroid of some vertices of a simplex, in terms of `points_with_circumcenter`. -/ def centroid_weights_with_circumcenter {n : ℕ} (fs : finset (fin (n + 1))) : points_with_circumcenter_index n → ℝ | (point_index i) := if i ∈ fs then ((card fs : ℝ) ⁻¹) else 0 | circumcenter_index := 0 /-- `centroid_weights_with_circumcenter` sums to 1, if the `finset` is nonempty. -/ @[simp] lemma sum_centroid_weights_with_circumcenter {n : ℕ} {fs : finset (fin (n + 1))} (h : fs.nonempty) : ∑ i, centroid_weights_with_circumcenter fs i = 1 := begin simp_rw [sum_points_with_circumcenter, centroid_weights_with_circumcenter, add_zero, ←fs.sum_centroid_weights_eq_one_of_nonempty ℝ h, set.sum_indicator_subset _ fs.subset_univ], rcongr end include V /-- The centroid of some vertices of a simplex, in terms of `points_with_circumcenter`. -/ lemma centroid_eq_affine_combination_of_points_with_circumcenter {n : ℕ} (s : simplex ℝ P n) (fs : finset (fin (n + 1))) : fs.centroid ℝ s.points = (univ : finset (points_with_circumcenter_index n)).affine_combination s.points_with_circumcenter (centroid_weights_with_circumcenter fs) := begin simp_rw [centroid_def, affine_combination_apply, weighted_vsub_of_point_apply, sum_points_with_circumcenter, centroid_weights_with_circumcenter, points_with_circumcenter_point, zero_smul, add_zero, centroid_weights, set.sum_indicator_subset_of_eq_zero (function.const (fin (n + 1)) ((card fs : ℝ)⁻¹)) (λ i wi, wi • (s.points i -ᵥ classical.choice add_torsor.nonempty)) fs.subset_univ (λ i, zero_smul ℝ _), set.indicator_apply], congr, end omit V /-- The weights for the circumcenter of a simplex, in terms of `points_with_circumcenter`. -/ def circumcenter_weights_with_circumcenter (n : ℕ) : points_with_circumcenter_index n → ℝ | (point_index i) := 0 | circumcenter_index := 1 /-- `circumcenter_weights_with_circumcenter` sums to 1. -/ @[simp] lemma sum_circumcenter_weights_with_circumcenter (n : ℕ) : ∑ i, circumcenter_weights_with_circumcenter n i = 1 := begin convert sum_ite_eq' univ circumcenter_index (function.const _ (1 : ℝ)), { ext ⟨j⟩ ; simp [circumcenter_weights_with_circumcenter] }, { simp } end include V /-- The circumcenter of a simplex, in terms of `points_with_circumcenter`. -/ lemma circumcenter_eq_affine_combination_of_points_with_circumcenter {n : ℕ} (s : simplex ℝ P n) : s.circumcenter = (univ : finset (points_with_circumcenter_index n)).affine_combination s.points_with_circumcenter (circumcenter_weights_with_circumcenter n) := begin rw ←points_with_circumcenter_eq_circumcenter, symmetry, refine affine_combination_of_eq_one_of_eq_zero _ _ _ (mem_univ _) rfl _, rintros ⟨i⟩ hi hn ; tauto end omit V /-- The weights for the reflection of the circumcenter in an edge of a simplex. This definition is only valid with `i₁ ≠ i₂`. -/ def reflection_circumcenter_weights_with_circumcenter {n : ℕ} (i₁ i₂ : fin (n + 1)) : points_with_circumcenter_index n → ℝ | (point_index i) := if i = i₁ ∨ i = i₂ then 1 else 0 | circumcenter_index := -1 /-- `reflection_circumcenter_weights_with_circumcenter` sums to 1. -/ @[simp] lemma sum_reflection_circumcenter_weights_with_circumcenter {n : ℕ} {i₁ i₂ : fin (n + 1)} (h : i₁ ≠ i₂) : ∑ i, reflection_circumcenter_weights_with_circumcenter i₁ i₂ i = 1 := begin simp_rw [sum_points_with_circumcenter, reflection_circumcenter_weights_with_circumcenter, sum_ite, sum_const, filter_or, filter_eq'], rw card_union_eq, { simp }, { simpa only [if_true, mem_univ, disjoint_singleton] using h } end include V /-- The reflection of the circumcenter of a simplex in an edge, in terms of `points_with_circumcenter`. -/ lemma reflection_circumcenter_eq_affine_combination_of_points_with_circumcenter {n : ℕ} (s : simplex ℝ P n) {i₁ i₂ : fin (n + 1)} (h : i₁ ≠ i₂) : reflection (affine_span ℝ (s.points '' {i₁, i₂})) s.circumcenter = (univ : finset (points_with_circumcenter_index n)).affine_combination s.points_with_circumcenter (reflection_circumcenter_weights_with_circumcenter i₁ i₂) := begin have hc : card ({i₁, i₂} : finset (fin (n + 1))) = 2, { simp [h] }, -- Making the next line a separate definition helps the elaborator: set W : affine_subspace ℝ P := affine_span ℝ (s.points '' {i₁, i₂}) with W_def, have h_faces : ↑(orthogonal_projection W s.circumcenter) = ↑((s.face hc).orthogonal_projection_span s.circumcenter), { apply eq_orthogonal_projection_of_eq_subspace, simp }, rw [euclidean_geometry.reflection_apply, h_faces, s.orthogonal_projection_circumcenter hc, circumcenter_eq_centroid, s.face_centroid_eq_centroid hc, centroid_eq_affine_combination_of_points_with_circumcenter, circumcenter_eq_affine_combination_of_points_with_circumcenter, ←@vsub_eq_zero_iff_eq V, affine_combination_vsub, weighted_vsub_vadd_affine_combination, affine_combination_vsub, weighted_vsub_apply, sum_points_with_circumcenter], simp_rw [pi.sub_apply, pi.add_apply, pi.sub_apply, sub_smul, add_smul, sub_smul, centroid_weights_with_circumcenter, circumcenter_weights_with_circumcenter, reflection_circumcenter_weights_with_circumcenter, ite_smul, zero_smul, sub_zero, apply_ite2 (+), add_zero, ←add_smul, hc, zero_sub, neg_smul, sub_self, add_zero], convert sum_const_zero, norm_num end end simplex end affine namespace euclidean_geometry open affine affine_subspace finite_dimensional variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] include V /-- Given a nonempty affine subspace, whose direction is complete, that contains a set of points, those points are cospherical if and only if they are equidistant from some point in that subspace. -/ lemma cospherical_iff_exists_mem_of_complete {s : affine_subspace ℝ P} {ps : set P} (h : ps ⊆ s) [nonempty s] [complete_space s.direction] : cospherical ps ↔ ∃ (center ∈ s) (radius : ℝ), ∀ p ∈ ps, dist p center = radius := begin split, { rintro ⟨c, hcr⟩, rw exists_dist_eq_iff_exists_dist_orthogonal_projection_eq h c at hcr, exact ⟨orthogonal_projection s c, orthogonal_projection_mem _, hcr⟩ }, { exact λ ⟨c, hc, hd⟩, ⟨c, hd⟩ } end /-- Given a nonempty affine subspace, whose direction is finite-dimensional, that contains a set of points, those points are cospherical if and only if they are equidistant from some point in that subspace. -/ lemma cospherical_iff_exists_mem_of_finite_dimensional {s : affine_subspace ℝ P} {ps : set P} (h : ps ⊆ s) [nonempty s] [finite_dimensional ℝ s.direction] : cospherical ps ↔ ∃ (center ∈ s) (radius : ℝ), ∀ p ∈ ps, dist p center = radius := cospherical_iff_exists_mem_of_complete h /-- All n-simplices among cospherical points in an n-dimensional subspace have the same circumradius. -/ lemma exists_circumradius_eq_of_cospherical_subset {s : affine_subspace ℝ P} {ps : set P} (h : ps ⊆ s) [nonempty s] {n : ℕ} [finite_dimensional ℝ s.direction] (hd : finrank ℝ s.direction = n) (hc : cospherical ps) : ∃ r : ℝ, ∀ sx : simplex ℝ P n, set.range sx.points ⊆ ps → sx.circumradius = r := begin rw cospherical_iff_exists_mem_of_finite_dimensional h at hc, rcases hc with ⟨c, hc, r, hcr⟩, use r, intros sx hsxps, have hsx : affine_span ℝ (set.range sx.points) = s, { refine sx.independent.affine_span_eq_of_le_of_card_eq_finrank_add_one (span_points_subset_coe_of_subset_coe (hsxps.trans h)) _, simp [hd] }, have hc : c ∈ affine_span ℝ (set.range sx.points) := hsx.symm ▸ hc, exact (sx.eq_circumradius_of_dist_eq hc (λ i, hcr (sx.points i) (hsxps (set.mem_range_self i)))).symm end /-- Two n-simplices among cospherical points in an n-dimensional subspace have the same circumradius. -/ lemma circumradius_eq_of_cospherical_subset {s : affine_subspace ℝ P} {ps : set P} (h : ps ⊆ s) [nonempty s] {n : ℕ} [finite_dimensional ℝ s.direction] (hd : finrank ℝ s.direction = n) (hc : cospherical ps) {sx₁ sx₂ : simplex ℝ P n} (hsx₁ : set.range sx₁.points ⊆ ps) (hsx₂ : set.range sx₂.points ⊆ ps) : sx₁.circumradius = sx₂.circumradius := begin rcases exists_circumradius_eq_of_cospherical_subset h hd hc with ⟨r, hr⟩, rw [hr sx₁ hsx₁, hr sx₂ hsx₂] end /-- All n-simplices among cospherical points in n-space have the same circumradius. -/ lemma exists_circumradius_eq_of_cospherical {ps : set P} {n : ℕ} [finite_dimensional ℝ V] (hd : finrank ℝ V = n) (hc : cospherical ps) : ∃ r : ℝ, ∀ sx : simplex ℝ P n, set.range sx.points ⊆ ps → sx.circumradius = r := begin haveI : nonempty (⊤ : affine_subspace ℝ P) := set.univ.nonempty, rw [←finrank_top, ←direction_top ℝ V P] at hd, refine exists_circumradius_eq_of_cospherical_subset _ hd hc, exact set.subset_univ _ end /-- Two n-simplices among cospherical points in n-space have the same circumradius. -/ lemma circumradius_eq_of_cospherical {ps : set P} {n : ℕ} [finite_dimensional ℝ V] (hd : finrank ℝ V = n) (hc : cospherical ps) {sx₁ sx₂ : simplex ℝ P n} (hsx₁ : set.range sx₁.points ⊆ ps) (hsx₂ : set.range sx₂.points ⊆ ps) : sx₁.circumradius = sx₂.circumradius := begin rcases exists_circumradius_eq_of_cospherical hd hc with ⟨r, hr⟩, rw [hr sx₁ hsx₁, hr sx₂ hsx₂] end /-- All n-simplices among cospherical points in an n-dimensional subspace have the same circumcenter. -/ lemma exists_circumcenter_eq_of_cospherical_subset {s : affine_subspace ℝ P} {ps : set P} (h : ps ⊆ s) [nonempty s] {n : ℕ} [finite_dimensional ℝ s.direction] (hd : finrank ℝ s.direction = n) (hc : cospherical ps) : ∃ c : P, ∀ sx : simplex ℝ P n, set.range sx.points ⊆ ps → sx.circumcenter = c := begin rw cospherical_iff_exists_mem_of_finite_dimensional h at hc, rcases hc with ⟨c, hc, r, hcr⟩, use c, intros sx hsxps, have hsx : affine_span ℝ (set.range sx.points) = s, { refine sx.independent.affine_span_eq_of_le_of_card_eq_finrank_add_one (span_points_subset_coe_of_subset_coe (hsxps.trans h)) _, simp [hd] }, have hc : c ∈ affine_span ℝ (set.range sx.points) := hsx.symm ▸ hc, exact (sx.eq_circumcenter_of_dist_eq hc (λ i, hcr (sx.points i) (hsxps (set.mem_range_self i)))).symm end /-- Two n-simplices among cospherical points in an n-dimensional subspace have the same circumcenter. -/ lemma circumcenter_eq_of_cospherical_subset {s : affine_subspace ℝ P} {ps : set P} (h : ps ⊆ s) [nonempty s] {n : ℕ} [finite_dimensional ℝ s.direction] (hd : finrank ℝ s.direction = n) (hc : cospherical ps) {sx₁ sx₂ : simplex ℝ P n} (hsx₁ : set.range sx₁.points ⊆ ps) (hsx₂ : set.range sx₂.points ⊆ ps) : sx₁.circumcenter = sx₂.circumcenter := begin rcases exists_circumcenter_eq_of_cospherical_subset h hd hc with ⟨r, hr⟩, rw [hr sx₁ hsx₁, hr sx₂ hsx₂] end /-- All n-simplices among cospherical points in n-space have the same circumcenter. -/ lemma exists_circumcenter_eq_of_cospherical {ps : set P} {n : ℕ} [finite_dimensional ℝ V] (hd : finrank ℝ V = n) (hc : cospherical ps) : ∃ c : P, ∀ sx : simplex ℝ P n, set.range sx.points ⊆ ps → sx.circumcenter = c := begin haveI : nonempty (⊤ : affine_subspace ℝ P) := set.univ.nonempty, rw [←finrank_top, ←direction_top ℝ V P] at hd, refine exists_circumcenter_eq_of_cospherical_subset _ hd hc, exact set.subset_univ _ end /-- Two n-simplices among cospherical points in n-space have the same circumcenter. -/ lemma circumcenter_eq_of_cospherical {ps : set P} {n : ℕ} [finite_dimensional ℝ V] (hd : finrank ℝ V = n) (hc : cospherical ps) {sx₁ sx₂ : simplex ℝ P n} (hsx₁ : set.range sx₁.points ⊆ ps) (hsx₂ : set.range sx₂.points ⊆ ps) : sx₁.circumcenter = sx₂.circumcenter := begin rcases exists_circumcenter_eq_of_cospherical hd hc with ⟨r, hr⟩, rw [hr sx₁ hsx₁, hr sx₂ hsx₂] end /-- Suppose all distances from `p₁` and `p₂` to the points of a simplex are equal, and that `p₁` and `p₂` lie in the affine span of `p` with the vertices of that simplex. Then `p₁` and `p₂` are equal or reflections of each other in the affine span of the vertices of the simplex. -/ lemma eq_or_eq_reflection_of_dist_eq {n : ℕ} {s : simplex ℝ P n} {p p₁ p₂ : P} {r : ℝ} (hp₁ : p₁ ∈ affine_span ℝ (insert p (set.range s.points))) (hp₂ : p₂ ∈ affine_span ℝ (insert p (set.range s.points))) (h₁ : ∀ i, dist (s.points i) p₁ = r) (h₂ : ∀ i, dist (s.points i) p₂ = r) : p₁ = p₂ ∨ p₁ = reflection (affine_span ℝ (set.range s.points)) p₂ := begin let span_s := affine_span ℝ (set.range s.points), have h₁' := s.orthogonal_projection_eq_circumcenter_of_dist_eq h₁, have h₂' := s.orthogonal_projection_eq_circumcenter_of_dist_eq h₂, rw [←affine_span_insert_affine_span, mem_affine_span_insert_iff (orthogonal_projection_mem p)] at hp₁ hp₂, obtain ⟨r₁, p₁o, hp₁o, hp₁⟩ := hp₁, obtain ⟨r₂, p₂o, hp₂o, hp₂⟩ := hp₂, obtain rfl : ↑(s.orthogonal_projection_span p₁) = p₁o, { subst hp₁, exact s.coe_orthogonal_projection_vadd_smul_vsub_orthogonal_projection hp₁o }, rw h₁' at hp₁, obtain rfl : ↑(s.orthogonal_projection_span p₂) = p₂o, { subst hp₂, exact s.coe_orthogonal_projection_vadd_smul_vsub_orthogonal_projection hp₂o }, rw h₂' at hp₂, have h : s.points 0 ∈ span_s := mem_affine_span ℝ (set.mem_range_self _), have hd₁ : dist p₁ s.circumcenter * dist p₁ s.circumcenter = r * r - s.circumradius * s.circumradius := s.dist_circumcenter_sq_eq_sq_sub_circumradius h₁ h₁' h, have hd₂ : dist p₂ s.circumcenter * dist p₂ s.circumcenter = r * r - s.circumradius * s.circumradius := s.dist_circumcenter_sq_eq_sq_sub_circumradius h₂ h₂' h, rw [←hd₂, hp₁, hp₂, dist_eq_norm_vsub V _ s.circumcenter, dist_eq_norm_vsub V _ s.circumcenter, vadd_vsub, vadd_vsub, ←real_inner_self_eq_norm_mul_norm, ←real_inner_self_eq_norm_mul_norm, real_inner_smul_left, real_inner_smul_left, real_inner_smul_right, real_inner_smul_right, ←mul_assoc, ←mul_assoc] at hd₁, by_cases hp : p = s.orthogonal_projection_span p, { rw simplex.orthogonal_projection_span at hp, rw [hp₁, hp₂, ←hp], simp only [true_or, eq_self_iff_true, smul_zero, vsub_self] }, { have hz : ⟪p -ᵥ orthogonal_projection span_s p, p -ᵥ orthogonal_projection span_s p⟫ ≠ 0, by simpa only [ne.def, vsub_eq_zero_iff_eq, inner_self_eq_zero] using hp, rw [mul_left_inj' hz, mul_self_eq_mul_self_iff] at hd₁, rw [hp₁, hp₂], cases hd₁, { left, rw hd₁ }, { right, rw [hd₁, reflection_vadd_smul_vsub_orthogonal_projection p r₂ s.circumcenter_mem_affine_span, neg_smul] } } end end euclidean_geometry
64b13bbf0d7ca107203c99964a359a3270271e86
b2e508d02500f1512e1618150413e6be69d9db10
/src/category_theory/whiskering.lean
38ecd24f5266722794abe54a10e811628196162d
[ "Apache-2.0" ]
permissive
callum-sutton/mathlib
c3788f90216e9cd43eeffcb9f8c9f959b3b01771
afd623825a3ac6bfbcc675a9b023edad3f069e89
refs/heads/master
1,591,371,888,053
1,560,990,690,000
1,560,990,690,000
192,476,045
0
0
Apache-2.0
1,568,941,843,000
1,560,837,965,000
Lean
UTF-8
Lean
false
false
7,537
lean
-- Copyright (c) 2018 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison import category_theory.natural_isomorphism namespace category_theory universes u₁ v₁ u₂ v₂ u₃ v₃ u₄ v₄ section variables (C : Type u₁) [𝒞 : category.{v₁} C] (D : Type u₂) [𝒟 : category.{v₂} D] (E : Type u₃) [ℰ : category.{v₃} E] include 𝒞 𝒟 ℰ def whiskering_left : (C ⥤ D) ⥤ ((D ⥤ E) ⥤ (C ⥤ E)) := { obj := λ F, { obj := λ G, F ⋙ G, map := λ G H α, { app := λ c, α.app (F.obj c), naturality' := by intros X Y f; rw [functor.comp_map, functor.comp_map, α.naturality] } }, map := λ F G τ, { app := λ H, { app := λ c, H.map (τ.app c), naturality' := λ X Y f, begin dsimp, rw [←H.map_comp, ←H.map_comp, ←τ.naturality] end }, naturality' := λ X Y f, begin ext1, dsimp, rw [f.naturality] end } } def whiskering_right : (D ⥤ E) ⥤ ((C ⥤ D) ⥤ (C ⥤ E)) := { obj := λ H, { obj := λ F, F ⋙ H, map := λ _ _ α, { app := λ c, H.map (α.app c), naturality' := by intros X Y f; rw [functor.comp_map, functor.comp_map, ←H.map_comp, ←H.map_comp, α.naturality] } }, map := λ G H τ, { app := λ F, { app := λ c, τ.app (F.obj c), naturality' := λ X Y f, begin dsimp, rw [τ.naturality] end }, naturality' := λ X Y f, begin ext1, dsimp, rw [←nat_trans.naturality] end } } variables {C} {D} {E} def whisker_left (F : C ⥤ D) {G H : D ⥤ E} (α : G ⟶ H) : (F ⋙ G) ⟶ (F ⋙ H) := ((whiskering_left C D E).obj F).map α @[simp] lemma whiskering_left_obj_obj (F : C ⥤ D) (G : D ⥤ E) : ((whiskering_left C D E).obj F).obj G = F ⋙ G := rfl @[simp] lemma whiskering_left_obj_map (F : C ⥤ D) {G H : D ⥤ E} (α : G ⟶ H) : ((whiskering_left C D E).obj F).map α = whisker_left F α := rfl @[simp] lemma whiskering_left_map_app_app {F G : C ⥤ D} (τ : F ⟶ G) (H : D ⥤ E) (c) : (((whiskering_left C D E).map τ).app H).app c = H.map (τ.app c) := rfl @[simp] lemma whisker_left.app (F : C ⥤ D) {G H : D ⥤ E} (α : G ⟶ H) (X : C) : (whisker_left F α).app X = α.app (F.obj X) := rfl def whisker_right {G H : C ⥤ D} (α : G ⟶ H) (F : D ⥤ E) : (G ⋙ F) ⟶ (H ⋙ F) := ((whiskering_right C D E).obj F).map α @[simp] lemma whiskering_right_obj_obj (G : C ⥤ D) (F : D ⥤ E) : ((whiskering_right C D E).obj F).obj G = G ⋙ F := rfl @[simp] lemma whiskering_right_obj_map {G H : C ⥤ D} (α : G ⟶ H) (F : D ⥤ E) : ((whiskering_right C D E).obj F).map α = whisker_right α F := rfl @[simp] lemma whiskering_right_map_app_app (F : C ⥤ D) {G H : D ⥤ E} (τ : G ⟶ H) (c) : (((whiskering_right C D E).map τ).app F).app c = τ.app (F.obj c) := rfl @[simp] lemma whisker_right.app {G H : C ⥤ D} (α : G ⟶ H) (F : D ⥤ E) (X : C) : (whisker_right α F).app X = F.map (α.app X) := rfl @[simp] lemma whisker_left_id (F : C ⥤ D) {G : D ⥤ E} : whisker_left F (nat_trans.id G) = nat_trans.id (F.comp G) := rfl @[simp] lemma whisker_left_id' (F : C ⥤ D) {G : D ⥤ E} : whisker_left F (𝟙 G) = 𝟙 (F.comp G) := rfl @[simp] lemma whisker_right_id {G : C ⥤ D} (F : D ⥤ E) : whisker_right (nat_trans.id G) F = nat_trans.id (G.comp F) := ((whiskering_right C D E).obj F).map_id _ @[simp] lemma whisker_right_id' {G : C ⥤ D} (F : D ⥤ E) : whisker_right (𝟙 G) F = 𝟙 (G.comp F) := ((whiskering_right C D E).obj F).map_id _ @[simp] lemma whisker_left_comp (F : C ⥤ D) {G H K : D ⥤ E} (α : G ⟶ H) (β : H ⟶ K) : whisker_left F (α ≫ β) = (whisker_left F α) ≫ (whisker_left F β) := rfl @[simp] lemma whisker_right_comp {G H K : C ⥤ D} (α : G ⟶ H) (β : H ⟶ K) (F : D ⥤ E) : whisker_right (α ≫ β) F = (whisker_right α F) ≫ (whisker_right β F) := ((whiskering_right C D E).obj F).map_comp α β def iso_whisker_left (F : C ⥤ D) {G H : D ⥤ E} (α : G ≅ H) : (F ⋙ G) ≅ (F ⋙ H) := ((whiskering_left C D E).obj F).map_iso α @[simp] lemma iso_whisker_left_hom (F : C ⥤ D) {G H : D ⥤ E} (α : G ≅ H) : (iso_whisker_left F α).hom = whisker_left F α.hom := rfl @[simp] lemma iso_whisker_left_inv (F : C ⥤ D) {G H : D ⥤ E} (α : G ≅ H) : (iso_whisker_left F α).inv = whisker_left F α.inv := rfl def iso_whisker_right {G H : C ⥤ D} (α : G ≅ H) (F : D ⥤ E) : (G ⋙ F) ≅ (H ⋙ F) := ((whiskering_right C D E).obj F).map_iso α @[simp] lemma iso_whisker_right_hom {G H : C ⥤ D} (α : G ≅ H) (F : D ⥤ E) : (iso_whisker_right α F).hom = whisker_right α.hom F := rfl @[simp] lemma iso_whisker_right_inv {G H : C ⥤ D} (α : G ≅ H) (F : D ⥤ E) : (iso_whisker_right α F).inv = whisker_right α.inv F := rfl variables {B : Type u₄} [ℬ : category.{v₄} B] include ℬ local attribute [elab_simple] whisker_left whisker_right @[simp] lemma whisker_left_twice (F : B ⥤ C) (G : C ⥤ D) {H K : D ⥤ E} (α : H ⟶ K) : whisker_left F (whisker_left G α) = whisker_left (F ⋙ G) α := rfl @[simp] lemma whisker_right_twice {H K : B ⥤ C} (F : C ⥤ D) (G : D ⥤ E) (α : H ⟶ K) : whisker_right (whisker_right α F) G = whisker_right α (F ⋙ G) := rfl lemma whisker_right_left (F : B ⥤ C) {G H : C ⥤ D} (α : G ⟶ H) (K : D ⥤ E) : whisker_right (whisker_left F α) K = whisker_left F (whisker_right α K) := rfl end namespace functor universes u₅ v₅ variables {A : Type u₁} [𝒜 : category.{v₁} A] variables {B : Type u₂} [ℬ : category.{v₂} B] include 𝒜 ℬ def left_unitor (F : A ⥤ B) : ((functor.id _) ⋙ F) ≅ F := { hom := { app := λ X, 𝟙 (F.obj X) }, inv := { app := λ X, 𝟙 (F.obj X) } } @[simp] lemma left_unitor_hom_app {F : A ⥤ B} {X} : F.left_unitor.hom.app X = 𝟙 _ := rfl @[simp] lemma left_unitor_inv_app {F : A ⥤ B} {X} : F.left_unitor.inv.app X = 𝟙 _ := rfl def right_unitor (F : A ⥤ B) : (F ⋙ (functor.id _)) ≅ F := { hom := { app := λ X, 𝟙 (F.obj X) }, inv := { app := λ X, 𝟙 (F.obj X) } } @[simp] lemma right_unitor_hom_app {F : A ⥤ B} {X} : F.right_unitor.hom.app X = 𝟙 _ := rfl @[simp] lemma right_unitor_inv_app {F : A ⥤ B} {X} : F.right_unitor.inv.app X = 𝟙 _ := rfl variables {C : Type u₃} [𝒞 : category.{v₃} C] variables {D : Type u₄} [𝒟 : category.{v₄} D] include 𝒞 𝒟 def associator (F : A ⥤ B) (G : B ⥤ C) (H : C ⥤ D) : ((F ⋙ G) ⋙ H) ≅ (F ⋙ (G ⋙ H)) := { hom := { app := λ _, 𝟙 _ }, inv := { app := λ _, 𝟙 _ } } @[simp] lemma associator_hom_app {F : A ⥤ B} {G : B ⥤ C} {H : C ⥤ D} {X} : (associator F G H).hom.app X = 𝟙 _ := rfl @[simp] lemma associator_inv_app {F : A ⥤ B} {G : B ⥤ C} {H : C ⥤ D} {X} : (associator F G H).inv.app X = 𝟙 _ := rfl omit 𝒟 lemma triangle (F : A ⥤ B) (G : B ⥤ C) : (associator F (functor.id B) G).hom ≫ (whisker_left F (left_unitor G).hom) = (whisker_right (right_unitor F).hom G) := begin ext1, dsimp [associator, left_unitor, right_unitor], simp end variables {E : Type u₅} [ℰ : category.{v₅} E] include 𝒟 ℰ variables (F : A ⥤ B) (G : B ⥤ C) (H : C ⥤ D) (K : D ⥤ E) lemma pentagon : (whisker_right (associator F G H).hom K) ≫ (associator F (G ⋙ H) K).hom ≫ (whisker_left F (associator G H K).hom) = ((associator (F ⋙ G) H K).hom ≫ (associator F G (H ⋙ K)).hom) := begin ext1, dsimp [associator], simp, end end functor end category_theory
b0c481ffed93b33246f7b5108fd17d5c52fab7f9
b09ab112c2467bddcdeb905c5de5336fc58f1b2b
/ord.lean
2862f4bcee89d0c3092aeb786888f9454cae4893
[ "MIT" ]
permissive
Nolrai/EpsilonOrdinals
71b913c1674637eb68f29f8c3d2ecfd198717989
ff4c8945eb94b1baf7194efe79998832bcb6be2d
refs/heads/master
1,471,017,041,666
1,458,797,649,000
1,458,797,649,000
51,234,651
0
0
null
null
null
null
UTF-8
Lean
false
false
7,061
lean
inductive ord : Type := | Zero : ord | Stroke : ord -> ord -> ord open ord infix `∥`:50 := Stroke definition ord.has_zero [instance] : has_zero ord := {| has_zero, zero := Zero |} attribute Stroke [coercion] --this seems to act flaky? definition ord.has_one [instance] : has_one ord := has_one.mk (0 ∥ 0) inductive ord.le : ord -> ord -> Prop := | refl {} : ∀ r : ord, ord.le r r | app {} : ∀ r q f : ord, ord.le q r -> ord.le q (f r) | mono {} : ∀ r q g f : ord, ord.le q r -> ord.le g f -> ord.le (g q) (f r) | limit {} : ∀ r q g f : ord, q ≠ f -> ord.le q (f r) -> ord.le g f -> ord.le (g q) (f r) local infix ≤ := ord.le definition ord.has_le [instance] : has_le ord := has_le.mk ord.le open ord.le lemma zero_le : ∀ r : ord, 0 ≤ r := begin intro r, induction r, {exact (ord.le.refl _)}, { apply app, { assumption }, } end lemma le_zero : ∀ r : ord, r ≤ 0 -> r = 0 := begin intros r H, cases H, esimp, end open nat definition nat.max : nat -> nat -> nat | 0 m := m | n 0 := n | (succ n) (succ m) := succ (nat.max n m) definition hight : ∀ o : ord, nat | 0 := 0 | (f ∥ r) := 1 + nat.max (hight f) (hight r) record has_swap [class] (A : Type) : Type := (swap : A -> A) record has_involution [class] (A : Type) extends (has_swap A) := (is_involution : ∀ x, swap (swap x) = x) abbreviation σ {{A}} [H : has_swap A] x := @has_swap.swap A H x inductive ineq : Type := | LessThan | GreaterThan inductive comp : Type := | Ineq : ineq -> comp | EqualTo namespace ineq abbreviation LT := LessThan abbreviation GT := GreaterThan definition inversion : ineq -> ineq | LT := GT | GT := LT definition ineq_swap [instance] : has_swap ineq := {| has_swap ineq, swap := inversion |} lemma inversion_is_involution : ∀ (x : ineq), σ(σ x) = x := ineq.rec rfl rfl definition ineq_involution [instance] : has_involution ineq := {| has_involution ineq, ineq_swap, is_involution := inversion_is_involution |} end ineq namespace comp export ineq abbreviation EQ := EqualTo attribute comp.Ineq [coercion] definition nudge : ineq -> comp -> comp | tie_breaker EQ := Ineq tie_breaker | _ non_tie := non_tie end comp section comp_spec open comp parameter {A : Type} parameter f : A -> A -> comp local infix `≤` := le variables x y : A definition comp_spec' [H : has_le A] : Prop := match f x y with | LT := x ≤ y | EQ := x = y | GT := y ≤ x end definition comp_spec [H : has_le A] : Prop := ∀ x y, comp_spec' x y end comp_spec namespace ord open comp open ineq inductive is_child : ord -> ord -> Prop := | through_f : forall {f r}, is_child f (f∥r) | through_r : forall {f r}, is_child r (f∥r) inductive kleen_star {A : Type} (R : A -> A -> Prop) : A -> A -> Prop := | refl : forall {a}, kleen_star R a a | next : forall {a b} c, R a b -> kleen_star R b c -> kleen_star R a c attribute kleen_star.refl [refl] notation R `⋆` := kleen_star R infix `~>`:50 := is_child open eq.ops well_founded decidable prod namespace trans_completion section One parameter A : Type parameter R : A -> A -> Prop end One end trans_completion open trans_completion lemma zero_has_no_children : ∀ x, ¬ (x ~> 0) := begin intros x H, cases H, now end lemma Zero_is_zero : Zero = 0 := rfl reveal Zero_is_zero open ord infix `~~>`:50 := is_child⋆ lemma is_desc_split' : forall y x, y ~~> x -> exists f r, ( y = x ∨ (x = (f∥r) ∧ ((y ~~> f) ∨ (y ~~> r))) ) := begin intros y x H, induction H, {existsi 0, existsi 0, left, reflexivity}, { induction v_0 with f v_1, induction v_1 with r v_2, cases v_2, { clear f r, induction a_1 with f r, all_goals existsi f, all_goals existsi r, all_goals right, all_goals split, all_goals try (symmetry; assumption), {left, reflexivity}, {right, reflexivity} }, { existsi f, existsi r, right, cases a_3 with H HH, split, {assumption}, cases HH with HH, {left, apply kleen_star.next, repeat assumption}, {right, apply kleen_star.next, repeat assumption}, }, }, end definition is_desc_split {y} {f} {r} : y ~~> (f∥r) -> y = (f∥r) ∨ ((y ~~> f) ∨ (y ~~> r)) := begin intros y f r H, assert (∃ f' r', (f∥r) = (f'\||r') ∧ (f∥r) ∨ ((y ~~> f) ∨ (y ~~> r)) end check is_desc_split theorem all_reached : well_founded (TR is_child) := well_founded.intro proof begin intro a, induction a with f r, all_goals split, { intros y H, cases H, { exfalso, assert H : ∃ z, z ~> 0, {existsi y, rewrite Zero_is_zero at a_1, assumption}, cases H, apply zero_has_no_children, assumption }, { exfalso, assert H : ∃ z, z ~> 0, {apply trans_valid, apply a_2}, cases H, apply zero_has_no_children, apply a_3 }, }, { intro y YH, assert H : (y = f ∨ y = r) ∨ y ~~> f ∨ y ~~> r, {apply is_desc_split, assumption}, cases H with H H, {all_goals cases H with H H, all_goals (subst y; assumption) }, { all_goals cases H with H H, {cases v_0 with _ HH, apply HH, assumption}, {cases v_1 with _ HH, apply HH, assumption}, }, } end qed protected definition R := rprod (TR is_child) (TR is_child) theorem wfR : well_founded ord.R := rprod.wf all_reached all_reached local infix `⟪`:50 := ord.R private lemma lemma1 : Π fp rp fq rq, (rp, rq)⟪(fp∥rp, fq∥rq) := take fp rp fq rq : ord, have Hp : rp ⟪ (fp∥rp), from TR.single is_child.through_r, qed definition compOrd' : Π x : (ord×ord), (Π p : (ord×ord), p ⟪ x ->comp) -> comp | (0,0) _ := EQ | (0,_) _ := Ineq LT | (_,0) _ := Ineq GT | ((fp∥rp),(fq∥rq)) f := match f (fp,fq) lemma1 with | EQ := f (rp,rq) _ | LT := nudge GT (f (rp,(fq∥rq)) _) | GT := nudge LT (f ((fp∥rp),rq) _) end end definition compOrd x y := fix compOrd' (x,y) end ord end
ad238f7c85df5e176cd7411933df32d4ab52a4d9
e6b8240a90527fd55d42d0ec6649253d5d0bd414
/src/algebra/big_operators.lean
a1d78b99fff9b7f2c645dc08858e9f10604ca1d8
[ "Apache-2.0" ]
permissive
mattearnshaw/mathlib
ac90f9fb8168aa642223bea3ffd0286b0cfde44f
d8dc1445cf8a8c74f8df60b9f7a1f5cf10946666
refs/heads/master
1,606,308,351,137
1,576,594,130,000
1,576,594,130,000
228,666,195
0
0
Apache-2.0
1,576,603,094,000
1,576,603,093,000
null
UTF-8
Lean
false
false
36,070
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl Some big operators for lists and finite sets. -/ import tactic.tauto data.list.basic data.finset data.nat.enat import algebra.group algebra.ordered_group algebra.group_power universes u v w variables {α : Type u} {β : Type v} {γ : Type w} theorem directed.finset_le {r : α → α → Prop} [is_trans α r] {ι} (hι : nonempty ι) {f : ι → α} (D : directed r f) (s : finset ι) : ∃ z, ∀ i ∈ s, r (f i) (f z) := show ∃ z, ∀ i ∈ s.1, r (f i) (f z), from multiset.induction_on s.1 (let ⟨z⟩ := hι in ⟨z, λ _, false.elim⟩) $ λ i s ⟨j, H⟩, let ⟨k, h₁, h₂⟩ := D i j in ⟨k, λ a h, or.cases_on (multiset.mem_cons.1 h) (λ h, h.symm ▸ h₁) (λ h, trans (H _ h) h₂)⟩ theorem finset.exists_le {α : Type u} [nonempty α] [directed_order α] (s : finset α) : ∃ M, ∀ i ∈ s, i ≤ M := directed.finset_le (by apply_instance) directed_order.directed s namespace finset variables {s s₁ s₂ : finset α} {a : α} {f g : α → β} /-- `prod s f` is the product of `f x` as `x` ranges over the elements of the finite set `s`. -/ @[to_additive] protected def prod [comm_monoid β] (s : finset α) (f : α → β) : β := (s.1.map f).prod @[to_additive] lemma prod_eq_multiset_prod [comm_monoid β] (s : finset α) (f : α → β) : s.prod f = (s.1.map f).prod := rfl @[to_additive] theorem prod_eq_fold [comm_monoid β] (s : finset α) (f : α → β) : s.prod f = s.fold (*) 1 f := rfl section comm_monoid variables [comm_monoid β] @[simp, to_additive] lemma prod_empty {α : Type u} {f : α → β} : (∅:finset α).prod f = 1 := rfl @[simp, to_additive] lemma prod_insert [decidable_eq α] : a ∉ s → (insert a s).prod f = f a * s.prod f := fold_insert @[simp, to_additive] lemma prod_singleton : (singleton a).prod f = f a := eq.trans fold_singleton $ mul_one _ @[to_additive] lemma prod_pair [decidable_eq α] {a b : α} (h : a ≠ b) : ({a, b} : finset α).prod f = f a * f b := by simp [prod_insert (not_mem_singleton.2 h.symm), mul_comm] @[simp] lemma prod_const_one : s.prod (λx, (1 : β)) = 1 := by simp only [finset.prod, multiset.map_const, multiset.prod_repeat, one_pow] @[simp] lemma sum_const_zero {β} {s : finset α} [add_comm_monoid β] : s.sum (λx, (0 : β)) = 0 := @prod_const_one _ (multiplicative β) _ _ attribute [to_additive] prod_const_one @[simp, to_additive] lemma prod_image [decidable_eq α] {s : finset γ} {g : γ → α} : (∀x∈s, ∀y∈s, g x = g y → x = y) → (s.image g).prod f = s.prod (λx, f (g x)) := fold_image @[simp, to_additive] lemma prod_map (s : finset α) (e : α ↪ γ) (f : γ → β) : (s.map e).prod f = s.prod (λa, f (e a)) := by rw [finset.prod, finset.map_val, multiset.map_map]; refl @[congr, to_additive] lemma prod_congr (h : s₁ = s₂) : (∀x∈s₂, f x = g x) → s₁.prod f = s₂.prod g := by rw [h]; exact fold_congr attribute [congr] finset.sum_congr @[to_additive] lemma prod_union_inter [decidable_eq α] : (s₁ ∪ s₂).prod f * (s₁ ∩ s₂).prod f = s₁.prod f * s₂.prod f := fold_union_inter @[to_additive] lemma prod_union [decidable_eq α] (h : disjoint s₁ s₂) : (s₁ ∪ s₂).prod f = s₁.prod f * s₂.prod f := by rw [←prod_union_inter, (disjoint_iff_inter_eq_empty.mp h)]; exact (mul_one _).symm @[to_additive] lemma prod_sdiff [decidable_eq α] (h : s₁ ⊆ s₂) : (s₂ \ s₁).prod f * s₁.prod f = s₂.prod f := by rw [←prod_union sdiff_disjoint, sdiff_union_of_subset h] @[to_additive] lemma prod_bind [decidable_eq α] {s : finset γ} {t : γ → finset α} : (∀x∈s, ∀y∈s, x ≠ y → disjoint (t x) (t y)) → (s.bind t).prod f = s.prod (λx, (t x).prod f) := by haveI := classical.dec_eq γ; exact finset.induction_on s (λ _, by simp only [bind_empty, prod_empty]) (assume x s hxs ih hd, have hd' : ∀x∈s, ∀y∈s, x ≠ y → disjoint (t x) (t y), from assume _ hx _ hy, hd _ (mem_insert_of_mem hx) _ (mem_insert_of_mem hy), have ∀y∈s, x ≠ y, from assume _ hy h, by rw [←h] at hy; contradiction, have ∀y∈s, disjoint (t x) (t y), from assume _ hy, hd _ (mem_insert_self _ _) _ (mem_insert_of_mem hy) (this _ hy), have disjoint (t x) (finset.bind s t), from (disjoint_bind_right _ _ _).mpr this, by simp only [bind_insert, prod_insert hxs, prod_union this, ih hd']) @[to_additive] lemma prod_product {s : finset γ} {t : finset α} {f : γ×α → β} : (s.product t).prod f = s.prod (λx, t.prod $ λy, f (x, y)) := begin haveI := classical.dec_eq α, haveI := classical.dec_eq γ, rw [product_eq_bind, prod_bind], { congr, funext, exact prod_image (λ _ _ _ _ H, (prod.mk.inj H).2) }, simp only [disjoint_iff_ne, mem_image], rintros _ _ _ _ h ⟨_, _⟩ ⟨_, _, ⟨_, _⟩⟩ ⟨_, _⟩ ⟨_, _, ⟨_, _⟩⟩ _, apply h, cc end @[to_additive] lemma prod_sigma {σ : α → Type*} {s : finset α} {t : Πa, finset (σ a)} {f : sigma σ → β} : (s.sigma t).prod f = s.prod (λa, (t a).prod $ λs, f ⟨a, s⟩) := by haveI := classical.dec_eq α; haveI := (λ a, classical.dec_eq (σ a)); exact calc (s.sigma t).prod f = (s.bind (λa, (t a).image (λs, sigma.mk a s))).prod f : by rw sigma_eq_bind ... = s.prod (λa, ((t a).image (λs, sigma.mk a s)).prod f) : prod_bind $ assume a₁ ha a₂ ha₂ h, by simp only [disjoint_iff_ne, mem_image]; rintro ⟨_, _⟩ ⟨_, _, _⟩ ⟨_, _⟩ ⟨_, _, _⟩ ⟨_, _⟩; apply h; cc ... = (s.prod $ λa, (t a).prod $ λs, f ⟨a, s⟩) : prod_congr rfl $ λ _ _, prod_image $ λ _ _ _ _ _, by cc @[to_additive] lemma prod_image' [decidable_eq α] {s : finset γ} {g : γ → α} (h : γ → β) (eq : ∀c∈s, f (g c) = (s.filter (λc', g c' = g c)).prod h) : (s.image g).prod f = s.prod h := begin letI := classical.dec_eq γ, rw [← image_bind_filter_eq s g] {occs := occurrences.pos [2]}, rw [finset.prod_bind], { refine finset.prod_congr rfl (assume a ha, _), rcases finset.mem_image.1 ha with ⟨b, hb, rfl⟩, exact eq b hb }, assume a₀ _ a₁ _ ne, refine (disjoint_iff_ne.2 _), assume c₀ h₀ c₁ h₁, rcases mem_filter.1 h₀ with ⟨h₀, rfl⟩, rcases mem_filter.1 h₁ with ⟨h₁, rfl⟩, exact mt (congr_arg g) ne end @[to_additive] lemma prod_mul_distrib : s.prod (λx, f x * g x) = s.prod f * s.prod g := eq.trans (by rw one_mul; refl) fold_op_distrib @[to_additive] lemma prod_comm [decidable_eq γ] {s : finset γ} {t : finset α} {f : γ → α → β} : s.prod (λx, t.prod $ f x) = t.prod (λy, s.prod $ λx, f x y) := finset.induction_on s (by simp only [prod_empty, prod_const_one]) $ λ _ _ H ih, by simp only [prod_insert H, prod_mul_distrib, ih] lemma prod_hom [comm_monoid γ] (g : β → γ) [is_monoid_hom g] : s.prod (λx, g (f x)) = g (s.prod f) := eq.trans (by rw is_monoid_hom.map_one g; refl) (fold_hom $ is_monoid_hom.map_mul g) @[to_additive] lemma prod_hom_rel [comm_monoid γ] {r : β → γ → Prop} {f : α → β} {g : α → γ} {s : finset α} (h₁ : r 1 1) (h₂ : ∀a b c, r b c → r (f a * b) (g a * c)) : r (s.prod f) (s.prod g) := begin letI := classical.dec_eq α, refine finset.induction_on s h₁ (assume a s has ih, _), rw [prod_insert has, prod_insert has], exact h₂ a (s.prod f) (s.prod g) ih, end @[to_additive] lemma prod_subset (h : s₁ ⊆ s₂) (hf : ∀x∈s₂, x ∉ s₁ → f x = 1) : s₁.prod f = s₂.prod f := by haveI := classical.dec_eq α; exact have (s₂ \ s₁).prod f = (s₂ \ s₁).prod (λx, 1), from prod_congr rfl $ by simpa only [mem_sdiff, and_imp], by rw [←prod_sdiff h]; simp only [this, prod_const_one, one_mul] @[to_additive] lemma prod_filter (p : α → Prop) [decidable_pred p] (f : α → β) : (s.filter p).prod f = s.prod (λa, if p a then f a else 1) := calc (s.filter p).prod f = (s.filter p).prod (λa, if p a then f a else 1) : prod_congr rfl (assume a h, by rw [if_pos (mem_filter.1 h).2]) ... = s.prod (λa, if p a then f a else 1) : begin refine prod_subset (filter_subset s) (assume x hs h, _), rw [mem_filter, not_and] at h, exact if_neg (h hs) end @[to_additive] lemma prod_eq_single {s : finset α} {f : α → β} (a : α) (h₀ : ∀b∈s, b ≠ a → f b = 1) (h₁ : a ∉ s → f a = 1) : s.prod f = f a := by haveI := classical.dec_eq α; from classical.by_cases (assume : a ∈ s, calc s.prod f = ({a} : finset α).prod f : begin refine (prod_subset _ _).symm, { intros _ H, rwa mem_singleton.1 H }, { simpa only [mem_singleton] } end ... = f a : prod_singleton) (assume : a ∉ s, (prod_congr rfl $ λ b hb, h₀ b hb $ by rintro rfl; cc).trans $ prod_const_one.trans (h₁ this).symm) @[to_additive] lemma prod_ite [comm_monoid γ] {s : finset α} {p : α → Prop} {hp : decidable_pred p} (f g : α → γ) (h : γ → β) : s.prod (λ x, h (if p x then f x else g x)) = (s.filter p).prod (λ x, h (f x)) * (s.filter (λ x, ¬ p x)).prod (λ x, h (g x)) := by letI := classical.dec_eq α; exact calc s.prod (λ x, h (if p x then f x else g x)) = (s.filter p ∪ s.filter (λ x, ¬ p x)).prod (λ x, h (if p x then f x else g x)) : by rw [filter_union_filter_neg_eq] ... = (s.filter p).prod (λ x, h (if p x then f x else g x)) * (s.filter (λ x, ¬ p x)).prod (λ x, h (if p x then f x else g x)) : prod_union (by simp [disjoint_right] {contextual := tt}) ... = (s.filter p).prod (λ x, h (f x)) * (s.filter (λ x, ¬ p x)).prod (λ x, h (g x)) : congr_arg2 _ (prod_congr rfl (by simp {contextual := tt})) (prod_congr rfl (by simp {contextual := tt})) @[simp, to_additive] lemma prod_ite_eq [decidable_eq α] (s : finset α) (a : α) (b : β) : s.prod (λ x, (ite (a = x) b 1)) = ite (a ∈ s) b 1 := begin rw ←finset.prod_filter, split_ifs; simp only [filter_eq, if_true, if_false, h, prod_empty, prod_singleton, insert_empty_eq_singleton], end @[to_additive] lemma prod_attach {f : α → β} : s.attach.prod (λx, f x.val) = s.prod f := by haveI := classical.dec_eq α; exact calc s.attach.prod (λx, f x.val) = ((s.attach).image subtype.val).prod f : by rw [prod_image]; exact assume x _ y _, subtype.eq ... = _ : by rw [attach_image_val] @[to_additive] lemma prod_bij {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Πa∈s, γ) (hi : ∀a ha, i a ha ∈ t) (h : ∀a ha, f a = g (i a ha)) (i_inj : ∀a₁ a₂ ha₁ ha₂, i a₁ ha₁ = i a₂ ha₂ → a₁ = a₂) (i_surj : ∀b∈t, ∃a ha, b = i a ha) : s.prod f = t.prod g := congr_arg multiset.prod (multiset.map_eq_map_of_bij_of_nodup f g s.2 t.2 i hi h i_inj i_surj) @[to_additive] lemma prod_bij_ne_one {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Πa∈s, f a ≠ 1 → γ) (hi₁ : ∀a h₁ h₂, i a h₁ h₂ ∈ t) (hi₂ : ∀a₁ a₂ h₁₁ h₁₂ h₂₁ h₂₂, i a₁ h₁₁ h₁₂ = i a₂ h₂₁ h₂₂ → a₁ = a₂) (hi₃ : ∀b∈t, g b ≠ 1 → ∃a h₁ h₂, b = i a h₁ h₂) (h : ∀a h₁ h₂, f a = g (i a h₁ h₂)) : s.prod f = t.prod g := by haveI := classical.prop_decidable; exact calc s.prod f = (s.filter $ λx, f x ≠ 1).prod f : (prod_subset (filter_subset _) $ by simp only [not_imp_comm, mem_filter]; exact λ _, and.intro).symm ... = (t.filter $ λx, g x ≠ 1).prod g : prod_bij (assume a ha, i a (mem_filter.mp ha).1 (mem_filter.mp ha).2) (assume a ha, (mem_filter.mp ha).elim $ λh₁ h₂, mem_filter.mpr ⟨hi₁ a h₁ h₂, λ hg, h₂ (hg ▸ h a h₁ h₂)⟩) (assume a ha, (mem_filter.mp ha).elim $ h a) (assume a₁ a₂ ha₁ ha₂, (mem_filter.mp ha₁).elim $ λha₁₁ ha₁₂, (mem_filter.mp ha₂).elim $ λha₂₁ ha₂₂, hi₂ a₁ a₂ _ _ _ _) (assume b hb, (mem_filter.mp hb).elim $ λh₁ h₂, let ⟨a, ha₁, ha₂, eq⟩ := hi₃ b h₁ h₂ in ⟨a, mem_filter.mpr ⟨ha₁, ha₂⟩, eq⟩) ... = t.prod g : (prod_subset (filter_subset _) $ by simp only [not_imp_comm, mem_filter]; exact λ _, and.intro) @[to_additive] lemma exists_ne_one_of_prod_ne_one : s.prod f ≠ 1 → ∃a∈s, f a ≠ 1 := by haveI := classical.dec_eq α; exact finset.induction_on s (λ H, (H rfl).elim) (assume a s has ih h, classical.by_cases (assume ha : f a = 1, let ⟨a, ha, hfa⟩ := ih (by rwa [prod_insert has, ha, one_mul] at h) in ⟨a, mem_insert_of_mem ha, hfa⟩) (assume hna : f a ≠ 1, ⟨a, mem_insert_self _ _, hna⟩)) @[to_additive] lemma prod_range_succ (f : ℕ → β) (n : ℕ) : (range (nat.succ n)).prod f = f n * (range n).prod f := by rw [range_succ, prod_insert not_mem_range_self] lemma prod_range_succ' (f : ℕ → β) : ∀ n : ℕ, (range (nat.succ n)).prod f = (range n).prod (f ∘ nat.succ) * f 0 | 0 := (prod_range_succ _ _).trans $ mul_comm _ _ | (n + 1) := by rw [prod_range_succ (λ m, f (nat.succ m)), mul_assoc, ← prod_range_succ']; exact prod_range_succ _ _ lemma sum_Ico_add {δ : Type*} [add_comm_monoid δ] (f : ℕ → δ) (m n k : ℕ) : (Ico m n).sum (λ l, f (k + l)) = (Ico (m + k) (n + k)).sum f := Ico.image_add m n k ▸ eq.symm $ sum_image $ λ x hx y hy h, nat.add_left_cancel h @[to_additive] lemma prod_Ico_add (f : ℕ → β) (m n k : ℕ) : (Ico m n).prod (λ l, f (k + l)) = (Ico (m + k) (n + k)).prod f := Ico.image_add m n k ▸ eq.symm $ prod_image $ λ x hx y hy h, nat.add_left_cancel h lemma sum_Ico_succ_top {δ : Type*} [add_comm_monoid δ] {a b : ℕ} (hab : a ≤ b) (f : ℕ → δ) : (Ico a (b + 1)).sum f = (Ico a b).sum f + f b := by rw [Ico.succ_top hab, sum_insert Ico.not_mem_top, add_comm] @[to_additive] lemma prod_Ico_succ_top {a b : ℕ} (hab : a ≤ b) (f : ℕ → β) : (Ico a b.succ).prod f = (Ico a b).prod f * f b := @sum_Ico_succ_top (additive β) _ _ _ hab _ lemma sum_eq_sum_Ico_succ_bot {δ : Type*} [add_comm_monoid δ] {a b : ℕ} (hab : a < b) (f : ℕ → δ) : (Ico a b).sum f = f a + (Ico (a + 1) b).sum f := have ha : a ∉ Ico (a + 1) b, by simp, by rw [← sum_insert ha, Ico.insert_succ_bot hab] @[to_additive] lemma prod_eq_prod_Ico_succ_bot {a b : ℕ} (hab : a < b) (f : ℕ → β) : (Ico a b).prod f = f a * (Ico (a + 1) b).prod f := @sum_eq_sum_Ico_succ_bot (additive β) _ _ _ hab _ @[to_additive] lemma prod_Ico_consecutive (f : ℕ → β) {m n k : ℕ} (hmn : m ≤ n) (hnk : n ≤ k) : (Ico m n).prod f * (Ico n k).prod f = (Ico m k).prod f := Ico.union_consecutive hmn hnk ▸ eq.symm $ prod_union $ Ico.disjoint_consecutive m n k @[to_additive] lemma prod_range_mul_prod_Ico (f : ℕ → β) {m n : ℕ} (h : m ≤ n) : (range m).prod f * (Ico m n).prod f = (range n).prod f := Ico.zero_bot m ▸ Ico.zero_bot n ▸ prod_Ico_consecutive f (nat.zero_le m) h @[to_additive sum_Ico_eq_add_neg] lemma prod_Ico_eq_div {δ : Type*} [comm_group δ] (f : ℕ → δ) {m n : ℕ} (h : m ≤ n) : (Ico m n).prod f = (range n).prod f * ((range m).prod f)⁻¹ := eq_mul_inv_iff_mul_eq.2 $ by rw [mul_comm]; exact prod_range_mul_prod_Ico f h lemma sum_Ico_eq_sub {δ : Type*} [add_comm_group δ] (f : ℕ → δ) {m n : ℕ} (h : m ≤ n) : (Ico m n).sum f = (range n).sum f - (range m).sum f := sum_Ico_eq_add_neg f h @[to_additive] lemma prod_Ico_eq_prod_range (f : ℕ → β) (m n : ℕ) : (Ico m n).prod f = (range (n - m)).prod (λ l, f (m + l)) := begin by_cases h : m ≤ n, { rw [← Ico.zero_bot, prod_Ico_add, zero_add, nat.sub_add_cancel h] }, { replace h : n ≤ m := le_of_not_ge h, rw [Ico.eq_empty_of_le h, nat.sub_eq_zero_of_le h, range_zero, prod_empty, prod_empty] } end @[to_additive] lemma prod_range_zero (f : ℕ → β) : (range 0).prod f = 1 := by rw [range_zero, prod_empty] lemma prod_range_one (f : ℕ → β) : (range 1).prod f = f 0 := by { rw [range_one], apply @prod_singleton ℕ β 0 f } lemma sum_range_one {δ : Type*} [add_comm_monoid δ] (f : ℕ → δ) : (range 1).sum f = f 0 := by { rw [range_one], apply @sum_singleton ℕ δ 0 f } attribute [to_additive finset.sum_range_one] prod_range_one @[simp] lemma prod_const (b : β) : s.prod (λ a, b) = b ^ s.card := by haveI := classical.dec_eq α; exact finset.induction_on s rfl (λ a s has ih, by rw [prod_insert has, card_insert_of_not_mem has, pow_succ, ih]) lemma prod_pow (s : finset α) (n : ℕ) (f : α → β) : s.prod (λ x, f x ^ n) = s.prod f ^ n := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (by simp [_root_.mul_pow] {contextual := tt}) lemma prod_nat_pow (s : finset α) (n : ℕ) (f : α → ℕ) : s.prod (λ x, f x ^ n) = s.prod f ^ n := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (by simp [nat.mul_pow] {contextual := tt}) @[to_additive] lemma prod_involution {s : finset α} {f : α → β} : ∀ (g : Π a ∈ s, α) (h₁ : ∀ a ha, f a * f (g a ha) = 1) (h₂ : ∀ a ha, f a ≠ 1 → g a ha ≠ a) (h₃ : ∀ a ha, g a ha ∈ s) (h₄ : ∀ a ha, g (g a ha) (h₃ a ha) = a), s.prod f = 1 := by haveI := classical.dec_eq α; haveI := classical.dec_eq β; exact finset.strong_induction_on s (λ s ih g h₁ h₂ h₃ h₄, if hs : s = ∅ then hs.symm ▸ rfl else let ⟨x, hx⟩ := exists_mem_of_ne_empty hs in have hmem : ∀ y ∈ (s.erase x).erase (g x hx), y ∈ s, from λ y hy, (mem_of_mem_erase (mem_of_mem_erase hy)), have g_inj : ∀ {x hx y hy}, g x hx = g y hy → x = y, from λ x hx y hy h, by rw [← h₄ x hx, ← h₄ y hy]; simp [h], have ih': (erase (erase s x) (g x hx)).prod f = (1 : β) := ih ((s.erase x).erase (g x hx)) ⟨subset.trans (erase_subset _ _) (erase_subset _ _), λ h, not_mem_erase (g x hx) (s.erase x) (h (h₃ x hx))⟩ (λ y hy, g y (hmem y hy)) (λ y hy, h₁ y (hmem y hy)) (λ y hy, h₂ y (hmem y hy)) (λ y hy, mem_erase.2 ⟨λ (h : g y _ = g x hx), by simpa [g_inj h] using hy, mem_erase.2 ⟨λ (h : g y _ = x), have y = g x hx, from h₄ y (hmem y hy) ▸ by simp [h], by simpa [this] using hy, h₃ y (hmem y hy)⟩⟩) (λ y hy, h₄ y (hmem y hy)), if hx1 : f x = 1 then ih' ▸ eq.symm (prod_subset hmem (λ y hy hy₁, have y = x ∨ y = g x hx, by simp [hy] at hy₁; tauto, this.elim (λ h, h.symm ▸ hx1) (λ h, h₁ x hx ▸ h ▸ hx1.symm ▸ (one_mul _).symm))) else by rw [← insert_erase hx, prod_insert (not_mem_erase _ _), ← insert_erase (mem_erase.2 ⟨h₂ x hx hx1, h₃ x hx⟩), prod_insert (not_mem_erase _ _), ih', mul_one, h₁ x hx]) @[to_additive] lemma prod_eq_one {f : α → β} {s : finset α} (h : ∀x∈s, f x = 1) : s.prod f = 1 := calc s.prod f = s.prod (λx, 1) : finset.prod_congr rfl h ... = 1 : finset.prod_const_one end comm_monoid attribute [to_additive] prod_hom lemma sum_smul [add_comm_monoid β] (s : finset α) (n : ℕ) (f : α → β) : s.sum (λ x, add_monoid.smul n (f x)) = add_monoid.smul n (s.sum f) := @prod_pow _ (multiplicative β) _ _ _ _ attribute [to_additive sum_smul] prod_pow @[simp] lemma sum_const [add_comm_monoid β] (b : β) : s.sum (λ a, b) = add_monoid.smul s.card b := @prod_const _ (multiplicative β) _ _ _ attribute [to_additive] prod_const lemma sum_range_succ' [add_comm_monoid β] (f : ℕ → β) : ∀ n : ℕ, (range (nat.succ n)).sum f = (range n).sum (f ∘ nat.succ) + f 0 := @prod_range_succ' (multiplicative β) _ _ attribute [to_additive] prod_range_succ' lemma sum_nat_cast [add_comm_monoid β] [has_one β] (s : finset α) (f : α → ℕ) : ↑(s.sum f) = s.sum (λa, f a : α → β) := (sum_hom _).symm lemma prod_nat_cast [comm_semiring β] (s : finset α) (f : α → ℕ) : ↑(s.prod f) = s.prod (λa, f a : α → β) := (prod_hom _).symm protected lemma sum_nat_coe_enat [decidable_eq α] (s : finset α) (f : α → ℕ) : s.sum (λ x, (f x : enat)) = (s.sum f : ℕ) := begin induction s using finset.induction with a s has ih h, { simp }, { simp [has, ih] } end theorem dvd_sum [comm_semiring α] {a : α} {s : finset β} {f : β → α} (h : ∀ x ∈ s, a ∣ f x) : a ∣ s.sum f := multiset.dvd_sum (λ y hy, by rcases multiset.mem_map.1 hy with ⟨x, hx, rfl⟩; exact h x hx) lemma le_sum_of_subadditive [add_comm_monoid α] [ordered_comm_monoid β] (f : α → β) (h_zero : f 0 = 0) (h_add : ∀x y, f (x + y) ≤ f x + f y) (s : finset γ) (g : γ → α) : f (s.sum g) ≤ s.sum (λc, f (g c)) := begin refine le_trans (multiset.le_sum_of_subadditive f h_zero h_add _) _, rw [multiset.map_map], refl end lemma abs_sum_le_sum_abs [discrete_linear_ordered_field α] {f : β → α} {s : finset β} : abs (s.sum f) ≤ s.sum (λa, abs (f a)) := le_sum_of_subadditive _ abs_zero abs_add s f section comm_group variables [comm_group β] @[simp, to_additive] lemma prod_inv_distrib : s.prod (λx, (f x)⁻¹) = (s.prod f)⁻¹ := prod_hom has_inv.inv end comm_group @[simp] theorem card_sigma {σ : α → Type*} (s : finset α) (t : Π a, finset (σ a)) : card (s.sigma t) = s.sum (λ a, card (t a)) := multiset.card_sigma _ _ lemma card_bind [decidable_eq β] {s : finset α} {t : α → finset β} (h : ∀ x ∈ s, ∀ y ∈ s, x ≠ y → disjoint (t x) (t y)) : (s.bind t).card = s.sum (λ u, card (t u)) := calc (s.bind t).card = (s.bind t).sum (λ _, 1) : by simp ... = s.sum (λ a, (t a).sum (λ _, 1)) : finset.sum_bind h ... = s.sum (λ u, card (t u)) : by simp lemma card_bind_le [decidable_eq β] {s : finset α} {t : α → finset β} : (s.bind t).card ≤ s.sum (λ a, (t a).card) := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (λ a s has ih, calc ((insert a s).bind t).card ≤ (t a).card + (s.bind t).card : by rw bind_insert; exact finset.card_union_le _ _ ... ≤ (insert a s).sum (λ a, card (t a)) : by rw sum_insert has; exact add_le_add_left ih _) theorem card_eq_sum_card_image [decidable_eq β] (f : α → β) (s : finset α) : s.card = (s.image f).sum (λ a, (s.filter (λ x, f x = a)).card) := by letI := classical.dec_eq α; exact calc s.card = ((s.image f).bind (λ a, s.filter (λ x, f x = a))).card : congr_arg _ (finset.ext.2 $ λ x, ⟨λ hs, mem_bind.2 ⟨f x, mem_image_of_mem _ hs, mem_filter.2 ⟨hs, rfl⟩⟩, λ h, let ⟨a, ha₁, ha₂⟩ := mem_bind.1 h in by convert filter_subset s ha₂⟩) ... = (s.image f).sum (λ a, (s.filter (λ x, f x = a)).card) : card_bind (by simp [disjoint_left, finset.ext] {contextual := tt}) lemma gsmul_sum [add_comm_group β] {f : α → β} {s : finset α} (z : ℤ) : gsmul z (s.sum f) = s.sum (λa, gsmul z (f a)) := (finset.sum_hom (gsmul z)).symm end finset namespace finset variables {s s₁ s₂ : finset α} {f g : α → β} {b : β} {a : α} @[simp] lemma sum_sub_distrib [add_comm_group β] : s.sum (λx, f x - g x) = s.sum f - s.sum g := sum_add_distrib.trans $ congr_arg _ sum_neg_distrib section semiring variables [semiring β] lemma sum_mul : s.sum f * b = s.sum (λx, f x * b) := (sum_hom (λx, x * b)).symm lemma mul_sum : b * s.sum f = s.sum (λx, b * f x) := (sum_hom (λx, b * x)).symm @[simp] lemma sum_mul_boole [decidable_eq α] (s : finset α) (f : α → β) (a : α) : s.sum (λ x, (f x * ite (a = x) 1 0)) = ite (a ∈ s) (f a) 0 := begin convert sum_ite_eq s a (f a), funext, split_ifs with h; simp [h], end @[simp] lemma sum_boole_mul [decidable_eq α] (s : finset α) (f : α → β) (a : α) : s.sum (λ x, (ite (a = x) 1 0) * f x) = ite (a ∈ s) (f a) 0 := begin convert sum_ite_eq s a (f a), funext, split_ifs with h; simp [h], end end semiring section comm_semiring variables [decidable_eq α] [comm_semiring β] lemma prod_eq_zero (ha : a ∈ s) (h : f a = 0) : s.prod f = 0 := calc s.prod f = (insert a (erase s a)).prod f : by rw insert_erase ha ... = 0 : by rw [prod_insert (not_mem_erase _ _), h, zero_mul] lemma prod_sum {δ : α → Type*} [∀a, decidable_eq (δ a)] {s : finset α} {t : Πa, finset (δ a)} {f : Πa, δ a → β} : s.prod (λa, (t a).sum (λb, f a b)) = (s.pi t).sum (λp, s.attach.prod (λx, f x.1 (p x.1 x.2))) := begin induction s using finset.induction with a s ha ih, { rw [pi_empty, sum_singleton], refl }, { have h₁ : ∀x ∈ t a, ∀y ∈ t a, ∀h : x ≠ y, disjoint (image (pi.cons s a x) (pi s t)) (image (pi.cons s a y) (pi s t)), { assume x hx y hy h, simp only [disjoint_iff_ne, mem_image], rintros _ ⟨p₂, hp, eq₂⟩ _ ⟨p₃, hp₃, eq₃⟩ eq, have : pi.cons s a x p₂ a (mem_insert_self _ _) = pi.cons s a y p₃ a (mem_insert_self _ _), { rw [eq₂, eq₃, eq] }, rw [pi.cons_same, pi.cons_same] at this, exact h this }, rw [prod_insert ha, pi_insert ha, ih, sum_mul, sum_bind h₁], refine sum_congr rfl (λ b _, _), have h₂ : ∀p₁∈pi s t, ∀p₂∈pi s t, pi.cons s a b p₁ = pi.cons s a b p₂ → p₁ = p₂, from assume p₁ h₁ p₂ h₂ eq, injective_pi_cons ha eq, rw [sum_image h₂, mul_sum], refine sum_congr rfl (λ g _, _), rw [attach_insert, prod_insert, prod_image], { simp only [pi.cons_same], congr', ext ⟨v, hv⟩, congr', exact (pi.cons_ne (by rintro rfl; exact ha hv)).symm }, { exact λ _ _ _ _, subtype.eq ∘ subtype.mk.inj }, { simp only [mem_image], rintro ⟨⟨_, hm⟩, _, rfl⟩, exact ha hm } } end end comm_semiring section integral_domain /- add integral_semi_domain to support nat and ennreal -/ variables [decidable_eq α] [integral_domain β] lemma prod_eq_zero_iff : s.prod f = 0 ↔ (∃a∈s, f a = 0) := finset.induction_on s ⟨not.elim one_ne_zero, λ ⟨_, H, _⟩, H.elim⟩ $ λ a s ha ih, by rw [prod_insert ha, mul_eq_zero_iff_eq_zero_or_eq_zero, bex_def, exists_mem_insert, ih, ← bex_def] end integral_domain section ordered_comm_monoid variables [decidable_eq α] [ordered_comm_monoid β] lemma sum_le_sum : (∀x∈s, f x ≤ g x) → s.sum f ≤ s.sum g := finset.induction_on s (λ _, le_refl _) $ assume a s ha ih h, have f a + s.sum f ≤ g a + s.sum g, from add_le_add' (h _ (mem_insert_self _ _)) (ih $ assume x hx, h _ $ mem_insert_of_mem hx), by simpa only [sum_insert ha] lemma sum_nonneg (h : ∀x∈s, 0 ≤ f x) : 0 ≤ s.sum f := le_trans (by rw [sum_const_zero]) (sum_le_sum h) lemma sum_nonpos (h : ∀x∈s, f x ≤ 0) : s.sum f ≤ 0 := le_trans (sum_le_sum h) (by rw [sum_const_zero]) lemma sum_le_sum_of_subset_of_nonneg (h : s₁ ⊆ s₂) (hf : ∀x∈s₂, x ∉ s₁ → 0 ≤ f x) : s₁.sum f ≤ s₂.sum f := calc s₁.sum f ≤ (s₂ \ s₁).sum f + s₁.sum f : le_add_of_nonneg_left' $ sum_nonneg $ by simpa only [mem_sdiff, and_imp] ... = (s₂ \ s₁ ∪ s₁).sum f : (sum_union sdiff_disjoint).symm ... = s₂.sum f : by rw [sdiff_union_of_subset h] lemma sum_eq_zero_iff_of_nonneg : (∀x∈s, 0 ≤ f x) → (s.sum f = 0 ↔ ∀x∈s, f x = 0) := finset.induction_on s (λ _, ⟨λ _ _, false.elim, λ _, rfl⟩) $ λ a s ha ih H, have ∀ x ∈ s, 0 ≤ f x, from λ _, H _ ∘ mem_insert_of_mem, by rw [sum_insert ha, add_eq_zero_iff' (H _ $ mem_insert_self _ _) (sum_nonneg this), forall_mem_insert, ih this] lemma sum_eq_zero_iff_of_nonpos : (∀x∈s, f x ≤ 0) → (s.sum f = 0 ↔ ∀x∈s, f x = 0) := @sum_eq_zero_iff_of_nonneg _ (order_dual β) _ _ _ _ lemma single_le_sum (hf : ∀x∈s, 0 ≤ f x) {a} (h : a ∈ s) : f a ≤ s.sum f := have (singleton a).sum f ≤ s.sum f, from sum_le_sum_of_subset_of_nonneg (λ x e, (mem_singleton.1 e).symm ▸ h) (λ x h _, hf x h), by rwa sum_singleton at this end ordered_comm_monoid section canonically_ordered_monoid variables [decidable_eq α] [canonically_ordered_monoid β] lemma sum_le_sum_of_subset (h : s₁ ⊆ s₂) : s₁.sum f ≤ s₂.sum f := sum_le_sum_of_subset_of_nonneg h $ assume x h₁ h₂, zero_le _ lemma sum_le_sum_of_ne_zero [@decidable_rel β (≤)] (h : ∀x∈s₁, f x ≠ 0 → x ∈ s₂) : s₁.sum f ≤ s₂.sum f := calc s₁.sum f = (s₁.filter (λx, f x = 0)).sum f + (s₁.filter (λx, f x ≠ 0)).sum f : by rw [←sum_union, filter_union_filter_neg_eq]; exact disjoint_filter.2 (assume _ _ h n_h, n_h h) ... ≤ s₂.sum f : add_le_of_nonpos_of_le' (sum_nonpos $ by simp only [mem_filter, and_imp]; exact λ _ _, le_of_eq) (sum_le_sum_of_subset $ by simpa only [subset_iff, mem_filter, and_imp]) end canonically_ordered_monoid section linear_ordered_comm_ring variables [decidable_eq α] [linear_ordered_comm_ring β] /- this is also true for a ordered commutative multiplicative monoid -/ lemma prod_nonneg {s : finset α} {f : α → β} (h0 : ∀(x ∈ s), 0 ≤ f x) : 0 ≤ s.prod f := begin induction s using finset.induction with a s has ih h, { simp [zero_le_one] }, { simp [has], apply mul_nonneg, apply h0 a (mem_insert_self a s), exact ih (λ x H, h0 x (mem_insert_of_mem H)) } end /- this is also true for a ordered commutative multiplicative monoid -/ lemma prod_pos {s : finset α} {f : α → β} (h0 : ∀(x ∈ s), 0 < f x) : 0 < s.prod f := begin induction s using finset.induction with a s has ih h, { simp [zero_lt_one] }, { simp [has], apply mul_pos, apply h0 a (mem_insert_self a s), exact ih (λ x H, h0 x (mem_insert_of_mem H)) } end /- this is also true for a ordered commutative multiplicative monoid -/ lemma prod_le_prod {s : finset α} {f g : α → β} (h0 : ∀(x ∈ s), 0 ≤ f x) (h1 : ∀(x ∈ s), f x ≤ g x) : s.prod f ≤ s.prod g := begin induction s using finset.induction with a s has ih h, { simp }, { simp [has], apply mul_le_mul, exact h1 a (mem_insert_self a s), apply ih (λ x H, h0 _ _) (λ x H, h1 _ _); exact (mem_insert_of_mem H), apply prod_nonneg (λ x H, h0 x (mem_insert_of_mem H)), apply le_trans (h0 a (mem_insert_self a s)) (h1 a (mem_insert_self a s)) } end end linear_ordered_comm_ring @[simp] lemma card_pi [decidable_eq α] {δ : α → Type*} (s : finset α) (t : Π a, finset (δ a)) : (s.pi t).card = s.prod (λ a, card (t a)) := multiset.card_pi _ _ theorem card_le_mul_card_image [decidable_eq β] {f : α → β} (s : finset α) (n : ℕ) (hn : ∀ a ∈ s.image f, (s.filter (λ x, f x = a)).card ≤ n) : s.card ≤ n * (s.image f).card := calc s.card = (s.image f).sum (λ a, (s.filter (λ x, f x = a)).card) : card_eq_sum_card_image _ _ ... ≤ (s.image f).sum (λ _, n) : sum_le_sum hn ... = _ : by simp [mul_comm] @[simp] lemma prod_Ico_id_eq_fact (n : ℕ) : (Ico 1 n.succ).prod (λ x, x) = nat.fact n := calc (Ico 1 n.succ).prod (λ x, x) = (range n).prod nat.succ : eq.symm (prod_bij (λ x _, nat.succ x) (λ a h₁, by simp [*, nat.lt_succ_iff, nat.succ_le_iff] at *) (by simp) (λ _ _ _ _, nat.succ_inj) (λ b h, have b.pred.succ = b, from nat.succ_pred_eq_of_pos $ by simp [nat.pos_iff_ne_zero, nat.succ_le_iff] at *; tauto, ⟨nat.pred b, mem_range.2 $ nat.lt_of_succ_lt_succ (by simp [*] at *), this.symm⟩)) ... = nat.fact n : by induction n; simp [*, range_succ] end finset namespace finset section gauss_sum /-- Gauss' summation formula -/ lemma sum_range_id_mul_two : ∀(n : ℕ), (finset.range n).sum (λi, i) * 2 = n * (n - 1) | 0 := rfl | 1 := rfl | ((n + 1) + 1) := begin rw [sum_range_succ, add_mul, sum_range_id_mul_two (n + 1), mul_comm, two_mul, nat.add_sub_cancel, nat.add_sub_cancel, mul_comm _ n], simp only [add_mul, one_mul, add_comm, add_assoc, add_left_comm] end /-- Gauss' summation formula -/ lemma sum_range_id (n : ℕ) : (finset.range n).sum (λi, i) = (n * (n - 1)) / 2 := by rw [← sum_range_id_mul_two n, nat.mul_div_cancel]; exact dec_trivial end gauss_sum lemma card_eq_sum_ones (s : finset α) : s.card = s.sum (λ _, 1) := by simp end finset section group open list variables [group α] [group β] @[to_additive] theorem is_group_hom.map_prod (f : α → β) [is_group_hom f] (l : list α) : f (prod l) = prod (map f l) := by induction l; simp only [*, is_mul_hom.map_mul f, is_group_hom.map_one f, prod_nil, prod_cons, map] theorem is_group_anti_hom.map_prod (f : α → β) [is_group_anti_hom f] (l : list α) : f (prod l) = prod (map f (reverse l)) := by induction l with hd tl ih; [exact is_group_anti_hom.map_one f, simp only [prod_cons, is_group_anti_hom.map_mul f, ih, reverse_cons, map_append, prod_append, map_singleton, prod_cons, prod_nil, mul_one]] theorem inv_prod : ∀ l : list α, (prod l)⁻¹ = prod (map (λ x, x⁻¹) (reverse l)) := λ l, @is_group_anti_hom.map_prod _ _ _ _ _ inv_is_group_anti_hom l -- TODO there is probably a cleaner proof of this end group section comm_group variables [comm_group α] [comm_group β] (f : α → β) [is_group_hom f] @[to_additive] lemma is_group_hom.map_multiset_prod (m : multiset α) : f m.prod = (m.map f).prod := quotient.induction_on m $ assume l, by simp [is_group_hom.map_prod f l] @[to_additive] lemma is_group_hom.map_finset_prod (g : γ → α) (s : finset γ) : f (s.prod g) = s.prod (f ∘ g) := show f (s.val.map g).prod = (s.val.map (f ∘ g)).prod, by rw [is_group_hom.map_multiset_prod f]; simp end comm_group @[to_additive is_add_group_hom_finset_sum] lemma is_group_hom_finset_prod {α β γ} [group α] [comm_group β] (s : finset γ) (f : γ → α → β) [∀c, is_group_hom (f c)] : is_group_hom (λa, s.prod (λc, f c a)) := { map_mul := assume a b, by simp only [λc, is_mul_hom.map_mul (f c), finset.prod_mul_distrib] } attribute [instance] is_group_hom_finset_prod is_add_group_hom_finset_sum namespace multiset variables [decidable_eq α] @[simp] lemma to_finset_sum_count_eq (s : multiset α) : s.to_finset.sum (λa, s.count a) = s.card := multiset.induction_on s rfl (assume a s ih, calc (to_finset (a :: s)).sum (λx, count x (a :: s)) = (to_finset (a :: s)).sum (λx, (if x = a then 1 else 0) + count x s) : finset.sum_congr rfl $ λ _ _, by split_ifs; [simp only [h, count_cons_self, nat.one_add], simp only [count_cons_of_ne h, zero_add]] ... = card (a :: s) : begin by_cases a ∈ s.to_finset, { have : (to_finset s).sum (λx, ite (x = a) 1 0) = (finset.singleton a).sum (λx, ite (x = a) 1 0), { apply (finset.sum_subset _ _).symm, { intros _ H, rwa mem_singleton.1 H }, { exact λ _ _ H, if_neg (mt finset.mem_singleton.2 H) } }, rw [to_finset_cons, finset.insert_eq_of_mem h, finset.sum_add_distrib, ih, this, finset.sum_singleton, if_pos rfl, add_comm, card_cons] }, { have ha : a ∉ s, by rwa mem_to_finset at h, have : (to_finset s).sum (λx, ite (x = a) 1 0) = (to_finset s).sum (λx, 0), from finset.sum_congr rfl (λ x hx, if_neg $ by rintro rfl; cc), rw [to_finset_cons, finset.sum_insert h, if_pos rfl, finset.sum_add_distrib, this, finset.sum_const_zero, ih, count_eq_zero_of_not_mem ha, zero_add, add_comm, card_cons] } end) end multiset namespace with_top open finset variables [decidable_eq α] /-- sum of finte numbers is still finite -/ lemma sum_lt_top [ordered_comm_monoid β] {s : finset α} {f : α → with_top β} : (∀a∈s, f a < ⊤) → s.sum f < ⊤ := finset.induction_on s (by { intro h, rw sum_empty, exact coe_lt_top _ }) (λa s ha ih h, begin rw [sum_insert ha, add_lt_top], split, { apply h, apply mem_insert_self }, { apply ih, intros a ha, apply h, apply mem_insert_of_mem ha } end) /-- sum of finte numbers is still finite -/ lemma sum_lt_top_iff [canonically_ordered_monoid β] {s : finset α} {f : α → with_top β} : s.sum f < ⊤ ↔ (∀a∈s, f a < ⊤) := iff.intro (λh a ha, lt_of_le_of_lt (single_le_sum (λa ha, zero_le _) ha) h) sum_lt_top end with_top
1aa8229c689b9b94a8c57e9bf1b245f4e74eec07
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/data/rat/sqrt.lean
e33db9ef02079f15d3c5700b2febf3e8650f82c5
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
1,165
lean
/- Copyright (c) 2019 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 data.rat.order import data.int.sqrt /-! # Square root on rational numbers This file defines the square root function on rational numbers, `rat.sqrt` and proves several theorems about it. -/ namespace rat /-- Square root function on rational numbers, defined by taking the (integer) square root of the numerator and the square root (on natural numbers) of the denominator. -/ @[pp_nodot] def sqrt (q : ℚ) : ℚ := rat.mk (int.sqrt q.num) (nat.sqrt q.denom) theorem sqrt_eq (q : ℚ) : rat.sqrt (q*q) = abs q := by rw [sqrt, mul_self_num, mul_self_denom, int.sqrt_eq, nat.sqrt_eq, abs_def] theorem exists_mul_self (x : ℚ) : (∃ q, q * q = x) ↔ rat.sqrt x * rat.sqrt x = x := ⟨λ ⟨n, hn⟩, by rw [← hn, sqrt_eq, abs_mul_abs_self], λ h, ⟨rat.sqrt x, h⟩⟩ theorem sqrt_nonneg (q : ℚ) : 0 ≤ rat.sqrt q := nonneg_iff_zero_le.1 $ (mk_nonneg _ $ int.coe_nat_pos.2 $ nat.pos_of_ne_zero $ λ H, nat.pos_iff_ne_zero.1 q.pos $ nat.sqrt_eq_zero.1 H).2 trivial end rat
a1a56fc2b34dd54f26b47b783639043082cfed98
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/src/Lean/Server/FileWorker/RequestHandling.lean
7de5b44ecb71bf7666f42c2dfb6b5b8ded78cf0f
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
tobiasgrosser/lean4
ce0fd9cca0feba1100656679bf41f0bffdbabb71
ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f
refs/heads/master
1,673,103,412,948
1,664,930,501,000
1,664,930,501,000
186,870,185
0
0
Apache-2.0
1,665,129,237,000
1,557,939,901,000
Lean
UTF-8
Lean
false
false
25,423
lean
/- Copyright (c) 2021 Wojciech Nawrocki. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki, Marc Huisinga -/ import Lean.DeclarationRange import Lean.Data.Json import Lean.Data.Lsp import Lean.Server.FileWorker.Utils import Lean.Server.Requests import Lean.Server.Completion import Lean.Server.References import Lean.Server.GoTo import Lean.Widget.InteractiveGoal import Lean.Widget.Diff namespace Lean.Server.FileWorker open Lsp open RequestM open Snapshots def handleCompletion (p : CompletionParams) : RequestM (RequestTask CompletionList) := do let doc ← readDoc let text := doc.meta.text let pos := text.lspPosToUtf8Pos p.position let caps := (← read).initParams.capabilities -- dbg_trace ">> handleCompletion invoked {pos}" -- NOTE: use `+ 1` since we sometimes want to consider invalid input technically after the command, -- such as a trailing dot after an option name. This shouldn't be a problem since any subsequent -- command starts with a keyword that (currently?) does not participate in completion. withWaitFindSnap doc (·.endPos + ' ' >= pos) (notFoundX := pure { items := #[], isIncomplete := true }) fun snap => do if let some r ← Completion.find? doc.meta.text pos snap.infoTree caps then return r return { items := #[ ], isIncomplete := true } open Elab in def handleHover (p : HoverParams) : RequestM (RequestTask (Option Hover)) := do let doc ← readDoc let text := doc.meta.text let mkHover (s : String) (r : String.Range) : Hover := { contents := { kind := MarkupKind.markdown value := s } range? := r.toLspRange text } let hoverPos := text.lspPosToUtf8Pos p.position withWaitFindSnap doc (fun s => s.endPos > hoverPos) (notFoundX := pure none) fun snap => do -- try to find parser docstring from syntax tree let stack? := snap.stx.findStack? (·.getRange?.any (·.contains hoverPos)) let stxDoc? ← match stack? with | some stack => stack.findSomeM? fun (stx, _) => do return (← findDocString? snap.env stx.getKind).map (·, stx.getRange?.get!) | none => pure none -- now try info tree if let some (ci, i) := snap.infoTree.hoverableInfoAt? hoverPos then if let some range := i.range? then -- prefer info tree if at least as specific as parser docstring if stxDoc?.all fun (_, stxRange) => stxRange.includes range then if let some hoverFmt ← i.fmtHover? ci then return mkHover (toString hoverFmt) range if let some (doc, range) := stxDoc? then return mkHover doc range return none open Elab GoToKind in def locationLinksOfInfo (kind : GoToKind) (ci : Elab.ContextInfo) (i : Elab.Info) (infoTree? : Option InfoTree := none) : RequestM (Array LocationLink) := do let rc ← read let doc ← readDoc let text := doc.meta.text let locationLinksFromDecl (i : Elab.Info) (n : Name) := locationLinksFromDecl rc.srcSearchPath doc.meta.uri n <| (·.toLspRange text) <$> i.range? let locationLinksFromBinder (i : Elab.Info) (id : FVarId) := do if let some i' := infoTree? >>= InfoTree.findInfo? fun | Info.ofTermInfo { isBinder := true, expr := Expr.fvar id' .., .. } => id' == id | _ => false then if let some r := i'.range? then let r := r.toLspRange text let ll : LocationLink := { originSelectionRange? := (·.toLspRange text) <$> i.range? targetUri := doc.meta.uri targetRange := r targetSelectionRange := r } return #[ll] return #[] let locationLinksFromImport (i : Elab.Info) := do let name := i.stx[2].getId if let some modUri ← documentUriFromModule rc.srcSearchPath name then let range := { start := ⟨0, 0⟩, «end» := ⟨0, 0⟩ : Range } let ll : LocationLink := { originSelectionRange? := (·.toLspRange text) <$> i.stx[2].getRange? (canonicalOnly := true) targetUri := modUri targetRange := range targetSelectionRange := range } return #[ll] return #[] if let Info.ofTermInfo ti := i then let mut expr := ti.expr if kind == type then expr ← ci.runMetaM i.lctx do return Expr.getAppFn (← instantiateMVars (← Meta.inferType expr)) match expr with | Expr.const n .. => return ← ci.runMetaM i.lctx <| locationLinksFromDecl i n | Expr.fvar id .. => return ← ci.runMetaM i.lctx <| locationLinksFromBinder i id | _ => pure () if let Info.ofFieldInfo fi := i then if kind == type then let expr ← ci.runMetaM i.lctx do instantiateMVars (← Meta.inferType fi.val) if let some n := expr.getAppFn.constName? then return ← ci.runMetaM i.lctx <| locationLinksFromDecl i n else return ← ci.runMetaM i.lctx <| locationLinksFromDecl i fi.projName if let Info.ofCommandInfo ⟨`import, _⟩ := i then if kind == definition || kind == declaration then return ← ci.runMetaM i.lctx <| locationLinksFromImport i -- If other go-tos fail, we try to show the elaborator or parser if let some ei := i.toElabInfo? then if kind == declaration && ci.env.contains ei.stx.getKind then return ← ci.runMetaM i.lctx <| locationLinksFromDecl i ei.stx.getKind if kind == definition && ci.env.contains ei.elaborator then return ← ci.runMetaM i.lctx <| locationLinksFromDecl i ei.elaborator return #[] open Elab GoToKind in def handleDefinition (kind : GoToKind) (p : TextDocumentPositionParams) : RequestM (RequestTask (Array LocationLink)) := do let doc ← readDoc let text := doc.meta.text let hoverPos := text.lspPosToUtf8Pos p.position withWaitFindSnap doc (fun s => s.endPos > hoverPos) (notFoundX := pure #[]) fun snap => do if let some (ci, i) := snap.infoTree.hoverableInfoAt? (includeStop := true /- #767 -/) hoverPos then locationLinksOfInfo kind ci i snap.infoTree else return #[] open RequestM in def getInteractiveGoals (p : Lsp.PlainGoalParams) : RequestM (RequestTask (Option Widget.InteractiveGoals)) := do let doc ← readDoc let text := doc.meta.text let hoverPos := text.lspPosToUtf8Pos p.position -- NOTE: use `>=` since the cursor can be *after* the input withWaitFindSnap doc (fun s => s.endPos >= hoverPos) (notFoundX := return none) fun snap => do if let rs@(_ :: _) := snap.infoTree.goalsAt? doc.meta.text hoverPos then let goals : List Widget.InteractiveGoals ← rs.mapM fun { ctxInfo := ci, tacticInfo := ti, useAfter := useAfter, .. } => do let ciAfter := { ci with mctx := ti.mctxAfter } let ci := if useAfter then ciAfter else { ci with mctx := ti.mctxBefore } -- compute the interactive goals let goals ← ci.runMetaM {} (do let goals := List.toArray <| if useAfter then ti.goalsAfter else ti.goalsBefore let goals ← goals.mapM (fun g => Meta.withPPForTacticGoal (Widget.goalToInteractive g)) return {goals} ) -- compute the goal diff let goals ← ciAfter.runMetaM {} (do try Widget.diffInteractiveGoals useAfter ti goals catch _ => -- fail silently, since this is just a bonus feature return goals ) return goals return some <| goals.foldl (· ++ ·) ∅ else return none open Elab in def handlePlainGoal (p : PlainGoalParams) : RequestM (RequestTask (Option PlainGoal)) := do let t ← getInteractiveGoals p return t.map <| Except.map <| Option.map <| fun {goals, ..} => if goals.isEmpty then { goals := #[], rendered := "no goals" } else let goalStrs := goals.map (toString ·.pretty) let goalBlocks := goalStrs.map fun goal => s!"```lean {goal} ```" let md := String.intercalate "\n---\n" goalBlocks.toList { goals := goalStrs, rendered := md } def getInteractiveTermGoal (p : Lsp.PlainTermGoalParams) : RequestM (RequestTask (Option Widget.InteractiveTermGoal)) := do let doc ← readDoc let text := doc.meta.text let hoverPos := text.lspPosToUtf8Pos p.position withWaitFindSnap doc (fun s => s.endPos > hoverPos) (notFoundX := pure none) fun snap => do if let some (ci, i@(Elab.Info.ofTermInfo ti)) := snap.infoTree.termGoalAt? hoverPos then let ty ← ci.runMetaM i.lctx do instantiateMVars <| ti.expectedType?.getD (← Meta.inferType ti.expr) -- for binders, hide the last hypothesis (the binder itself) let lctx' := if ti.isBinder then i.lctx.pop else i.lctx let goal ← ci.runMetaM lctx' do Widget.goalToInteractive (← Meta.mkFreshExprMVar ty).mvarId! let range := if let some r := i.range? then r.toLspRange text else ⟨p.position, p.position⟩ return some { goal with range } else return none def handlePlainTermGoal (p : PlainTermGoalParams) : RequestM (RequestTask (Option PlainTermGoal)) := do let t ← getInteractiveTermGoal p return t.map <| Except.map <| Option.map fun goal => { goal := toString goal.toInteractiveGoal.pretty range := goal.range } partial def handleDocumentHighlight (p : DocumentHighlightParams) : RequestM (RequestTask (Array DocumentHighlight)) := do let doc ← readDoc let text := doc.meta.text let pos := text.lspPosToUtf8Pos p.position let rec highlightReturn? (doRange? : Option Range) : Syntax → Option DocumentHighlight | `(doElem|return%$i $e) => Id.run do if let some range := i.getRange? then if range.contains pos then return some { range := doRange?.getD (range.toLspRange text), kind? := DocumentHighlightKind.text } highlightReturn? doRange? e | `(do%$i $elems) => highlightReturn? (i.getRange?.get!.toLspRange text) elems | stx => stx.getArgs.findSome? (highlightReturn? doRange?) let highlightRefs? (snaps : Array Snapshot) : Option (Array DocumentHighlight) := Id.run do let trees := snaps.map (·.infoTree) let refs : Lsp.ModuleRefs := findModuleRefs text trees let mut ranges := #[] for ident in ← refs.findAt p.position do if let some info ← refs.find? ident then if let some definition := info.definition then ranges := ranges.push definition ranges := ranges.append info.usages if ranges.isEmpty then return none some <| ranges.map ({ range := ·, kind? := DocumentHighlightKind.text }) withWaitFindSnap doc (fun s => s.endPos > pos) (notFoundX := pure #[]) fun snap => do let (snaps, _) ← doc.cmdSnaps.getFinishedPrefix if let some his := highlightRefs? snaps.toArray then return his if let some hi := highlightReturn? none snap.stx then return #[hi] return #[] structure NamespaceEntry where /-- The list of the name components introduced by this namespace command, in reverse order so that `end` will peel them off from the front. -/ name : List Name stx : Syntax selection : Syntax prevSiblings : Array DocumentSymbol def NamespaceEntry.finish (text : FileMap) (syms : Array DocumentSymbol) (endStx : Option Syntax) : NamespaceEntry → Array DocumentSymbol | { name, stx, selection, prevSiblings, .. } => -- we can assume that commands always have at least one position (see `parseCommand`) let range := match endStx with | some endStx => (mkNullNode #[stx, endStx]).getRange?.get! | none => { stx.getRange?.get! with stop := text.source.endPos } let name := name.foldr (fun x y => y ++ x) Name.anonymous prevSiblings.push <| DocumentSymbol.mk { -- anonymous sections are represented by `«»` name components name := if name == `«» then "<section>" else name.toString kind := .namespace range := range.toLspRange text selectionRange := selection.getRange?.getD range |>.toLspRange text children? := syms } open Parser.Command in partial def handleDocumentSymbol (_ : DocumentSymbolParams) : RequestM (RequestTask DocumentSymbolResult) := do let doc ← readDoc -- bad: we have to wait on elaboration of the entire file before we can report document symbols let t := doc.cmdSnaps.waitAll mapTask t fun (snaps, _) => do let mut stxs := snaps.map (·.stx) return { syms := toDocumentSymbols doc.meta.text stxs #[] [] } where toDocumentSymbols (text : FileMap) (stxs : List Syntax) (syms : Array DocumentSymbol) (stack : List NamespaceEntry) : Array DocumentSymbol := match stxs with | [] => stack.foldl (fun syms entry => entry.finish text syms none) syms | stx::stxs => match stx with | `(namespace $id) => let entry := { name := id.getId.componentsRev, stx, selection := id, prevSiblings := syms } toDocumentSymbols text stxs #[] (entry :: stack) | `(section $(id)?) => let name := id.map (·.getId.componentsRev) |>.getD [`«»] let entry := { name, stx, selection := id.map (·.raw) |>.getD stx, prevSiblings := syms } toDocumentSymbols text stxs #[] (entry :: stack) | `(end $(id)?) => let rec popStack n syms | [] => toDocumentSymbols text stxs syms [] | entry :: stack => if entry.name.length == n then let syms := entry.finish text syms stx toDocumentSymbols text stxs syms stack else if entry.name.length > n then let syms := { entry with name := entry.name.take n, prevSiblings := #[] }.finish text syms stx toDocumentSymbols text stxs syms ({ entry with name := entry.name.drop n } :: stack) else let syms := entry.finish text syms stx popStack (n - entry.name.length) syms stack popStack (id.map (·.getId.getNumParts) |>.getD 1) syms stack | _ => Id.run do unless stx.isOfKind ``Lean.Parser.Command.declaration do return toDocumentSymbols text stxs syms stack if let some stxRange := stx.getRange? then let (name, selection) := match stx with | `($_:declModifiers $_:attrKind instance $[$np:namedPrio]? $[$id$[.{$ls,*}]?]? $sig:declSig $_) => ((·.getId.toString) <$> id |>.getD s!"instance {sig.raw.reprint.getD ""}", id.map (·.raw) |>.getD sig) | _ => match stx.getArg 1 |>.getArg 1 with | `(declId|$id$[.{$ls,*}]?) => (id.raw.getId.toString, id) | _ => let stx10 : Syntax := (stx.getArg 1).getArg 0 -- TODO: stx[1][0] times out (stx10.isIdOrAtom?.getD "<unknown>", stx10) if let some selRange := selection.getRange? then let sym := DocumentSymbol.mk { name := name kind := SymbolKind.method range := stxRange.toLspRange text selectionRange := selRange.toLspRange text } return toDocumentSymbols text stxs (syms.push sym) stack toDocumentSymbols text stxs syms stack def noHighlightKinds : Array SyntaxNodeKind := #[ -- usually have special highlighting by the client ``Lean.Parser.Term.sorry, ``Lean.Parser.Term.type, ``Lean.Parser.Term.prop, -- not really keywords `antiquotName, ``Lean.Parser.Command.docComment, ``Lean.Parser.Command.moduleDoc] structure SemanticTokensContext where beginPos : String.Pos endPos : String.Pos text : FileMap snap : Snapshot structure SemanticTokensState where data : Array Nat lastLspPos : Lsp.Position partial def handleSemanticTokens (beginPos endPos : String.Pos) : RequestM (RequestTask SemanticTokens) := do let doc ← readDoc let text := doc.meta.text let t := doc.cmdSnaps.waitAll (·.beginPos < endPos) mapTask t fun (snaps, _) => StateT.run' (s := { data := #[], lastLspPos := ⟨0, 0⟩ : SemanticTokensState }) do for s in snaps do if s.endPos <= beginPos then continue ReaderT.run (r := SemanticTokensContext.mk beginPos endPos text s) <| go s.stx return { data := (← get).data } where go (stx : Syntax) := do match stx with | `($e.$id:ident) => go e; addToken id SemanticTokenType.property -- indistinguishable from next pattern --| `(level|$id:ident) => addToken id SemanticTokenType.variable | `($id:ident) => highlightId id | _ => if !noHighlightKinds.contains stx.getKind then highlightKeyword stx if stx.isOfKind choiceKind then go stx[0] else stx.getArgs.forM go highlightId (stx : Syntax) : ReaderT SemanticTokensContext (StateT SemanticTokensState RequestM) _ := do if let some range := stx.getRange? then let mut lastPos := range.start for ti in (← read).snap.infoTree.deepestNodes (fun | _, i@(Elab.Info.ofTermInfo ti), _ => match i.pos? with | some ipos => if range.contains ipos then some ti else none | _ => none | _, _, _ => none) do let pos := ti.stx.getPos?.get! -- avoid reporting same position twice; the info node can occur multiple times if -- e.g. the term is elaborated multiple times if pos < lastPos then continue if let Expr.fvar fvarId .. := ti.expr then if let some localDecl := ti.lctx.find? fvarId then -- Recall that `isAuxDecl` is an auxiliary declaration used to elaborate a recursive definition. if localDecl.isAuxDecl then if ti.isBinder then addToken ti.stx SemanticTokenType.function else addToken ti.stx SemanticTokenType.variable else if ti.stx.getPos?.get! > lastPos then -- any info after the start position: must be projection notation addToken ti.stx SemanticTokenType.property lastPos := ti.stx.getPos?.get! highlightKeyword stx := do if let Syntax.atom _ val := stx then if (val.length > 0 && val.front.isAlpha) || -- Support for keywords of the form `#<alpha>...` (val.length > 1 && val.front == '#' && (val.get ⟨1⟩).isAlpha) then addToken stx SemanticTokenType.keyword addToken stx type := do let ⟨beginPos, endPos, text, _⟩ ← read if let (some pos, some tailPos) := (stx.getPos?, stx.getTailPos?) then if beginPos <= pos && pos < endPos then let lspPos := (← get).lastLspPos let lspPos' := text.utf8PosToLspPos pos let deltaLine := lspPos'.line - lspPos.line let deltaStart := lspPos'.character - (if lspPos'.line == lspPos.line then lspPos.character else 0) let length := (text.utf8PosToLspPos tailPos).character - lspPos'.character let tokenType := type.toNat let tokenModifiers := 0 modify fun st => { data := st.data ++ #[deltaLine, deltaStart, length, tokenType, tokenModifiers] lastLspPos := lspPos' } def handleSemanticTokensFull (_ : SemanticTokensParams) : RequestM (RequestTask SemanticTokens) := do handleSemanticTokens 0 ⟨1 <<< 16⟩ def handleSemanticTokensRange (p : SemanticTokensRangeParams) : RequestM (RequestTask SemanticTokens) := do let doc ← readDoc let text := doc.meta.text let beginPos := text.lspPosToUtf8Pos p.range.start let endPos := text.lspPosToUtf8Pos p.range.end handleSemanticTokens beginPos endPos partial def handleFoldingRange (_ : FoldingRangeParams) : RequestM (RequestTask (Array FoldingRange)) := do let doc ← readDoc let t := doc.cmdSnaps.waitAll mapTask t fun (snaps, _) => do let stxs := snaps.map (·.stx) let (_, ranges) ← StateT.run (addRanges doc.meta.text [] stxs) #[] return ranges where isImport stx := stx.isOfKind ``Lean.Parser.Module.header || stx.isOfKind ``Lean.Parser.Command.open addRanges (text : FileMap) sections | [] => do if let (_, start)::rest := sections then addRange text FoldingRangeKind.region start text.source.endPos addRanges text rest [] | stx::stxs => match stx with | `(namespace $id) => addRanges text ((id.getId.getNumParts, stx.getPos?)::sections) stxs | `(section $(id)?) => addRanges text ((id.map (·.getId.getNumParts) |>.getD 1, stx.getPos?)::sections) stxs | `(end $(id)?) => do let rec popRanges n sections := do if let (size, start)::rest := sections then if size == n then addRange text FoldingRangeKind.region start stx.getTailPos? addRanges text rest stxs else if size > n then -- we don't add a range here because vscode doesn't like -- multiple folding regions with the same start line addRanges text ((size - n, start)::rest) stxs else addRange text FoldingRangeKind.region start stx.getTailPos? popRanges (n - size) rest else addRanges text sections stxs popRanges (id.map (·.getId.getNumParts) |>.getD 1) sections | `(mutual $body* end) => do addRangeFromSyntax text FoldingRangeKind.region stx addRanges text [] body.raw.toList addRanges text sections stxs | _ => do if isImport stx then let (imports, stxs) := stxs.span isImport let last := imports.getLastD stx addRange text FoldingRangeKind.imports stx.getPos? last.getTailPos? addRanges text sections stxs else addCommandRange text stx addRanges text sections stxs addCommandRange text stx := match stx.getKind with | `Lean.Parser.Command.moduleDoc => addRangeFromSyntax text FoldingRangeKind.comment stx | ``Lean.Parser.Command.declaration => do -- When visiting a declaration, attempt to fold the doc comment -- separately to the main definition. -- We never fold other modifiers, such as annotations. if let `($dm:declModifiers $decl) := stx then if let some comment := dm.raw[0].getOptional? then addRangeFromSyntax text FoldingRangeKind.comment comment addRangeFromSyntax text FoldingRangeKind.region decl else addRangeFromSyntax text FoldingRangeKind.region stx | _ => addRangeFromSyntax text FoldingRangeKind.region stx addRangeFromSyntax (text : FileMap) kind stx := addRange text kind stx.getPos? stx.getTailPos? addRange (text : FileMap) kind start? stop? := do if let (some startP, some endP) := (start?, stop?) then let startP := text.utf8PosToLspPos startP let endP := text.utf8PosToLspPos endP if startP.line != endP.line then modify fun st => st.push { startLine := startP.line endLine := endP.line kind? := some kind } partial def handleWaitForDiagnostics (p : WaitForDiagnosticsParams) : RequestM (RequestTask WaitForDiagnostics) := do let rec waitLoop : RequestM EditableDocument := do let doc ← readDoc if p.version ≤ doc.meta.version then return doc else IO.sleep 50 waitLoop let t ← RequestM.asTask waitLoop RequestM.bindTask t fun doc? => do let doc ← liftExcept doc? let t₁ := doc.cmdSnaps.waitAll return t₁.map fun _ => pure WaitForDiagnostics.mk builtin_initialize registerLspRequestHandler "textDocument/waitForDiagnostics" WaitForDiagnosticsParams WaitForDiagnostics handleWaitForDiagnostics registerLspRequestHandler "textDocument/completion" CompletionParams CompletionList handleCompletion registerLspRequestHandler "textDocument/hover" HoverParams (Option Hover) handleHover registerLspRequestHandler "textDocument/declaration" TextDocumentPositionParams (Array LocationLink) (handleDefinition GoToKind.declaration) registerLspRequestHandler "textDocument/definition" TextDocumentPositionParams (Array LocationLink) (handleDefinition GoToKind.definition) registerLspRequestHandler "textDocument/typeDefinition" TextDocumentPositionParams (Array LocationLink) (handleDefinition GoToKind.type) registerLspRequestHandler "textDocument/documentHighlight" DocumentHighlightParams DocumentHighlightResult handleDocumentHighlight registerLspRequestHandler "textDocument/documentSymbol" DocumentSymbolParams DocumentSymbolResult handleDocumentSymbol registerLspRequestHandler "textDocument/semanticTokens/full" SemanticTokensParams SemanticTokens handleSemanticTokensFull registerLspRequestHandler "textDocument/semanticTokens/range" SemanticTokensRangeParams SemanticTokens handleSemanticTokensRange registerLspRequestHandler "textDocument/foldingRange" FoldingRangeParams (Array FoldingRange) handleFoldingRange registerLspRequestHandler "$/lean/plainGoal" PlainGoalParams (Option PlainGoal) handlePlainGoal registerLspRequestHandler "$/lean/plainTermGoal" PlainTermGoalParams (Option PlainTermGoal) handlePlainTermGoal end Lean.Server.FileWorker
16744a0e5f9903fe6cbad36ebdb1f413ebbed860
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/data/polynomial/degree/definitions.lean
f8d1c695c5469002ddde847dea1535286b5f37eb
[ "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
49,003
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import data.nat.with_bot import data.polynomial.induction import data.polynomial.monomial /-! # Theory of univariate polynomials The definitions include `degree`, `monic`, `leading_coeff` Results include - `degree_mul` : The degree of the product is the sum of degrees - `leading_coeff_add_of_degree_eq` and `leading_coeff_add_of_degree_lt` : The leading_coefficient of a sum is determined by the leading coefficients and degrees -/ noncomputable theory open finsupp finset open_locale big_operators classical polynomial namespace polynomial universes u v variables {R : Type u} {S : Type v} {a b c d : R} {n m : ℕ} section semiring variables [semiring R] {p q r : R[X]} /-- `degree p` is the degree of the polynomial `p`, i.e. the largest `X`-exponent in `p`. `degree p = some n` when `p ≠ 0` and `n` is the highest power of `X` that appears in `p`, otherwise `degree 0 = ⊥`. -/ def degree (p : R[X]) : with_bot ℕ := p.support.max lemma degree_lt_wf : well_founded (λp q : R[X], degree p < degree q) := inv_image.wf degree (with_bot.well_founded_lt nat.lt_wf) instance : has_well_founded R[X] := ⟨_, degree_lt_wf⟩ /-- `nat_degree p` forces `degree p` to ℕ, by defining nat_degree 0 = 0. -/ def nat_degree (p : R[X]) : ℕ := (degree p).get_or_else 0 /-- `leading_coeff p` gives the coefficient of the highest power of `X` in `p`-/ def leading_coeff (p : R[X]) : R := coeff p (nat_degree p) /-- a polynomial is `monic` if its leading coefficient is 1 -/ def monic (p : R[X]) := leading_coeff p = (1 : R) @[nontriviality] lemma monic_of_subsingleton [subsingleton R] (p : R[X]) : monic p := subsingleton.elim _ _ lemma monic.def : monic p ↔ leading_coeff p = 1 := iff.rfl instance monic.decidable [decidable_eq R] : decidable (monic p) := by unfold monic; apply_instance @[simp] lemma monic.leading_coeff {p : R[X]} (hp : p.monic) : leading_coeff p = 1 := hp lemma monic.coeff_nat_degree {p : R[X]} (hp : p.monic) : p.coeff p.nat_degree = 1 := hp @[simp] lemma degree_zero : degree (0 : R[X]) = ⊥ := rfl @[simp] lemma nat_degree_zero : nat_degree (0 : R[X]) = 0 := rfl @[simp] lemma coeff_nat_degree : coeff p (nat_degree p) = leading_coeff p := rfl lemma degree_eq_bot : degree p = ⊥ ↔ p = 0 := ⟨λ h, support_eq_empty.1 (finset.max_eq_bot.1 h), λ h, h.symm ▸ rfl⟩ @[nontriviality] lemma degree_of_subsingleton [subsingleton R] : degree p = ⊥ := by rw [subsingleton.elim p 0, degree_zero] @[nontriviality] lemma nat_degree_of_subsingleton [subsingleton R] : nat_degree p = 0 := by rw [subsingleton.elim p 0, nat_degree_zero] lemma degree_eq_nat_degree (hp : p ≠ 0) : degree p = (nat_degree p : with_bot ℕ) := let ⟨n, hn⟩ := not_forall.1 (mt option.eq_none_iff_forall_not_mem.2 (mt degree_eq_bot.1 hp)) in have hn : degree p = some n := not_not.1 hn, by rw [nat_degree, hn]; refl lemma degree_eq_iff_nat_degree_eq {p : R[X]} {n : ℕ} (hp : p ≠ 0) : p.degree = n ↔ p.nat_degree = n := by rw [degree_eq_nat_degree hp, with_bot.coe_eq_coe] lemma degree_eq_iff_nat_degree_eq_of_pos {p : R[X]} {n : ℕ} (hn : 0 < n) : p.degree = n ↔ p.nat_degree = n := begin split, { intro H, rwa ← degree_eq_iff_nat_degree_eq, rintro rfl, rw degree_zero at H, exact option.no_confusion H }, { intro H, rwa degree_eq_iff_nat_degree_eq, rintro rfl, rw nat_degree_zero at H, rw H at hn, exact lt_irrefl _ hn } end lemma nat_degree_eq_of_degree_eq_some {p : R[X]} {n : ℕ} (h : degree p = n) : nat_degree p = n := have hp0 : p ≠ 0, from λ hp0, by rw hp0 at h; exact option.no_confusion h, option.some_inj.1 $ show (nat_degree p : with_bot ℕ) = n, by rwa [← degree_eq_nat_degree hp0] @[simp] lemma degree_le_nat_degree : degree p ≤ nat_degree p := with_bot.gi_get_or_else_bot.gc.le_u_l _ lemma nat_degree_eq_of_degree_eq [semiring S] {q : S[X]} (h : degree p = degree q) : nat_degree p = nat_degree q := by unfold nat_degree; rw h lemma le_degree_of_ne_zero (h : coeff p n ≠ 0) : (n : with_bot ℕ) ≤ degree p := show @has_le.le (with_bot ℕ) _ (some n : with_bot ℕ) (p.support.sup some : with_bot ℕ), from finset.le_sup (mem_support_iff.2 h) lemma le_nat_degree_of_ne_zero (h : coeff p n ≠ 0) : n ≤ nat_degree p := begin rw [← with_bot.coe_le_coe, ← degree_eq_nat_degree], exact le_degree_of_ne_zero h, { assume h, subst h, exact h rfl } end lemma le_nat_degree_of_mem_supp (a : ℕ) : a ∈ p.support → a ≤ nat_degree p:= le_nat_degree_of_ne_zero ∘ mem_support_iff.mp lemma degree_eq_of_le_of_coeff_ne_zero (pn : p.degree ≤ n) (p1 : p.coeff n ≠ 0) : p.degree = n := pn.antisymm (le_degree_of_ne_zero p1) lemma nat_degree_eq_of_le_of_coeff_ne_zero (pn : p.nat_degree ≤ n) (p1 : p.coeff n ≠ 0) : p.nat_degree = n := pn.antisymm (le_nat_degree_of_ne_zero p1) lemma degree_mono [semiring S] {f : R[X]} {g : S[X]} (h : f.support ⊆ g.support) : f.degree ≤ g.degree := finset.sup_mono h lemma supp_subset_range (h : nat_degree p < m) : p.support ⊆ finset.range m := λ n hn, mem_range.2 $ (le_nat_degree_of_mem_supp _ hn).trans_lt h lemma supp_subset_range_nat_degree_succ : p.support ⊆ finset.range (nat_degree p + 1) := supp_subset_range (nat.lt_succ_self _) lemma degree_le_degree (h : coeff q (nat_degree p) ≠ 0) : degree p ≤ degree q := begin by_cases hp : p = 0, { rw hp, exact bot_le }, { rw degree_eq_nat_degree hp, exact le_degree_of_ne_zero h } end lemma degree_ne_of_nat_degree_ne {n : ℕ} : p.nat_degree ≠ n → degree p ≠ n := mt $ λ h, by rw [nat_degree, h, option.get_or_else_coe] theorem nat_degree_le_iff_degree_le {n : ℕ} : nat_degree p ≤ n ↔ degree p ≤ n := with_bot.get_or_else_bot_le_iff lemma nat_degree_lt_iff_degree_lt (hp : p ≠ 0) : p.nat_degree < n ↔ p.degree < ↑n := with_bot.get_or_else_bot_lt_iff $ degree_eq_bot.not.mpr hp alias nat_degree_le_iff_degree_le ↔ .. lemma nat_degree_le_nat_degree [semiring S] {q : S[X]} (hpq : p.degree ≤ q.degree) : p.nat_degree ≤ q.nat_degree := with_bot.gi_get_or_else_bot.gc.monotone_l hpq @[simp] lemma degree_C (ha : a ≠ 0) : degree (C a) = (0 : with_bot ℕ) := by rw [degree, ← monomial_zero_left, support_monomial 0 ha, max_eq_sup_coe, sup_singleton, with_bot.coe_zero] lemma degree_C_le : degree (C a) ≤ 0 := begin by_cases h : a = 0, { rw [h, C_0], exact bot_le }, { rw [degree_C h], exact le_rfl } end lemma degree_C_lt : degree (C a) < 1 := degree_C_le.trans_lt $ with_bot.coe_lt_coe.mpr zero_lt_one lemma degree_one_le : degree (1 : R[X]) ≤ (0 : with_bot ℕ) := by rw [← C_1]; exact degree_C_le @[simp] lemma nat_degree_C (a : R) : nat_degree (C a) = 0 := begin by_cases ha : a = 0, { have : C a = 0, { rw [ha, C_0] }, rw [nat_degree, degree_eq_bot.2 this], refl }, { rw [nat_degree, degree_C ha], refl } end @[simp] lemma nat_degree_one : nat_degree (1 : R[X]) = 0 := nat_degree_C 1 @[simp] lemma nat_degree_nat_cast (n : ℕ) : nat_degree (n : R[X]) = 0 := by simp only [←C_eq_nat_cast, nat_degree_C] @[simp] lemma degree_monomial (n : ℕ) (ha : a ≠ 0) : degree (monomial n a) = n := by rw [degree, support_monomial n ha]; refl @[simp] lemma degree_C_mul_X_pow (n : ℕ) (ha : a ≠ 0) : degree (C a * X ^ n) = n := by rw [← monomial_eq_C_mul_X, degree_monomial n ha] lemma degree_C_mul_X (ha : a ≠ 0) : degree (C a * X) = 1 := by simpa only [pow_one] using degree_C_mul_X_pow 1 ha lemma degree_monomial_le (n : ℕ) (a : R) : degree (monomial n a) ≤ n := if h : a = 0 then by rw [h, (monomial n).map_zero]; exact bot_le else le_of_eq (degree_monomial n h) lemma degree_C_mul_X_pow_le (n : ℕ) (a : R) : degree (C a * X ^ n) ≤ n := by { rw C_mul_X_pow_eq_monomial, apply degree_monomial_le } lemma degree_C_mul_X_le (a : R) : degree (C a * X) ≤ 1 := by simpa only [pow_one] using degree_C_mul_X_pow_le 1 a @[simp] lemma nat_degree_C_mul_X_pow (n : ℕ) (a : R) (ha : a ≠ 0) : nat_degree (C a * X ^ n) = n := nat_degree_eq_of_degree_eq_some (degree_C_mul_X_pow n ha) @[simp] lemma nat_degree_C_mul_X (a : R) (ha : a ≠ 0) : nat_degree (C a * X) = 1 := by simpa only [pow_one] using nat_degree_C_mul_X_pow 1 a ha @[simp] lemma nat_degree_monomial [decidable_eq R] (i : ℕ) (r : R) : nat_degree (monomial i r) = if r = 0 then 0 else i := begin split_ifs with hr, { simp [hr] }, { rw [← C_mul_X_pow_eq_monomial, nat_degree_C_mul_X_pow i r hr] } end lemma nat_degree_monomial_le (a : R) {m : ℕ} : (monomial m a).nat_degree ≤ m := begin rw polynomial.nat_degree_monomial, split_ifs, exacts [nat.zero_le _, rfl.le], end lemma nat_degree_monomial_eq (i : ℕ) {r : R} (r0 : r ≠ 0) : (monomial i r).nat_degree = i := eq.trans (nat_degree_monomial _ _) (if_neg r0) lemma coeff_eq_zero_of_degree_lt (h : degree p < n) : coeff p n = 0 := not_not.1 (mt le_degree_of_ne_zero (not_le_of_gt h)) lemma coeff_eq_zero_of_nat_degree_lt {p : R[X]} {n : ℕ} (h : p.nat_degree < n) : p.coeff n = 0 := begin apply coeff_eq_zero_of_degree_lt, by_cases hp : p = 0, { subst hp, exact with_bot.bot_lt_coe n }, { rwa [degree_eq_nat_degree hp, with_bot.coe_lt_coe] } end @[simp] lemma coeff_nat_degree_succ_eq_zero {p : R[X]} : p.coeff (p.nat_degree + 1) = 0 := coeff_eq_zero_of_nat_degree_lt (lt_add_one _) -- We need the explicit `decidable` argument here because an exotic one shows up in a moment! lemma ite_le_nat_degree_coeff (p : R[X]) (n : ℕ) (I : decidable (n < 1 + nat_degree p)) : @ite _ (n < 1 + nat_degree p) I (coeff p n) 0 = coeff p n := begin split_ifs, { refl }, { exact (coeff_eq_zero_of_nat_degree_lt (not_le.1 (λ w, h (nat.lt_one_add_iff.2 w)))).symm, } end lemma as_sum_support (p : R[X]) : p = ∑ i in p.support, monomial i (p.coeff i) := (sum_monomial_eq p).symm lemma as_sum_support_C_mul_X_pow (p : R[X]) : p = ∑ i in p.support, C (p.coeff i) * X^i := trans p.as_sum_support $ by simp only [C_mul_X_pow_eq_monomial] /-- We can reexpress a sum over `p.support` as a sum over `range n`, for any `n` satisfying `p.nat_degree < n`. -/ lemma sum_over_range' [add_comm_monoid S] (p : R[X]) {f : ℕ → R → S} (h : ∀ n, f n 0 = 0) (n : ℕ) (w : p.nat_degree < n) : p.sum f = ∑ (a : ℕ) in range n, f a (coeff p a) := begin rcases p, have := supp_subset_range w, simp only [polynomial.sum, support, coeff, nat_degree, degree] at ⊢ this, exact finsupp.sum_of_support_subset _ this _ (λ n hn, h n) end /-- We can reexpress a sum over `p.support` as a sum over `range (p.nat_degree + 1)`. -/ lemma sum_over_range [add_comm_monoid S] (p : R[X]) {f : ℕ → R → S} (h : ∀ n, f n 0 = 0) : p.sum f = ∑ (a : ℕ) in range (p.nat_degree + 1), f a (coeff p a) := sum_over_range' p h (p.nat_degree + 1) (lt_add_one _) -- TODO this is essentially a duplicate of `sum_over_range`, and should be removed. lemma sum_fin [add_comm_monoid S] (f : ℕ → R → S) (hf : ∀ i, f i 0 = 0) {n : ℕ} {p : R[X]} (hn : p.degree < n) : ∑ (i : fin n), f i (p.coeff i) = p.sum f := begin by_cases hp : p = 0, { rw [hp, sum_zero_index, finset.sum_eq_zero], intros i _, exact hf i }, rw [sum_over_range' _ hf n ((nat_degree_lt_iff_degree_lt hp).mpr hn), fin.sum_univ_eq_sum_range (λ i, f i (p.coeff i))], end lemma as_sum_range' (p : R[X]) (n : ℕ) (w : p.nat_degree < n) : p = ∑ i in range n, monomial i (coeff p i) := p.sum_monomial_eq.symm.trans $ p.sum_over_range' monomial_zero_right _ w lemma as_sum_range (p : R[X]) : p = ∑ i in range (p.nat_degree + 1), monomial i (coeff p i) := p.sum_monomial_eq.symm.trans $ p.sum_over_range $ monomial_zero_right lemma as_sum_range_C_mul_X_pow (p : R[X]) : p = ∑ i in range (p.nat_degree + 1), C (coeff p i) * X ^ i := p.as_sum_range.trans $ by simp only [C_mul_X_pow_eq_monomial] lemma coeff_ne_zero_of_eq_degree (hn : degree p = n) : coeff p n ≠ 0 := λ h, mem_support_iff.mp (mem_of_max hn) h lemma eq_X_add_C_of_degree_le_one (h : degree p ≤ 1) : p = C (p.coeff 1) * X + C (p.coeff 0) := ext (λ n, nat.cases_on n (by simp) (λ n, nat.cases_on n (by simp [coeff_C]) (λ m, have degree p < m.succ.succ, from lt_of_le_of_lt h dec_trivial, by simp [coeff_eq_zero_of_degree_lt this, coeff_C, nat.succ_ne_zero, coeff_X, nat.succ_inj', @eq_comm ℕ 0]))) lemma eq_X_add_C_of_degree_eq_one (h : degree p = 1) : p = C (p.leading_coeff) * X + C (p.coeff 0) := (eq_X_add_C_of_degree_le_one (show degree p ≤ 1, from h ▸ le_rfl)).trans (by simp [leading_coeff, nat_degree_eq_of_degree_eq_some h]) lemma eq_X_add_C_of_nat_degree_le_one (h : nat_degree p ≤ 1) : p = C (p.coeff 1) * X + C (p.coeff 0) := eq_X_add_C_of_degree_le_one $ degree_le_of_nat_degree_le h lemma exists_eq_X_add_C_of_nat_degree_le_one (h : nat_degree p ≤ 1) : ∃ a b, p = C a * X + C b := ⟨p.coeff 1, p.coeff 0, eq_X_add_C_of_nat_degree_le_one h⟩ theorem degree_X_pow_le (n : ℕ) : degree (X^n : R[X]) ≤ n := by simpa only [C_1, one_mul] using degree_C_mul_X_pow_le n (1:R) theorem degree_X_le : degree (X : R[X]) ≤ 1 := degree_monomial_le _ _ lemma nat_degree_X_le : (X : R[X]).nat_degree ≤ 1 := nat_degree_le_of_degree_le degree_X_le lemma mem_support_C_mul_X_pow {n a : ℕ} {c : R} (h : a ∈ (C c * X ^ n).support) : a = n := mem_singleton.1 $ support_C_mul_X_pow' n c h lemma card_support_C_mul_X_pow_le_one {c : R} {n : ℕ} : (C c * X ^ n).support.card ≤ 1 := begin rw ← card_singleton n, apply card_le_of_subset (support_C_mul_X_pow' n c), end lemma card_supp_le_succ_nat_degree (p : R[X]) : p.support.card ≤ p.nat_degree + 1 := begin rw ← finset.card_range (p.nat_degree + 1), exact finset.card_le_of_subset supp_subset_range_nat_degree_succ, end lemma le_degree_of_mem_supp (a : ℕ) : a ∈ p.support → ↑a ≤ degree p := le_degree_of_ne_zero ∘ mem_support_iff.mp lemma nonempty_support_iff : p.support.nonempty ↔ p ≠ 0 := by rw [ne.def, nonempty_iff_ne_empty, ne.def, ← support_eq_empty] end semiring section nonzero_semiring variables [semiring R] [nontrivial R] {p q : R[X]} @[simp] lemma degree_one : degree (1 : R[X]) = (0 : with_bot ℕ) := degree_C (show (1 : R) ≠ 0, from zero_ne_one.symm) @[simp] lemma degree_X : degree (X : R[X]) = 1 := degree_monomial _ one_ne_zero @[simp] lemma nat_degree_X : (X : R[X]).nat_degree = 1 := nat_degree_eq_of_degree_eq_some degree_X end nonzero_semiring section ring variables [ring R] lemma coeff_mul_X_sub_C {p : R[X]} {r : R} {a : ℕ} : coeff (p * (X - C r)) (a + 1) = coeff p a - coeff p (a + 1) * r := by simp [mul_sub] @[simp] lemma degree_neg (p : R[X]) : degree (-p) = degree p := by unfold degree; rw support_neg @[simp] lemma nat_degree_neg (p : R[X]) : nat_degree (-p) = nat_degree p := by simp [nat_degree] @[simp] lemma nat_degree_int_cast (n : ℤ) : nat_degree (n : R[X]) = 0 := by simp only [←C_eq_int_cast, nat_degree_C] @[simp] lemma leading_coeff_neg (p : R[X]) : (-p).leading_coeff = -p.leading_coeff := by rw [leading_coeff, leading_coeff, nat_degree_neg, coeff_neg] end ring section semiring variables [semiring R] /-- The second-highest coefficient, or 0 for constants -/ def next_coeff (p : R[X]) : R := if p.nat_degree = 0 then 0 else p.coeff (p.nat_degree - 1) @[simp] lemma next_coeff_C_eq_zero (c : R) : next_coeff (C c) = 0 := by { rw next_coeff, simp } lemma next_coeff_of_pos_nat_degree (p : R[X]) (hp : 0 < p.nat_degree) : next_coeff p = p.coeff (p.nat_degree - 1) := by { rw [next_coeff, if_neg], contrapose! hp, simpa } variables {p q : R[X]} {ι : Type*} lemma coeff_nat_degree_eq_zero_of_degree_lt (h : degree p < degree q) : coeff p (nat_degree q) = 0 := coeff_eq_zero_of_degree_lt (lt_of_lt_of_le h degree_le_nat_degree) lemma ne_zero_of_degree_gt {n : with_bot ℕ} (h : n < degree p) : p ≠ 0 := mt degree_eq_bot.2 (ne.symm (ne_of_lt (lt_of_le_of_lt bot_le h))) lemma ne_zero_of_degree_ge_degree (hpq : p.degree ≤ q.degree) (hp : p ≠ 0) : q ≠ 0 := polynomial.ne_zero_of_degree_gt (lt_of_lt_of_le (bot_lt_iff_ne_bot.mpr (by rwa [ne.def, polynomial.degree_eq_bot])) hpq : q.degree > ⊥) lemma ne_zero_of_nat_degree_gt {n : ℕ} (h : n < nat_degree p) : p ≠ 0 := λ H, by simpa [H, nat.not_lt_zero] using h lemma degree_lt_degree (h : nat_degree p < nat_degree q) : degree p < degree q := begin by_cases hp : p = 0, { simp [hp], rw bot_lt_iff_ne_bot, intro hq, simpa [hp, degree_eq_bot.mp hq, lt_irrefl] using h }, { rw [degree_eq_nat_degree hp, degree_eq_nat_degree $ ne_zero_of_nat_degree_gt h], exact_mod_cast h } end lemma nat_degree_lt_nat_degree_iff (hp : p ≠ 0) : nat_degree p < nat_degree q ↔ degree p < degree q := ⟨degree_lt_degree, begin intro h, have hq : q ≠ 0 := ne_zero_of_degree_gt h, rw [degree_eq_nat_degree hp, degree_eq_nat_degree hq] at h, exact_mod_cast h end⟩ lemma eq_C_of_degree_le_zero (h : degree p ≤ 0) : p = C (coeff p 0) := begin ext (_|n), { simp }, rw [coeff_C, if_neg (nat.succ_ne_zero _), coeff_eq_zero_of_degree_lt], exact h.trans_lt (with_bot.some_lt_some.2 n.succ_pos), end lemma eq_C_of_degree_eq_zero (h : degree p = 0) : p = C (coeff p 0) := eq_C_of_degree_le_zero (h ▸ le_rfl) lemma degree_le_zero_iff : degree p ≤ 0 ↔ p = C (coeff p 0) := ⟨eq_C_of_degree_le_zero, λ h, h.symm ▸ degree_C_le⟩ lemma degree_add_le (p q : R[X]) : degree (p + q) ≤ max (degree p) (degree q) := calc degree (p + q) = ((p + q).support).sup some : rfl ... ≤ (p.support ∪ q.support).sup some : sup_mono support_add ... = p.support.sup some ⊔ q.support.sup some : sup_union lemma degree_add_le_of_degree_le {p q : R[X]} {n : ℕ} (hp : degree p ≤ n) (hq : degree q ≤ n) : degree (p + q) ≤ n := (degree_add_le p q).trans $ max_le hp hq lemma nat_degree_add_le (p q : R[X]) : nat_degree (p + q) ≤ max (nat_degree p) (nat_degree q) := begin cases le_max_iff.1 (degree_add_le p q); simp [nat_degree_le_nat_degree h] end lemma nat_degree_add_le_of_degree_le {p q : R[X]} {n : ℕ} (hp : nat_degree p ≤ n) (hq : nat_degree q ≤ n) : nat_degree (p + q) ≤ n := (nat_degree_add_le p q).trans $ max_le hp hq @[simp] lemma leading_coeff_zero : leading_coeff (0 : R[X]) = 0 := rfl @[simp] lemma leading_coeff_eq_zero : leading_coeff p = 0 ↔ p = 0 := ⟨λ h, by_contradiction $ λ hp, mt mem_support_iff.1 (not_not.2 h) (mem_of_max (degree_eq_nat_degree hp)), λ h, h.symm ▸ leading_coeff_zero⟩ lemma leading_coeff_ne_zero : leading_coeff p ≠ 0 ↔ p ≠ 0 := by rw [ne.def, leading_coeff_eq_zero] lemma leading_coeff_eq_zero_iff_deg_eq_bot : leading_coeff p = 0 ↔ degree p = ⊥ := by rw [leading_coeff_eq_zero, degree_eq_bot] lemma nat_degree_mem_support_of_nonzero (H : p ≠ 0) : p.nat_degree ∈ p.support := by { rw mem_support_iff, exact (not_congr leading_coeff_eq_zero).mpr H } lemma nat_degree_eq_support_max' (h : p ≠ 0) : p.nat_degree = p.support.max' (nonempty_support_iff.mpr h) := (le_max' _ _ $ nat_degree_mem_support_of_nonzero h).antisymm $ max'_le _ _ _ le_nat_degree_of_mem_supp lemma nat_degree_C_mul_X_pow_le (a : R) (n : ℕ) : nat_degree (C a * X ^ n) ≤ n := nat_degree_le_iff_degree_le.2 $ degree_C_mul_X_pow_le _ _ lemma degree_add_eq_left_of_degree_lt (h : degree q < degree p) : degree (p + q) = degree p := le_antisymm (max_eq_left_of_lt h ▸ degree_add_le _ _) $ degree_le_degree $ begin rw [coeff_add, coeff_nat_degree_eq_zero_of_degree_lt h, add_zero], exact mt leading_coeff_eq_zero.1 (ne_zero_of_degree_gt h) end lemma degree_add_eq_right_of_degree_lt (h : degree p < degree q) : degree (p + q) = degree q := by rw [add_comm, degree_add_eq_left_of_degree_lt h] lemma nat_degree_add_eq_left_of_nat_degree_lt (h : nat_degree q < nat_degree p) : nat_degree (p + q) = nat_degree p := nat_degree_eq_of_degree_eq (degree_add_eq_left_of_degree_lt (degree_lt_degree h)) lemma nat_degree_add_eq_right_of_nat_degree_lt (h : nat_degree p < nat_degree q) : nat_degree (p + q) = nat_degree q := nat_degree_eq_of_degree_eq (degree_add_eq_right_of_degree_lt (degree_lt_degree h)) lemma degree_add_C (hp : 0 < degree p) : degree (p + C a) = degree p := add_comm (C a) p ▸ degree_add_eq_right_of_degree_lt $ lt_of_le_of_lt degree_C_le hp lemma degree_add_eq_of_leading_coeff_add_ne_zero (h : leading_coeff p + leading_coeff q ≠ 0) : degree (p + q) = max p.degree q.degree := le_antisymm (degree_add_le _ _) $ match lt_trichotomy (degree p) (degree q) with | or.inl hlt := by rw [degree_add_eq_right_of_degree_lt hlt, max_eq_right_of_lt hlt]; exact le_rfl | or.inr (or.inl heq) := le_of_not_gt $ assume hlt : max (degree p) (degree q) > degree (p + q), h $ show leading_coeff p + leading_coeff q = 0, begin rw [heq, max_self] at hlt, rw [leading_coeff, leading_coeff, nat_degree_eq_of_degree_eq heq, ← coeff_add], exact coeff_nat_degree_eq_zero_of_degree_lt hlt end | or.inr (or.inr hlt) := by rw [degree_add_eq_left_of_degree_lt hlt, max_eq_left_of_lt hlt]; exact le_rfl end lemma degree_erase_le (p : R[X]) (n : ℕ) : degree (p.erase n) ≤ degree p := by { rcases p, simp only [erase, degree, coeff, support], convert sup_mono (erase_subset _ _) } lemma degree_erase_lt (hp : p ≠ 0) : degree (p.erase (nat_degree p)) < degree p := begin apply lt_of_le_of_ne (degree_erase_le _ _), rw [degree_eq_nat_degree hp, degree, support_erase], exact λ h, not_mem_erase _ _ (mem_of_max h), end lemma degree_update_le (p : R[X]) (n : ℕ) (a : R) : degree (p.update n a) ≤ max (degree p) n := begin rw [degree, support_update], split_ifs, { exact (finset.max_mono (erase_subset _ _)).trans (le_max_left _ _) }, { rw [max_insert, max_comm], exact le_rfl }, end lemma degree_sum_le (s : finset ι) (f : ι → R[X]) : degree (∑ i in s, f i) ≤ s.sup (λ b, degree (f b)) := finset.induction_on s (by simp only [sum_empty, sup_empty, degree_zero, le_refl]) $ assume a s has ih, calc degree (∑ i in insert a s, f i) ≤ max (degree (f a)) (degree (∑ i in s, f i)) : by rw sum_insert has; exact degree_add_le _ _ ... ≤ _ : by rw [sup_insert, sup_eq_max]; exact max_le_max le_rfl ih lemma degree_mul_le (p q : R[X]) : degree (p * q) ≤ degree p + degree q := calc degree (p * q) ≤ (p.support).sup (λi, degree (sum q (λj a, C (coeff p i * a) * X ^ (i + j)))) : begin simp only [monomial_eq_C_mul_X.symm], convert degree_sum_le _ _, exact mul_eq_sum_sum end ... ≤ p.support.sup (λi, q.support.sup (λj, degree (C (coeff p i * coeff q j) * X ^ (i + j)))) : finset.sup_mono_fun (assume i hi, degree_sum_le _ _) ... ≤ degree p + degree q : begin refine finset.sup_le (λ a ha, finset.sup_le (λ b hb, le_trans (degree_C_mul_X_pow_le _ _) _)), rw [with_bot.coe_add], rw mem_support_iff at ha hb, exact add_le_add (le_degree_of_ne_zero ha) (le_degree_of_ne_zero hb) end lemma degree_pow_le (p : R[X]) : ∀ (n : ℕ), degree (p ^ n) ≤ n • (degree p) | 0 := by rw [pow_zero, zero_nsmul]; exact degree_one_le | (n+1) := calc degree (p ^ (n + 1)) ≤ degree p + degree (p ^ n) : by rw pow_succ; exact degree_mul_le _ _ ... ≤ _ : by rw succ_nsmul; exact add_le_add le_rfl (degree_pow_le _) @[simp] lemma leading_coeff_monomial (a : R) (n : ℕ) : leading_coeff (monomial n a) = a := begin by_cases ha : a = 0, { simp only [ha, (monomial n).map_zero, leading_coeff_zero] }, { rw [leading_coeff, nat_degree_monomial, if_neg ha, coeff_monomial], simp } end lemma leading_coeff_C_mul_X_pow (a : R) (n : ℕ) : leading_coeff (C a * X ^ n) = a := by rw [C_mul_X_pow_eq_monomial, leading_coeff_monomial] lemma leading_coeff_C_mul_X (a : R) : leading_coeff (C a * X) = a := by simpa only [pow_one] using leading_coeff_C_mul_X_pow a 1 @[simp] lemma leading_coeff_C (a : R) : leading_coeff (C a) = a := leading_coeff_monomial a 0 @[simp] lemma leading_coeff_X_pow (n : ℕ) : leading_coeff ((X : R[X]) ^ n) = 1 := by simpa only [C_1, one_mul] using leading_coeff_C_mul_X_pow (1 : R) n @[simp] lemma leading_coeff_X : leading_coeff (X : R[X]) = 1 := by simpa only [pow_one] using @leading_coeff_X_pow R _ 1 @[simp] lemma monic_X_pow (n : ℕ) : monic (X ^ n : R[X]) := leading_coeff_X_pow n @[simp] lemma monic_X : monic (X : R[X]) := leading_coeff_X @[simp] lemma leading_coeff_one : leading_coeff (1 : R[X]) = 1 := leading_coeff_C 1 @[simp] lemma monic_one : monic (1 : R[X]) := leading_coeff_C _ lemma monic.ne_zero {R : Type*} [semiring R] [nontrivial R] {p : R[X]} (hp : p.monic) : p ≠ 0 := by { rintro rfl, simpa [monic] using hp } lemma monic.ne_zero_of_ne (h : (0:R) ≠ 1) {p : R[X]} (hp : p.monic) : p ≠ 0 := by { nontriviality R, exact hp.ne_zero } lemma monic_of_nat_degree_le_of_coeff_eq_one (n : ℕ) (pn : p.nat_degree ≤ n) (p1 : p.coeff n = 1) : monic p := begin nontriviality, refine (congr_arg _ $ nat_degree_eq_of_le_of_coeff_ne_zero pn _).trans p1, exact ne_of_eq_of_ne p1 one_ne_zero, end lemma monic_of_degree_le_of_coeff_eq_one (n : ℕ) (pn : p.degree ≤ n) (p1 : p.coeff n = 1) : monic p := monic_of_nat_degree_le_of_coeff_eq_one n (nat_degree_le_of_degree_le pn) p1 lemma monic.ne_zero_of_polynomial_ne {r} (hp : monic p) (hne : q ≠ r) : p ≠ 0 := by { haveI := nontrivial.of_polynomial_ne hne, exact hp.ne_zero } lemma leading_coeff_add_of_degree_lt (h : degree p < degree q) : leading_coeff (p + q) = leading_coeff q := have coeff p (nat_degree q) = 0, from coeff_nat_degree_eq_zero_of_degree_lt h, by simp only [leading_coeff, nat_degree_eq_of_degree_eq (degree_add_eq_right_of_degree_lt h), this, coeff_add, zero_add] lemma leading_coeff_add_of_degree_eq (h : degree p = degree q) (hlc : leading_coeff p + leading_coeff q ≠ 0) : leading_coeff (p + q) = leading_coeff p + leading_coeff q := have nat_degree (p + q) = nat_degree p, by apply nat_degree_eq_of_degree_eq; rw [degree_add_eq_of_leading_coeff_add_ne_zero hlc, h, max_self], by simp only [leading_coeff, this, nat_degree_eq_of_degree_eq h, coeff_add] @[simp] lemma coeff_mul_degree_add_degree (p q : R[X]) : coeff (p * q) (nat_degree p + nat_degree q) = leading_coeff p * leading_coeff q := calc coeff (p * q) (nat_degree p + nat_degree q) = ∑ x in nat.antidiagonal (nat_degree p + nat_degree q), coeff p x.1 * coeff q x.2 : coeff_mul _ _ _ ... = coeff p (nat_degree p) * coeff q (nat_degree q) : begin refine finset.sum_eq_single (nat_degree p, nat_degree q) _ _, { rintro ⟨i,j⟩ h₁ h₂, rw nat.mem_antidiagonal at h₁, by_cases H : nat_degree p < i, { rw [coeff_eq_zero_of_degree_lt (lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 H)), zero_mul] }, { rw not_lt_iff_eq_or_lt at H, cases H, { subst H, rw add_left_cancel_iff at h₁, dsimp at h₁, subst h₁, exfalso, exact h₂ rfl }, { suffices : nat_degree q < j, { rw [coeff_eq_zero_of_degree_lt (lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 this)), mul_zero] }, { by_contra H', rw not_lt at H', exact ne_of_lt (nat.lt_of_lt_of_le (nat.add_lt_add_right H j) (nat.add_le_add_left H' _)) h₁ } } } }, { intro H, exfalso, apply H, rw nat.mem_antidiagonal } end lemma degree_mul' (h : leading_coeff p * leading_coeff q ≠ 0) : degree (p * q) = degree p + degree q := have hp : p ≠ 0 := by refine mt _ h; exact λ hp, by rw [hp, leading_coeff_zero, zero_mul], have hq : q ≠ 0 := by refine mt _ h; exact λ hq, by rw [hq, leading_coeff_zero, mul_zero], le_antisymm (degree_mul_le _ _) begin rw [degree_eq_nat_degree hp, degree_eq_nat_degree hq], refine le_degree_of_ne_zero _, rwa coeff_mul_degree_add_degree end lemma monic.degree_mul (hq : monic q) : degree (p * q) = degree p + degree q := if hp : p = 0 then by simp [hp] else degree_mul' $ by rwa [hq.leading_coeff, mul_one, ne.def, leading_coeff_eq_zero] lemma nat_degree_mul' (h : leading_coeff p * leading_coeff q ≠ 0) : nat_degree (p * q) = nat_degree p + nat_degree q := have hp : p ≠ 0 := mt leading_coeff_eq_zero.2 (λ h₁, h $ by rw [h₁, zero_mul]), have hq : q ≠ 0 := mt leading_coeff_eq_zero.2 (λ h₁, h $ by rw [h₁, mul_zero]), nat_degree_eq_of_degree_eq_some $ by rw [degree_mul' h, with_bot.coe_add, degree_eq_nat_degree hp, degree_eq_nat_degree hq] lemma leading_coeff_mul' (h : leading_coeff p * leading_coeff q ≠ 0) : leading_coeff (p * q) = leading_coeff p * leading_coeff q := begin unfold leading_coeff, rw [nat_degree_mul' h, coeff_mul_degree_add_degree], refl end lemma monomial_nat_degree_leading_coeff_eq_self (h : p.support.card ≤ 1) : monomial p.nat_degree p.leading_coeff = p := begin rcases card_support_le_one_iff_monomial.1 h with ⟨n, a, rfl⟩, by_cases ha : a = 0; simp [ha] end lemma C_mul_X_pow_eq_self (h : p.support.card ≤ 1) : C p.leading_coeff * X^p.nat_degree = p := by rw [C_mul_X_pow_eq_monomial, monomial_nat_degree_leading_coeff_eq_self h] lemma leading_coeff_pow' : leading_coeff p ^ n ≠ 0 → leading_coeff (p ^ n) = leading_coeff p ^ n := nat.rec_on n (by simp) $ λ n ih h, have h₁ : leading_coeff p ^ n ≠ 0 := λ h₁, h $ by rw [pow_succ, h₁, mul_zero], have h₂ : leading_coeff p * leading_coeff (p ^ n) ≠ 0 := by rwa [pow_succ, ← ih h₁] at h, by rw [pow_succ, pow_succ, leading_coeff_mul' h₂, ih h₁] lemma degree_pow' : ∀ {n : ℕ}, leading_coeff p ^ n ≠ 0 → degree (p ^ n) = n • (degree p) | 0 := λ h, by rw [pow_zero, ← C_1] at *; rw [degree_C h, zero_nsmul] | (n+1) := λ h, have h₁ : leading_coeff p ^ n ≠ 0 := λ h₁, h $ by rw [pow_succ, h₁, mul_zero], have h₂ : leading_coeff p * leading_coeff (p ^ n) ≠ 0 := by rwa [pow_succ, ← leading_coeff_pow' h₁] at h, by rw [pow_succ, degree_mul' h₂, succ_nsmul, degree_pow' h₁] lemma nat_degree_pow' {n : ℕ} (h : leading_coeff p ^ n ≠ 0) : nat_degree (p ^ n) = n * nat_degree p := if hp0 : p = 0 then if hn0 : n = 0 then by simp * else by rw [hp0, zero_pow (nat.pos_of_ne_zero hn0)]; simp else have hpn : p ^ n ≠ 0, from λ hpn0, have h1 : _ := h, by rw [← leading_coeff_pow' h1, hpn0, leading_coeff_zero] at h; exact h rfl, option.some_inj.1 $ show (nat_degree (p ^ n) : with_bot ℕ) = (n * nat_degree p : ℕ), by rw [← degree_eq_nat_degree hpn, degree_pow' h, degree_eq_nat_degree hp0, ← with_bot.coe_nsmul]; simp theorem leading_coeff_monic_mul {p q : R[X]} (hp : monic p) : leading_coeff (p * q) = leading_coeff q := begin rcases eq_or_ne q 0 with rfl|H, { simp }, { rw [leading_coeff_mul', hp.leading_coeff, one_mul], rwa [hp.leading_coeff, one_mul, ne.def, leading_coeff_eq_zero] } end theorem leading_coeff_mul_monic {p q : R[X]} (hq : monic q) : leading_coeff (p * q) = leading_coeff p := decidable.by_cases (λ H : leading_coeff p = 0, by rw [H, leading_coeff_eq_zero.1 H, zero_mul, leading_coeff_zero]) (λ H : leading_coeff p ≠ 0, by rw [leading_coeff_mul', hq.leading_coeff, mul_one]; rwa [hq.leading_coeff, mul_one]) @[simp] theorem leading_coeff_mul_X_pow {p : R[X]} {n : ℕ} : leading_coeff (p * X ^ n) = leading_coeff p := leading_coeff_mul_monic (monic_X_pow n) @[simp] theorem leading_coeff_mul_X {p : R[X]} : leading_coeff (p * X) = leading_coeff p := leading_coeff_mul_monic monic_X lemma nat_degree_mul_le {p q : R[X]} : nat_degree (p * q) ≤ nat_degree p + nat_degree q := begin apply nat_degree_le_of_degree_le, apply le_trans (degree_mul_le p q), rw with_bot.coe_add, refine add_le_add _ _; apply degree_le_nat_degree, end lemma nat_degree_pow_le {p : R[X]} {n : ℕ} : (p ^ n).nat_degree ≤ n * p.nat_degree := begin induction n with i hi, { simp }, { rw [pow_succ, nat.succ_mul, add_comm], apply le_trans nat_degree_mul_le, exact add_le_add_left hi _ } end @[simp] lemma coeff_pow_mul_nat_degree (p : R[X]) (n : ℕ) : (p ^ n).coeff (n * p.nat_degree) = p.leading_coeff ^ n := begin induction n with i hi, { simp }, { rw [pow_succ', pow_succ', nat.succ_mul], by_cases hp1 : p.leading_coeff ^ i = 0, { rw [hp1, zero_mul], by_cases hp2 : p ^ i = 0, { rw [hp2, zero_mul, coeff_zero] }, { apply coeff_eq_zero_of_nat_degree_lt, have h1 : (p ^ i).nat_degree < i * p.nat_degree, { apply lt_of_le_of_ne nat_degree_pow_le (λ h, hp2 _), rw [←h, hp1] at hi, exact leading_coeff_eq_zero.mp hi }, calc (p ^ i * p).nat_degree ≤ (p ^ i).nat_degree + p.nat_degree : nat_degree_mul_le ... < i * p.nat_degree + p.nat_degree : add_lt_add_right h1 _ } }, { rw [←nat_degree_pow' hp1, ←leading_coeff_pow' hp1], exact coeff_mul_degree_add_degree _ _ } } end lemma zero_le_degree_iff {p : R[X]} : 0 ≤ degree p ↔ p ≠ 0 := by rw [ne.def, ← degree_eq_bot]; cases degree p; exact dec_trivial lemma degree_nonneg_iff_ne_zero : 0 ≤ degree p ↔ p ≠ 0 := by simp [degree_eq_bot, ← not_lt] lemma nat_degree_eq_zero_iff_degree_le_zero : p.nat_degree = 0 ↔ p.degree ≤ 0 := by rw [← nonpos_iff_eq_zero, nat_degree_le_iff_degree_le, with_bot.coe_zero] theorem degree_le_iff_coeff_zero (f : R[X]) (n : with_bot ℕ) : degree f ≤ n ↔ ∀ m : ℕ, n < m → coeff f m = 0 := by simp only [degree, finset.max, finset.sup_le_iff, mem_support_iff, ne.def, ← not_le, not_imp_comm] theorem degree_lt_iff_coeff_zero (f : R[X]) (n : ℕ) : degree f < n ↔ ∀ m : ℕ, n ≤ m → coeff f m = 0 := begin refine ⟨λ hf m hm, coeff_eq_zero_of_degree_lt (lt_of_lt_of_le hf (with_bot.coe_le_coe.2 hm)), _⟩, simp only [degree, finset.sup_lt_iff (with_bot.bot_lt_coe n), mem_support_iff, with_bot.some_eq_coe, with_bot.coe_lt_coe, ← @not_le ℕ, max_eq_sup_coe], exact λ h m, mt (h m), end lemma degree_smul_le (a : R) (p : R[X]) : degree (a • p) ≤ degree p := begin apply (degree_le_iff_coeff_zero _ _).2 (λ m hm, _), rw degree_lt_iff_coeff_zero at hm, simp [hm m le_rfl], end lemma nat_degree_smul_le (a : R) (p : R[X]) : nat_degree (a • p) ≤ nat_degree p := nat_degree_le_nat_degree (degree_smul_le a p) lemma degree_lt_degree_mul_X (hp : p ≠ 0) : p.degree < (p * X).degree := by haveI := nontrivial.of_polynomial_ne hp; exact have leading_coeff p * leading_coeff X ≠ 0, by simpa, by erw [degree_mul' this, degree_eq_nat_degree hp, degree_X, ← with_bot.coe_one, ← with_bot.coe_add, with_bot.coe_lt_coe]; exact nat.lt_succ_self _ lemma nat_degree_pos_iff_degree_pos : 0 < nat_degree p ↔ 0 < degree p := lt_iff_lt_of_le_iff_le nat_degree_le_iff_degree_le lemma eq_C_of_nat_degree_le_zero (h : nat_degree p ≤ 0) : p = C (coeff p 0) := eq_C_of_degree_le_zero $ degree_le_of_nat_degree_le h lemma eq_C_of_nat_degree_eq_zero (h : nat_degree p = 0) : p = C (coeff p 0) := eq_C_of_nat_degree_le_zero h.le lemma ne_zero_of_coe_le_degree (hdeg : ↑n ≤ p.degree) : p ≠ 0 := degree_nonneg_iff_ne_zero.mp $ (with_bot.coe_le_coe.mpr n.zero_le).trans hdeg lemma le_nat_degree_of_coe_le_degree (hdeg : ↑n ≤ p.degree) : n ≤ p.nat_degree := with_bot.coe_le_coe.mp ((degree_eq_nat_degree $ ne_zero_of_coe_le_degree hdeg) ▸ hdeg) lemma degree_sum_fin_lt {n : ℕ} (f : fin n → R) : degree (∑ i : fin n, C (f i) * X ^ (i : ℕ)) < n := begin haveI : is_commutative (with_bot ℕ) max := ⟨max_comm⟩, haveI : is_associative (with_bot ℕ) max := ⟨max_assoc⟩, calc (∑ i, C (f i) * X ^ (i : ℕ)).degree ≤ finset.univ.fold (⊔) ⊥ (λ i, (C (f i) * X ^ (i : ℕ)).degree) : degree_sum_le _ _ ... = finset.univ.fold max ⊥ (λ i, (C (f i) * X ^ (i : ℕ)).degree) : rfl ... < n : (finset.fold_max_lt (n : with_bot ℕ)).mpr ⟨with_bot.bot_lt_coe _, _⟩, rintros ⟨i, hi⟩ -, calc (C (f ⟨i, hi⟩) * X ^ i).degree ≤ (C _).degree + (X ^ i).degree : degree_mul_le _ _ ... ≤ 0 + i : add_le_add degree_C_le (degree_X_pow_le i) ... = i : zero_add _ ... < n : with_bot.some_lt_some.mpr hi, end lemma degree_linear_le : degree (C a * X + C b) ≤ 1 := degree_add_le_of_degree_le (degree_C_mul_X_le _) $ le_trans degree_C_le nat.with_bot.coe_nonneg lemma degree_linear_lt : degree (C a * X + C b) < 2 := degree_linear_le.trans_lt $ with_bot.coe_lt_coe.mpr one_lt_two lemma degree_C_lt_degree_C_mul_X (ha : a ≠ 0) : degree (C b) < degree (C a * X) := by simpa only [degree_C_mul_X ha] using degree_C_lt @[simp] lemma degree_linear (ha : a ≠ 0) : degree (C a * X + C b) = 1 := by rw [degree_add_eq_left_of_degree_lt $ degree_C_lt_degree_C_mul_X ha, degree_C_mul_X ha] lemma nat_degree_linear_le : nat_degree (C a * X + C b) ≤ 1 := nat_degree_le_of_degree_le degree_linear_le @[simp] lemma nat_degree_linear (ha : a ≠ 0) : nat_degree (C a * X + C b) = 1 := nat_degree_eq_of_degree_eq_some $ degree_linear ha @[simp] lemma leading_coeff_linear (ha : a ≠ 0): leading_coeff (C a * X + C b) = a := by rw [add_comm, leading_coeff_add_of_degree_lt (degree_C_lt_degree_C_mul_X ha), leading_coeff_C_mul_X] lemma degree_quadratic_le : degree (C a * X ^ 2 + C b * X + C c) ≤ 2 := by simpa only [add_assoc] using degree_add_le_of_degree_le (degree_C_mul_X_pow_le 2 a) (le_trans degree_linear_le $ with_bot.coe_le_coe.mpr one_le_two) lemma degree_quadratic_lt : degree (C a * X ^ 2 + C b * X + C c) < 3 := degree_quadratic_le.trans_lt $ with_bot.coe_lt_coe.mpr $ lt_add_one 2 lemma degree_linear_lt_degree_C_mul_X_sq (ha : a ≠ 0) : degree (C b * X + C c) < degree (C a * X ^ 2) := by simpa only [degree_C_mul_X_pow 2 ha] using degree_linear_lt @[simp] lemma degree_quadratic (ha : a ≠ 0) : degree (C a * X ^ 2 + C b * X + C c) = 2 := begin rw [add_assoc, degree_add_eq_left_of_degree_lt $ degree_linear_lt_degree_C_mul_X_sq ha, degree_C_mul_X_pow 2 ha], refl end lemma nat_degree_quadratic_le : nat_degree (C a * X ^ 2 + C b * X + C c) ≤ 2 := nat_degree_le_of_degree_le degree_quadratic_le @[simp] lemma nat_degree_quadratic (ha : a ≠ 0) : nat_degree (C a * X ^ 2 + C b * X + C c) = 2 := nat_degree_eq_of_degree_eq_some $ degree_quadratic ha @[simp] lemma leading_coeff_quadratic (ha : a ≠ 0) : leading_coeff (C a * X ^ 2 + C b * X + C c) = a := by rw [add_assoc, add_comm, leading_coeff_add_of_degree_lt $ degree_linear_lt_degree_C_mul_X_sq ha, leading_coeff_C_mul_X_pow] lemma degree_cubic_le : degree (C a * X ^ 3 + C b * X ^ 2 + C c * X + C d) ≤ 3 := by simpa only [add_assoc] using degree_add_le_of_degree_le (degree_C_mul_X_pow_le 3 a) (le_trans degree_quadratic_le $ with_bot.coe_le_coe.mpr $ nat.le_succ 2) lemma degree_cubic_lt : degree (C a * X ^ 3 + C b * X ^ 2 + C c * X + C d) < 4 := degree_cubic_le.trans_lt $ with_bot.coe_lt_coe.mpr $ lt_add_one 3 lemma degree_quadratic_lt_degree_C_mul_X_cb (ha : a ≠ 0) : degree (C b * X ^ 2 + C c * X + C d) < degree (C a * X ^ 3) := by simpa only [degree_C_mul_X_pow 3 ha] using degree_quadratic_lt @[simp] lemma degree_cubic (ha : a ≠ 0) : degree (C a * X ^ 3 + C b * X ^ 2 + C c * X + C d) = 3 := begin rw [add_assoc, add_assoc, ← add_assoc (C b * X ^ 2), degree_add_eq_left_of_degree_lt $ degree_quadratic_lt_degree_C_mul_X_cb ha, degree_C_mul_X_pow 3 ha], refl end lemma nat_degree_cubic_le : nat_degree (C a * X ^ 3 + C b * X ^ 2 + C c * X + C d) ≤ 3 := nat_degree_le_of_degree_le degree_cubic_le @[simp] lemma nat_degree_cubic (ha : a ≠ 0) : nat_degree (C a * X ^ 3 + C b * X ^ 2 + C c * X + C d) = 3 := nat_degree_eq_of_degree_eq_some $ degree_cubic ha @[simp] lemma leading_coeff_cubic (ha : a ≠ 0): leading_coeff (C a * X ^ 3 + C b * X ^ 2 + C c * X + C d) = a := by rw [add_assoc, add_assoc, ← add_assoc (C b * X ^ 2), add_comm, leading_coeff_add_of_degree_lt $ degree_quadratic_lt_degree_C_mul_X_cb ha, leading_coeff_C_mul_X_pow] end semiring section nontrivial_semiring variables [semiring R] [nontrivial R] {p q : R[X]} @[simp] lemma degree_X_pow (n : ℕ) : degree ((X : R[X]) ^ n) = n := by rw [X_pow_eq_monomial, degree_monomial _ (@one_ne_zero R _ _)] @[simp] lemma nat_degree_X_pow (n : ℕ) : nat_degree ((X : R[X]) ^ n) = n := nat_degree_eq_of_degree_eq_some (degree_X_pow n) /- This lemma explicitly does not require the `nontrivial R` assumption. -/ lemma nat_degree_X_pow_le {R : Type*} [semiring R] (n : ℕ) : (X ^ n : R[X]).nat_degree ≤ n := begin nontriviality R, rwa polynomial.nat_degree_X_pow, end theorem not_is_unit_X : ¬ is_unit (X : R[X]) := λ ⟨⟨_, g, hfg, hgf⟩, rfl⟩, @zero_ne_one R _ _ $ by { change g * monomial 1 1 = 1 at hgf, rw [← coeff_one_zero, ← hgf], simp } @[simp] lemma degree_mul_X : degree (p * X) = degree p + 1 := by simp [monic_X.degree_mul] @[simp] lemma degree_mul_X_pow : degree (p * X ^ n) = degree p + n := by simp [(monic_X_pow n).degree_mul] end nontrivial_semiring section ring variables [ring R] {p q : R[X]} lemma degree_sub_le (p q : R[X]) : degree (p - q) ≤ max (degree p) (degree q) := by simpa only [sub_eq_add_neg, degree_neg q] using degree_add_le p (-q) lemma degree_sub_lt (hd : degree p = degree q) (hp0 : p ≠ 0) (hlc : leading_coeff p = leading_coeff q) : degree (p - q) < degree p := have hp : monomial (nat_degree p) (leading_coeff p) + p.erase (nat_degree p) = p := monomial_add_erase _ _, have hq : monomial (nat_degree q) (leading_coeff q) + q.erase (nat_degree q) = q := monomial_add_erase _ _, have hd' : nat_degree p = nat_degree q := by unfold nat_degree; rw hd, have hq0 : q ≠ 0 := mt degree_eq_bot.2 (hd ▸ mt degree_eq_bot.1 hp0), calc degree (p - q) = degree (erase (nat_degree q) p + -erase (nat_degree q) q) : by conv { to_lhs, rw [← hp, ← hq, hlc, hd', add_sub_add_left_eq_sub, sub_eq_add_neg] } ... ≤ max (degree (erase (nat_degree q) p)) (degree (erase (nat_degree q) q)) : degree_neg (erase (nat_degree q) q) ▸ degree_add_le _ _ ... < degree p : max_lt_iff.2 ⟨hd' ▸ degree_erase_lt hp0, hd.symm ▸ degree_erase_lt hq0⟩ lemma nat_degree_X_sub_C_le {r : R} : (X - C r).nat_degree ≤ 1 := nat_degree_le_iff_degree_le.2 $ le_trans (degree_sub_le _ _) $ max_le degree_X_le $ le_trans degree_C_le $ with_bot.coe_le_coe.2 zero_le_one lemma degree_sub_eq_left_of_degree_lt (h : degree q < degree p) : degree (p - q) = degree p := by { rw ← degree_neg q at h, rw [sub_eq_add_neg, degree_add_eq_left_of_degree_lt h] } lemma degree_sub_eq_right_of_degree_lt (h : degree p < degree q) : degree (p - q) = degree q := by { rw ← degree_neg q at h, rw [sub_eq_add_neg, degree_add_eq_right_of_degree_lt h, degree_neg] } end ring section nonzero_ring variables [nontrivial R] section semiring variable [semiring R] @[simp] lemma degree_X_add_C (a : R) : degree (X + C a) = 1 := have degree (C a) < degree (X : R[X]), from calc degree (C a) ≤ 0 : degree_C_le ... < 1 : with_bot.some_lt_some.mpr zero_lt_one ... = degree X : degree_X.symm, by rw [degree_add_eq_left_of_degree_lt this, degree_X] @[simp] lemma nat_degree_X_add_C (x : R) : (X + C x).nat_degree = 1 := nat_degree_eq_of_degree_eq_some $ degree_X_add_C x @[simp] lemma next_coeff_X_add_C [semiring S] (c : S) : next_coeff (X + C c) = c := begin nontriviality S, simp [next_coeff_of_pos_nat_degree] end lemma degree_X_pow_add_C {n : ℕ} (hn : 0 < n) (a : R) : degree ((X : R[X]) ^ n + C a) = n := have degree (C a) < degree ((X : R[X]) ^ n), from calc degree (C a) ≤ 0 : degree_C_le ... < degree ((X : R[X]) ^ n) : by rwa [degree_X_pow]; exact with_bot.coe_lt_coe.2 hn, by rw [degree_add_eq_left_of_degree_lt this, degree_X_pow] lemma X_pow_add_C_ne_zero {n : ℕ} (hn : 0 < n) (a : R) : (X : R[X]) ^ n + C a ≠ 0 := mt degree_eq_bot.2 (show degree ((X : R[X]) ^ n + C a) ≠ ⊥, by rw degree_X_pow_add_C hn a; exact dec_trivial) theorem X_add_C_ne_zero (r : R) : X + C r ≠ 0 := pow_one (X : R[X]) ▸ X_pow_add_C_ne_zero zero_lt_one r theorem zero_nmem_multiset_map_X_add_C {α : Type*} (m : multiset α) (f : α → R) : (0 : R[X]) ∉ m.map (λ a, X + C (f a)) := λ mem, let ⟨a, _, ha⟩ := multiset.mem_map.mp mem in X_add_C_ne_zero _ ha lemma nat_degree_X_pow_add_C {n : ℕ} {r : R} : (X ^ n + C r).nat_degree = n := begin by_cases hn : n = 0, { rw [hn, pow_zero, ←C_1, ←ring_hom.map_add, nat_degree_C] }, { exact nat_degree_eq_of_degree_eq_some (degree_X_pow_add_C (pos_iff_ne_zero.mpr hn) r) }, end end semiring end nonzero_ring section semiring variable [semiring R] @[simp] lemma leading_coeff_X_pow_add_C {n : ℕ} (hn : 0 < n) {r : R} : (X ^ n + C r).leading_coeff = 1 := begin nontriviality R, rw [leading_coeff, nat_degree_X_pow_add_C, coeff_add, coeff_X_pow_self, coeff_C, if_neg (pos_iff_ne_zero.mp hn), add_zero] end @[simp] lemma leading_coeff_X_add_C [semiring S] (r : S) : (X + C r).leading_coeff = 1 := by rw [←pow_one (X : S[X]), leading_coeff_X_pow_add_C zero_lt_one] @[simp] lemma leading_coeff_X_pow_add_one {n : ℕ} (hn : 0 < n) : (X ^ n + 1 : R[X]).leading_coeff = 1 := leading_coeff_X_pow_add_C hn @[simp] lemma leading_coeff_pow_X_add_C (r : R) (i : ℕ) : leading_coeff ((X + C r) ^ i) = 1 := by { nontriviality, rw leading_coeff_pow'; simp } end semiring section ring variable [ring R] @[simp] lemma leading_coeff_X_pow_sub_C {n : ℕ} (hn : 0 < n) {r : R} : (X ^ n - C r).leading_coeff = 1 := by rw [sub_eq_add_neg, ←map_neg C r, leading_coeff_X_pow_add_C hn]; apply_instance @[simp] lemma leading_coeff_X_pow_sub_one {n : ℕ} (hn : 0 < n) : (X ^ n - 1 : R[X]).leading_coeff = 1 := leading_coeff_X_pow_sub_C hn variables [nontrivial R] @[simp] lemma degree_X_sub_C (a : R) : degree (X - C a) = 1 := by rw [sub_eq_add_neg, ←map_neg C a, degree_X_add_C] @[simp] lemma nat_degree_X_sub_C (x : R) : (X - C x).nat_degree = 1 := nat_degree_eq_of_degree_eq_some $ degree_X_sub_C x @[simp] lemma next_coeff_X_sub_C [ring S] (c : S) : next_coeff (X - C c) = - c := by rw [sub_eq_add_neg, ←map_neg C c, next_coeff_X_add_C] lemma degree_X_pow_sub_C {n : ℕ} (hn : 0 < n) (a : R) : degree ((X : R[X]) ^ n - C a) = n := by rw [sub_eq_add_neg, ←map_neg C a, degree_X_pow_add_C hn]; apply_instance lemma X_pow_sub_C_ne_zero {n : ℕ} (hn : 0 < n) (a : R) : (X : R[X]) ^ n - C a ≠ 0 := by { rw [sub_eq_add_neg, ←map_neg C a], exact X_pow_add_C_ne_zero hn _ } theorem X_sub_C_ne_zero (r : R) : X - C r ≠ 0 := pow_one (X : R[X]) ▸ X_pow_sub_C_ne_zero zero_lt_one r theorem zero_nmem_multiset_map_X_sub_C {α : Type*} (m : multiset α) (f : α → R) : (0 : R[X]) ∉ m.map (λ a, X - C (f a)) := λ mem, let ⟨a, _, ha⟩ := multiset.mem_map.mp mem in X_sub_C_ne_zero _ ha lemma nat_degree_X_pow_sub_C {n : ℕ} {r : R} : (X ^ n - C r).nat_degree = n := by rw [sub_eq_add_neg, ←map_neg C r, nat_degree_X_pow_add_C] @[simp] lemma leading_coeff_X_sub_C [ring S] (r : S) : (X - C r).leading_coeff = 1 := by rw [sub_eq_add_neg, ←map_neg C r, leading_coeff_X_add_C] end ring section no_zero_divisors variables [semiring R] [no_zero_divisors R] {p q : R[X]} @[simp] lemma degree_mul : degree (p * q) = degree p + degree q := if hp0 : p = 0 then by simp only [hp0, degree_zero, zero_mul, with_bot.bot_add] else if hq0 : q = 0 then by simp only [hq0, degree_zero, mul_zero, with_bot.add_bot] else degree_mul' $ mul_ne_zero (mt leading_coeff_eq_zero.1 hp0) (mt leading_coeff_eq_zero.1 hq0) /-- `degree` as a monoid homomorphism between `R[X]` and `multiplicative (with_bot ℕ)`. This is useful to prove results about multiplication and degree. -/ def degree_monoid_hom [nontrivial R] : R[X] →* multiplicative (with_bot ℕ) := { to_fun := degree, map_one' := degree_one, map_mul' := λ _ _, degree_mul } @[simp] lemma degree_pow [nontrivial R] (p : R[X]) (n : ℕ) : degree (p ^ n) = n • (degree p) := map_pow (@degree_monoid_hom R _ _ _) _ _ @[simp] lemma leading_coeff_mul (p q : R[X]) : leading_coeff (p * q) = leading_coeff p * leading_coeff q := begin by_cases hp : p = 0, { simp only [hp, zero_mul, leading_coeff_zero] }, { by_cases hq : q = 0, { simp only [hq, mul_zero, leading_coeff_zero] }, { rw [leading_coeff_mul'], exact mul_ne_zero (mt leading_coeff_eq_zero.1 hp) (mt leading_coeff_eq_zero.1 hq) } } end /-- `polynomial.leading_coeff` bundled as a `monoid_hom` when `R` has `no_zero_divisors`, and thus `leading_coeff` is multiplicative -/ def leading_coeff_hom : R[X] →* R := { to_fun := leading_coeff, map_one' := by simp, map_mul' := leading_coeff_mul } @[simp] lemma leading_coeff_hom_apply (p : R[X]) : leading_coeff_hom p = leading_coeff p := rfl @[simp] lemma leading_coeff_pow (p : R[X]) (n : ℕ) : leading_coeff (p ^ n) = leading_coeff p ^ n := (leading_coeff_hom : R[X] →* R).map_pow p n end no_zero_divisors end polynomial
3e2cc5d9f6aa27c6a1068f6e41e97596810c3ae3
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/test/find_unused_decl2.lean
9e59c5bc054e8487faac8cccec3fccf60e423c15
[ "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
261
lean
import tactic.find_unused def unused1 : ℕ := 1 inductive unused_type | intro : unused_type def my_list := list ℕ def some_val : list ℕ := [1,2,3] @[main_declaration] def other_val : my_list := some_val def used_somewhere_else : my_list := some_val
797fb3d3b1c0cec4ffda713a9a44f478b3893e44
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/library/standard/logic/axioms/examples/diaconescu.lean
d48fb2cf8fdd28c50eec14572cc52eae8efd2824
[ "Apache-2.0" ]
permissive
codyroux/lean
7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3
0cca265db19f7296531e339192e9b9bae4a31f8b
refs/heads/master
1,610,909,964,159
1,407,084,399,000
1,416,857,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,951
lean
------------------------------------------------------------------------------------------------------ Copyright (c) 2014 Microsoft Corporation. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Author: Leonardo de Moura ---------------------------------------------------------------------------------------------------- import logic.axioms.hilbert logic.axioms.funext using eq_proofs -- Diaconescu’s theorem -- Show that Excluded middle follows from -- Hilbert's choice operator, function extensionality and Prop extensionality section hypothesis propext {a b : Prop} : (a → b) → (b → a) → a = b parameter p : Prop definition u [private] := epsilon (λ x, x = true ∨ p) definition v [private] := epsilon (λ x, x = false ∨ p) lemma u_def [private] : u = true ∨ p := epsilon_ax (exists_intro true (or_inl (refl true))) lemma v_def [private] : v = false ∨ p := epsilon_ax (exists_intro false (or_inl (refl false))) lemma uv_implies_p [private] : ¬(u = v) ∨ p := or_elim u_def (assume Hut : u = true, or_elim v_def (assume Hvf : v = false, have Hne : ¬(u = v), from Hvf⁻¹ ▸ Hut⁻¹ ▸ true_ne_false, or_inl Hne) (assume Hp : p, or_inr Hp)) (assume Hp : p, or_inr Hp) lemma p_implies_uv [private] : p → u = v := assume Hp : p, have Hpred : (λ x, x = true ∨ p) = (λ x, x = false ∨ p), from funext (take x : Prop, have Hl : (x = true ∨ p) → (x = false ∨ p), from assume A, or_inr Hp, have Hr : (x = false ∨ p) → (x = true ∨ p), from assume A, or_inr Hp, show (x = true ∨ p) = (x = false ∨ p), from propext Hl Hr), show u = v, from Hpred ▸ (refl (epsilon (λ x, x = true ∨ p))) theorem em : p ∨ ¬p := have H : ¬(u = v) → ¬p, from contrapos p_implies_uv, or_elim uv_implies_p (assume Hne : ¬(u = v), or_inr (H Hne)) (assume Hp : p, or_inl Hp) end
94c84b5f6bbe438c6af821be3731ea037d5ed0bf
750acab0c635b67751bcfec43c5411aa3941c441
/sdg2.lean
cd719da5e55a98274115f4386cb84bbd0088129b
[]
no_license
nthomas103/lean_work
912f8e662cdd73ba97f5d3655ddb8a5d2cd204c9
7e9785cae2b60a77b41922fd5d5b159a1fae415c
refs/heads/master
1,586,739,169,355
1,455,759,226,000
1,455,759,226,000
50,978,095
0
0
null
null
null
null
UTF-8
Lean
false
false
4,077
lean
import standard algebra.module open algebra set prod prod.ops fin nat function -- SDG -- 1.1.1 variables {R : Type} [field R] definition D := { d : R | d ^ 2 = 0 } lemma zero_in_D : (0:R) ∈ D := sorry definition kock_lawvere (f : ∀ d, d ∈ D → R) : ∃! b : R, ∀ d (memD : d ∈ D), f d memD = f 0 zero_in_D + d * b := sorry definition nat.to_R [coercion] (n : ℕ) : R := sorry -- 1.1.3 lemma d0dd : ∀ d, d ∈ D → d * (0:R) = d * d := sorry proposition cancel_d (a b : R) : (∀ d, d ∈ D → d * a = d * b) → a = b := sorry proposition D_not_ideal : ¬ ∀ d₁ d₂ : R, d₁ ∈ D → d₂ ∈ D → d₁ + d₂ ∈ D := sorry --definition D2 := { d : R × R | d.1 ^ 2 = 0 ∧ d.2 ^ 2 = 0 ∧ d.1 * d.2 = 0 } definition D' (n : ℕ) := { d : vector R n | ∀ i j, d i * d j = 0 } --cartesian product notation? better name? proposition D'n_ne_Dn : ∀ n, n ≥ 2 → D' n ≠ { d : vector R n | ∀ i, d i ∈ D } := sorry -- 1.1.4 definition euclidean_module [class] (E : Type) [vector_space R E] := ∀ (f : ∀ d : R, d ∈ D → E), ∃! b : E, ∀ d (memD : d ∈ D), f d memD = f 0 zero_in_D + d • b definition Rn_vector_space {n : ℕ} : vector_space R (vector R n) := sorry --use typeclasses properly to make this cleaner? proposition Rn_euclidean {n : ℕ} : @euclidean_module _ _ (vector R n) Rn_vector_space := sorry --proposition : any product of Euclidean R-modules is a Euclidean R-module --proposition function_euclidean_module (X E : Type) [euclidean_module E] -- 1.2 -- 1.2.1 definition derivative_exists (f : R → R) (a : R) : Σ b, ∀ d (memD : d ∈ D), f (a + d) = f a + d * b := sorry definition der (f : R → R) (a : R) : R := obtain b h, from derivative_exists f a, b postfix `′`:80 := der definition der' (f : R → R) : ℕ → R → R | 0 := f | (n+1) := (der' n) notation f`₍`n`₎` := der' f n definition function_field [instance] : vector_space R (R → R) := sorry definition function_alg [instance] : comm_ring (R → R) := sorry section derivative variables (f g : R → R) (α : R) theorem der_add : (f + g)′ = f′ + g′ := sorry theorem der_smul : (α • f)′ = α • f′ := sorry theorem der_mul : (f * g)′ = f′ * g + f * g′ := sorry theorem chain_rule : (f ∘ g)′ = (f′ ∘ g) * g′ := sorry end derivative -- 1.2.2 proposition taylor (f : R → R) (x : R) (k : ℕ) : ∀ (d : vector R k) (memD : ∀ i, d i ∈ D), let δ := ∑ i ← upto k, d i in f (x + δ) = ∑ n ← upto k, f₍n₎ x * δ ^ n / (nat.to_R (fact n)) := sorry -- 1.2.3 definition directional_derivative_exists {V E : Type} [vector_space R V] [vector_space R E] [@euclidean_module R _ E _] (f : V → E) (u a : V) : Σ b, ∀ (d : R) (memD : d ∈ D), f (a + d • u) = (f a) + (d • b) := sorry definition directional_derivative {V E : Type} [vector_space R V] [vector_space R E] [@euclidean_module R _ E _] (f : V → E) (u a : V) : E := sorry --obtain b h, from directional_derivative_exists f u a, b prefix `∂`:80 := directional_derivative --theorem linear_direction -- 1.3 -- 1.3.1 structure preorder [class] (r : R → R → Prop) := (refl : ∀ x, r x x) (trans : ∀ x y z, r x y → r y z → r x z) (add : ∀ x y z, r x y → r (x + z) (y + z)) (mul : ∀ x y, r 0 x → r 0 y → r 0 (x * y)) (zero_le_one : r 0 1) (one_nle_zero : ¬ r 1 0) (zero_le_D : ∀ d, d ∈ D → r 0 d) (D_le_zero : ∀ d, d ∈ D → r d 0) section preorder variables {r : R → R → Prop} [preorder r] local infix `≼`:80 := r definition interval (a b : R) : set R := { x : R | a ≼ x ∧ x ≼ b } notation `'[`a`,`b`]` := interval a b proposition D_in_00 : D ⊆ '[(0:R), (0:R)] := sorry end preorder -- 2 definition is_microlinear_object (T : Type) : Type := sorry -- 3.1.1 section variables {M : Type} [is_microlinear_object M] (m : M) definition is_tangent_vector := Σ (t : ∀ d : R, d ∈ D → M), t 0 zero_in_D = m end
d3c09a8d7a29e97e382d9f87082b07b77bd07027
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/field_theory/adjoin.lean
d82d4c233958889314280852bd591250f1830e2e
[ "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
45,752
lean
/- Copyright (c) 2020 Thomas Browning, Patrick Lutz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning, Patrick Lutz -/ import field_theory.intermediate_field import field_theory.separable import field_theory.splitting_field import ring_theory.tensor_product /-! # Adjoining Elements to Fields In this file we introduce the notion of adjoining elements to fields. This isn't quite the same as adjoining elements to rings. For example, `algebra.adjoin K {x}` might not include `x⁻¹`. ## Main results - `adjoin_adjoin_left`: adjoining S and then T is the same as adjoining `S ∪ T`. - `bot_eq_top_of_dim_adjoin_eq_one`: if `F⟮x⟯` has dimension `1` over `F` for every `x` in `E` then `F = E` ## Notation - `F⟮α⟯`: adjoin a single element `α` to `F`. -/ open finite_dimensional polynomial open_locale classical polynomial namespace intermediate_field section adjoin_def variables (F : Type*) [field F] {E : Type*} [field E] [algebra F E] (S : set E) /-- `adjoin F S` extends a field `F` by adjoining a set `S ⊆ E`. -/ def adjoin : intermediate_field F E := { algebra_map_mem' := λ x, subfield.subset_closure (or.inl (set.mem_range_self x)), ..subfield.closure (set.range (algebra_map F E) ∪ S) } end adjoin_def section lattice variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E] @[simp] lemma adjoin_le_iff {S : set E} {T : intermediate_field F E} : adjoin F S ≤ T ↔ S ≤ T := ⟨λ H, le_trans (le_trans (set.subset_union_right _ _) subfield.subset_closure) H, λ H, (@subfield.closure_le E _ (set.range (algebra_map F E) ∪ S) T.to_subfield).mpr (set.union_subset (intermediate_field.set_range_subset T) H)⟩ lemma gc : galois_connection (adjoin F : set E → intermediate_field F E) coe := λ _ _, adjoin_le_iff /-- Galois insertion between `adjoin` and `coe`. -/ def gi : galois_insertion (adjoin F : set E → intermediate_field F E) coe := { choice := λ s hs, (adjoin F s).copy s $ le_antisymm (gc.le_u_l s) hs, gc := intermediate_field.gc, le_l_u := λ S, (intermediate_field.gc (S : set E) (adjoin F S)).1 $ le_rfl, choice_eq := λ _ _, copy_eq _ _ _ } instance : complete_lattice (intermediate_field F E) := galois_insertion.lift_complete_lattice intermediate_field.gi instance : inhabited (intermediate_field F E) := ⟨⊤⟩ lemma coe_bot : ↑(⊥ : intermediate_field F E) = set.range (algebra_map F E) := begin change ↑(subfield.closure (set.range (algebra_map F E) ∪ ∅)) = set.range (algebra_map F E), simp [←set.image_univ, ←ring_hom.map_field_closure] end lemma mem_bot {x : E} : x ∈ (⊥ : intermediate_field F E) ↔ x ∈ set.range (algebra_map F E) := set.ext_iff.mp coe_bot x @[simp] lemma bot_to_subalgebra : (⊥ : intermediate_field F E).to_subalgebra = ⊥ := by { ext, rw [mem_to_subalgebra, algebra.mem_bot, mem_bot] } @[simp] lemma coe_top : ↑(⊤ : intermediate_field F E) = (set.univ : set E) := rfl @[simp] lemma mem_top {x : E} : x ∈ (⊤ : intermediate_field F E) := trivial @[simp] lemma top_to_subalgebra : (⊤ : intermediate_field F E).to_subalgebra = ⊤ := rfl @[simp] lemma top_to_subfield : (⊤ : intermediate_field F E).to_subfield = ⊤ := rfl @[simp, norm_cast] lemma coe_inf (S T : intermediate_field F E) : (↑(S ⊓ T) : set E) = S ∩ T := rfl @[simp] lemma mem_inf {S T : intermediate_field F E} {x : E} : x ∈ S ⊓ T ↔ x ∈ S ∧ x ∈ T := iff.rfl @[simp] lemma inf_to_subalgebra (S T : intermediate_field F E) : (S ⊓ T).to_subalgebra = S.to_subalgebra ⊓ T.to_subalgebra := rfl @[simp] lemma inf_to_subfield (S T : intermediate_field F E) : (S ⊓ T).to_subfield = S.to_subfield ⊓ T.to_subfield := rfl @[simp, norm_cast] lemma coe_Inf (S : set (intermediate_field F E)) : (↑(Inf S) : set E) = Inf (coe '' S) := rfl @[simp] lemma Inf_to_subalgebra (S : set (intermediate_field F E)) : (Inf S).to_subalgebra = Inf (to_subalgebra '' S) := set_like.coe_injective $ by simp [set.sUnion_image] @[simp] lemma Inf_to_subfield (S : set (intermediate_field F E)) : (Inf S).to_subfield = Inf (to_subfield '' S) := set_like.coe_injective $ by simp [set.sUnion_image] @[simp, norm_cast] lemma coe_infi {ι : Sort*} (S : ι → intermediate_field F E) : (↑(infi S) : set E) = ⋂ i, (S i) := by simp [infi] @[simp] lemma infi_to_subalgebra {ι : Sort*} (S : ι → intermediate_field F E) : (infi S).to_subalgebra = ⨅ i, (S i).to_subalgebra := set_like.coe_injective $ by simp [infi] @[simp] lemma infi_to_subfield {ι : Sort*} (S : ι → intermediate_field F E) : (infi S).to_subfield = ⨅ i, (S i).to_subfield := set_like.coe_injective $ by simp [infi] /-- Construct an algebra isomorphism from an equality of intermediate fields -/ @[simps apply] def equiv_of_eq {S T : intermediate_field F E} (h : S = T) : S ≃ₐ[F] T := by refine { to_fun := λ x, ⟨x, _⟩, inv_fun := λ x, ⟨x, _⟩, .. }; tidy @[simp] lemma equiv_of_eq_symm {S T : intermediate_field F E} (h : S = T) : (equiv_of_eq h).symm = equiv_of_eq h.symm := rfl @[simp] lemma equiv_of_eq_rfl (S : intermediate_field F E) : equiv_of_eq (rfl : S = S) = alg_equiv.refl := by { ext, refl } @[simp] lemma equiv_of_eq_trans {S T U : intermediate_field F E} (hST : S = T) (hTU : T = U) : (equiv_of_eq hST).trans (equiv_of_eq hTU) = equiv_of_eq (trans hST hTU) := rfl variables (F E) /-- The bottom intermediate_field is isomorphic to the field. -/ noncomputable def bot_equiv : (⊥ : intermediate_field F E) ≃ₐ[F] F := (subalgebra.equiv_of_eq _ _ bot_to_subalgebra).trans (algebra.bot_equiv F E) variables {F E} @[simp] lemma bot_equiv_def (x : F) : bot_equiv F E (algebra_map F (⊥ : intermediate_field F E) x) = x := alg_equiv.commutes (bot_equiv F E) x @[simp] lemma bot_equiv_symm (x : F) : (bot_equiv F E).symm x = algebra_map F _ x := rfl noncomputable instance algebra_over_bot : algebra (⊥ : intermediate_field F E) F := (intermediate_field.bot_equiv F E).to_alg_hom.to_ring_hom.to_algebra lemma coe_algebra_map_over_bot : (algebra_map (⊥ : intermediate_field F E) F : (⊥ : intermediate_field F E) → F) = (intermediate_field.bot_equiv F E) := rfl instance is_scalar_tower_over_bot : is_scalar_tower (⊥ : intermediate_field F E) F E := is_scalar_tower.of_algebra_map_eq begin intro x, obtain ⟨y, rfl⟩ := (bot_equiv F E).symm.surjective x, rw [coe_algebra_map_over_bot, (bot_equiv F E).apply_symm_apply, bot_equiv_symm, is_scalar_tower.algebra_map_apply F (⊥ : intermediate_field F E) E] end /-- The top intermediate_field is isomorphic to the field. This is the intermediate field version of `subalgebra.top_equiv`. -/ @[simps apply] def top_equiv : (⊤ : intermediate_field F E) ≃ₐ[F] E := (subalgebra.equiv_of_eq _ _ top_to_subalgebra).trans subalgebra.top_equiv @[simp] lemma top_equiv_symm_apply_coe (a : E) : ↑((top_equiv.symm) a : (⊤ : intermediate_field F E)) = a := rfl @[simp] lemma restrict_scalars_bot_eq_self (K : intermediate_field F E) : (⊥ : intermediate_field K E).restrict_scalars _ = K := by { ext, rw [mem_restrict_scalars, mem_bot], exact set.ext_iff.mp subtype.range_coe x } @[simp] lemma restrict_scalars_top {K : Type*} [field K] [algebra K E] [algebra K F] [is_scalar_tower K F E] : (⊤ : intermediate_field F E).restrict_scalars K = ⊤ := rfl lemma _root_.alg_hom.field_range_eq_map {K : Type*} [field K] [algebra F K] (f : E →ₐ[F] K) : f.field_range = intermediate_field.map f ⊤ := set_like.ext' set.image_univ.symm lemma _root_.alg_hom.map_field_range {K L : Type*} [field K] [field L] [algebra F K] [algebra F L] (f : E →ₐ[F] K) (g : K →ₐ[F] L) : f.field_range.map g = (g.comp f).field_range := set_like.ext' (set.range_comp g f).symm end lattice section adjoin_def variables (F : Type*) [field F] {E : Type*} [field E] [algebra F E] (S : set E) lemma adjoin_eq_range_algebra_map_adjoin : (adjoin F S : set E) = set.range (algebra_map (adjoin F S) E) := (subtype.range_coe).symm lemma adjoin.algebra_map_mem (x : F) : algebra_map F E x ∈ adjoin F S := intermediate_field.algebra_map_mem (adjoin F S) x lemma adjoin.range_algebra_map_subset : set.range (algebra_map F E) ⊆ adjoin F S := begin intros x hx, cases hx with f hf, rw ← hf, exact adjoin.algebra_map_mem F S f, end instance adjoin.field_coe : has_coe_t F (adjoin F S) := {coe := λ x, ⟨algebra_map F E x, adjoin.algebra_map_mem F S x⟩} lemma subset_adjoin : S ⊆ adjoin F S := λ x hx, subfield.subset_closure (or.inr hx) instance adjoin.set_coe : has_coe_t S (adjoin F S) := {coe := λ x, ⟨x,subset_adjoin F S (subtype.mem x)⟩} @[mono] lemma adjoin.mono (T : set E) (h : S ⊆ T) : adjoin F S ≤ adjoin F T := galois_connection.monotone_l gc h lemma adjoin_contains_field_as_subfield (F : subfield E) : (F : set E) ⊆ adjoin F S := λ x hx, adjoin.algebra_map_mem F S ⟨x, hx⟩ lemma subset_adjoin_of_subset_left {F : subfield E} {T : set E} (HT : T ⊆ F) : T ⊆ adjoin F S := λ x hx, (adjoin F S).algebra_map_mem ⟨x, HT hx⟩ lemma subset_adjoin_of_subset_right {T : set E} (H : T ⊆ S) : T ⊆ adjoin F S := λ x hx, subset_adjoin F S (H hx) @[simp] lemma adjoin_empty (F E : Type*) [field F] [field E] [algebra F E] : adjoin F (∅ : set E) = ⊥ := eq_bot_iff.mpr (adjoin_le_iff.mpr (set.empty_subset _)) @[simp] lemma adjoin_univ (F E : Type*) [field F] [field E] [algebra F E] : adjoin F (set.univ : set E) = ⊤ := eq_top_iff.mpr $ subset_adjoin _ _ /-- If `K` is a field with `F ⊆ K` and `S ⊆ K` then `adjoin F S ≤ K`. -/ lemma adjoin_le_subfield {K : subfield E} (HF : set.range (algebra_map F E) ⊆ K) (HS : S ⊆ K) : (adjoin F S).to_subfield ≤ K := begin apply subfield.closure_le.mpr, rw set.union_subset_iff, exact ⟨HF, HS⟩, end lemma adjoin_subset_adjoin_iff {F' : Type*} [field F'] [algebra F' E] {S S' : set E} : (adjoin F S : set E) ⊆ adjoin F' S' ↔ set.range (algebra_map F E) ⊆ adjoin F' S' ∧ S ⊆ adjoin F' S' := ⟨λ h, ⟨trans (adjoin.range_algebra_map_subset _ _) h, trans (subset_adjoin _ _) h⟩, λ ⟨hF, hS⟩, subfield.closure_le.mpr (set.union_subset hF hS)⟩ /-- `F[S][T] = F[S ∪ T]` -/ lemma adjoin_adjoin_left (T : set E) : (adjoin (adjoin F S) T).restrict_scalars _ = adjoin F (S ∪ T) := begin rw set_like.ext'_iff, change ↑(adjoin (adjoin F S) T) = _, apply set.eq_of_subset_of_subset; rw adjoin_subset_adjoin_iff; split, { rintros _ ⟨⟨x, hx⟩, rfl⟩, exact adjoin.mono _ _ _ (set.subset_union_left _ _) hx }, { exact subset_adjoin_of_subset_right _ _ (set.subset_union_right _ _) }, { exact subset_adjoin_of_subset_left _ (adjoin.range_algebra_map_subset _ _) }, { exact set.union_subset (subset_adjoin_of_subset_left _ (subset_adjoin _ _)) (subset_adjoin _ _) }, end @[simp] lemma adjoin_insert_adjoin (x : E) : adjoin F (insert x (adjoin F S : set E)) = adjoin F (insert x S) := le_antisymm (adjoin_le_iff.mpr (set.insert_subset.mpr ⟨subset_adjoin _ _ (set.mem_insert _ _), adjoin_le_iff.mpr (subset_adjoin_of_subset_right _ _ (set.subset_insert _ _))⟩)) (adjoin.mono _ _ _ (set.insert_subset_insert (subset_adjoin _ _))) /-- `F[S][T] = F[T][S]` -/ lemma adjoin_adjoin_comm (T : set E) : (adjoin (adjoin F S) T).restrict_scalars F = (adjoin (adjoin F T) S).restrict_scalars F := by rw [adjoin_adjoin_left, adjoin_adjoin_left, set.union_comm] lemma adjoin_map {E' : Type*} [field E'] [algebra F E'] (f : E →ₐ[F] E') : (adjoin F S).map f = adjoin F (f '' S) := begin ext x, show x ∈ (subfield.closure (set.range (algebra_map F E) ∪ S)).map (f : E →+* E') ↔ x ∈ subfield.closure (set.range (algebra_map F E') ∪ f '' S), rw [ring_hom.map_field_closure, set.image_union, ← set.range_comp, ← ring_hom.coe_comp, f.comp_algebra_map], refl, end lemma algebra_adjoin_le_adjoin : algebra.adjoin F S ≤ (adjoin F S).to_subalgebra := algebra.adjoin_le (subset_adjoin _ _) lemma adjoin_eq_algebra_adjoin (inv_mem : ∀ x ∈ algebra.adjoin F S, x⁻¹ ∈ algebra.adjoin F S) : (adjoin F S).to_subalgebra = algebra.adjoin F S := le_antisymm (show adjoin F S ≤ { neg_mem' := λ x, (algebra.adjoin F S).neg_mem, inv_mem' := inv_mem, .. algebra.adjoin F S}, from adjoin_le_iff.mpr (algebra.subset_adjoin)) (algebra_adjoin_le_adjoin _ _) lemma eq_adjoin_of_eq_algebra_adjoin (K : intermediate_field F E) (h : K.to_subalgebra = algebra.adjoin F S) : K = adjoin F S := begin apply to_subalgebra_injective, rw h, refine (adjoin_eq_algebra_adjoin _ _ _).symm, intros x, convert K.inv_mem, rw ← h, refl end @[elab_as_eliminator] lemma adjoin_induction {s : set E} {p : E → Prop} {x} (h : x ∈ adjoin F s) (Hs : ∀ x ∈ s, p x) (Hmap : ∀ x, p (algebra_map F E x)) (Hadd : ∀ x y, p x → p y → p (x + y)) (Hneg : ∀ x, p x → p (-x)) (Hinv : ∀ x, p x → p x⁻¹) (Hmul : ∀ x y, p x → p y → p (x * y)) : p x := subfield.closure_induction h (λ x hx, or.cases_on hx (λ ⟨x, hx⟩, hx ▸ Hmap x) (Hs x)) ((algebra_map F E).map_one ▸ Hmap 1) Hadd Hneg Hinv Hmul /-- Variation on `set.insert` to enable good notation for adjoining elements to fields. Used to preferentially use `singleton` rather than `insert` when adjoining one element. -/ --this definition of notation is courtesy of Kyle Miller on zulip class insert {α : Type*} (s : set α) := (insert : α → set α) @[priority 1000] instance insert_empty {α : Type*} : insert (∅ : set α) := { insert := λ x, @singleton _ _ set.has_singleton x } @[priority 900] instance insert_nonempty {α : Type*} (s : set α) : insert s := { insert := λ x, has_insert.insert x s } notation K`⟮`:std.prec.max_plus l:(foldr `, ` (h t, insert.insert t h) ∅) `⟯` := adjoin K l section adjoin_simple variables (α : E) lemma mem_adjoin_simple_self : α ∈ F⟮α⟯ := subset_adjoin F {α} (set.mem_singleton α) /-- generator of `F⟮α⟯` -/ def adjoin_simple.gen : F⟮α⟯ := ⟨α, mem_adjoin_simple_self F α⟩ @[simp] lemma adjoin_simple.algebra_map_gen : algebra_map F⟮α⟯ E (adjoin_simple.gen F α) = α := rfl @[simp] lemma adjoin_simple.is_integral_gen : is_integral F (adjoin_simple.gen F α) ↔ is_integral F α := by { conv_rhs { rw ← adjoin_simple.algebra_map_gen F α }, rw is_integral_algebra_map_iff (algebra_map F⟮α⟯ E).injective, apply_instance } lemma adjoin_simple_adjoin_simple (β : E) : F⟮α⟯⟮β⟯.restrict_scalars F = F⟮α, β⟯ := adjoin_adjoin_left _ _ _ lemma adjoin_simple_comm (β : E) : F⟮α⟯⟮β⟯.restrict_scalars F = F⟮β⟯⟮α⟯.restrict_scalars F := adjoin_adjoin_comm _ _ _ variables {F} {α} lemma adjoin_algebraic_to_subalgebra {S : set E} (hS : ∀ x ∈ S, is_algebraic F x) : (intermediate_field.adjoin F S).to_subalgebra = algebra.adjoin F S := begin simp only [is_algebraic_iff_is_integral] at hS, have : algebra.is_integral F (algebra.adjoin F S) := by rwa [←le_integral_closure_iff_is_integral, algebra.adjoin_le_iff], have := is_field_of_is_integral_of_is_field' this (field.to_is_field F), rw ← ((algebra.adjoin F S).to_intermediate_field' this).eq_adjoin_of_eq_algebra_adjoin F S; refl, end lemma adjoin_simple_to_subalgebra_of_integral (hα : is_integral F α) : (F⟮α⟯).to_subalgebra = algebra.adjoin F {α} := begin apply adjoin_algebraic_to_subalgebra, rintro x (rfl : x = α), rwa is_algebraic_iff_is_integral, end lemma is_splitting_field_iff {p : F[X]} {K : intermediate_field F E} : p.is_splitting_field F K ↔ p.splits (algebra_map F K) ∧ K = adjoin F (p.root_set E) := begin suffices : _ → ((algebra.adjoin F (p.root_set K) = ⊤ ↔ K = adjoin F (p.root_set E))), { exact ⟨λ h, ⟨h.1, (this h.1).mp h.2⟩, λ h, ⟨h.1, (this h.1).mpr h.2⟩⟩ }, simp_rw [set_like.ext_iff, ←mem_to_subalgebra, ←set_like.ext_iff], rw [←K.range_val, adjoin_algebraic_to_subalgebra (λ x, is_algebraic_of_mem_root_set)], exact λ hp, (adjoin_root_set_eq_range hp K.val).symm.trans eq_comm, end lemma adjoin_root_set_is_splitting_field {p : F[X]} (hp : p.splits (algebra_map F E)) : p.is_splitting_field F (adjoin F (p.root_set E)) := is_splitting_field_iff.mpr ⟨splits_of_splits hp (λ x hx, subset_adjoin F (p.root_set E) hx), rfl⟩ open_locale big_operators /-- A compositum of splitting fields is a splitting field -/ lemma is_splitting_field_supr {ι : Type*} {t : ι → intermediate_field F E} {p : ι → F[X]} {s : finset ι} (h0 : ∏ i in s, p i ≠ 0) (h : ∀ i ∈ s, (p i).is_splitting_field F (t i)) : (∏ i in s, p i).is_splitting_field F (⨆ i ∈ s, t i : intermediate_field F E) := begin let K : intermediate_field F E := ⨆ i ∈ s, t i, have hK : ∀ i ∈ s, t i ≤ K := λ i hi, le_supr_of_le i (le_supr (λ _, t i) hi), simp only [is_splitting_field_iff] at h ⊢, refine ⟨splits_prod (algebra_map F K) (λ i hi, polynomial.splits_comp_of_splits (algebra_map F (t i)) (inclusion (hK i hi)).to_ring_hom (h i hi).1), _⟩, simp only [root_set_prod p s h0, ←set.supr_eq_Union, (@gc F _ E _ _).l_supr₂], exact supr_congr (λ i, supr_congr (λ hi, (h i hi).2)), end open set complete_lattice @[simp] lemma adjoin_simple_le_iff {K : intermediate_field F E} : F⟮α⟯ ≤ K ↔ α ∈ K := adjoin_le_iff.trans singleton_subset_iff /-- Adjoining a single element is compact in the lattice of intermediate fields. -/ lemma adjoin_simple_is_compact_element (x : E) : is_compact_element F⟮x⟯ := begin rw is_compact_element_iff_le_of_directed_Sup_le, rintros s ⟨F₀, hF₀⟩ hs hx, simp only [adjoin_simple_le_iff] at hx ⊢, let F : intermediate_field F E := { carrier := ⋃ E ∈ s, ↑E, add_mem' := by { rintros x₁ x₂ ⟨-, ⟨F₁, rfl⟩, ⟨-, ⟨hF₁, rfl⟩, hx₁⟩⟩ ⟨-, ⟨F₂, rfl⟩, ⟨-, ⟨hF₂, rfl⟩, hx₂⟩⟩, obtain ⟨F₃, hF₃, h₁₃, h₂₃⟩ := hs F₁ hF₁ F₂ hF₂, exact mem_Union_of_mem F₃ (mem_Union_of_mem hF₃ (F₃.add_mem (h₁₃ hx₁) (h₂₃ hx₂))) }, neg_mem' := by { rintros x ⟨-, ⟨E, rfl⟩, ⟨-, ⟨hE, rfl⟩, hx⟩⟩, exact mem_Union_of_mem E (mem_Union_of_mem hE (E.neg_mem hx)) }, mul_mem' := by { rintros x₁ x₂ ⟨-, ⟨F₁, rfl⟩, ⟨-, ⟨hF₁, rfl⟩, hx₁⟩⟩ ⟨-, ⟨F₂, rfl⟩, ⟨-, ⟨hF₂, rfl⟩, hx₂⟩⟩, obtain ⟨F₃, hF₃, h₁₃, h₂₃⟩ := hs F₁ hF₁ F₂ hF₂, exact mem_Union_of_mem F₃ (mem_Union_of_mem hF₃ (F₃.mul_mem (h₁₃ hx₁) (h₂₃ hx₂))) }, inv_mem' := by { rintros x ⟨-, ⟨E, rfl⟩, ⟨-, ⟨hE, rfl⟩, hx⟩⟩, exact mem_Union_of_mem E (mem_Union_of_mem hE (E.inv_mem hx)) }, algebra_map_mem' := λ x, mem_Union_of_mem F₀ (mem_Union_of_mem hF₀ (F₀.algebra_map_mem x)) }, have key : Sup s ≤ F := Sup_le (λ E hE, subset_Union_of_subset E (subset_Union _ hE)), obtain ⟨-, ⟨E, rfl⟩, -, ⟨hE, rfl⟩, hx⟩ := key hx, exact ⟨E, hE, hx⟩, end /-- Adjoining a finite subset is compact in the lattice of intermediate fields. -/ lemma adjoin_finset_is_compact_element (S : finset E) : is_compact_element (adjoin F S : intermediate_field F E) := begin have key : adjoin F ↑S = ⨆ x ∈ S, F⟮x⟯ := le_antisymm (adjoin_le_iff.mpr (λ x hx, set_like.mem_coe.mpr (adjoin_simple_le_iff.mp (le_supr_of_le x (le_supr_of_le hx le_rfl))))) (supr_le (λ x, supr_le (λ hx, adjoin_simple_le_iff.mpr (subset_adjoin F S hx)))), rw [key, ←finset.sup_eq_supr], exact finset_sup_compact_of_compact S (λ x hx, adjoin_simple_is_compact_element x), end /-- Adjoining a finite subset is compact in the lattice of intermediate fields. -/ lemma adjoin_finite_is_compact_element {S : set E} (h : S.finite) : is_compact_element (adjoin F S) := finite.coe_to_finset h ▸ (adjoin_finset_is_compact_element h.to_finset) /-- The lattice of intermediate fields is compactly generated. -/ instance : is_compactly_generated (intermediate_field F E) := ⟨λ s, ⟨(λ x, F⟮x⟯) '' s, ⟨by rintros t ⟨x, hx, rfl⟩; exact adjoin_simple_is_compact_element x, Sup_image.trans (le_antisymm (supr_le (λ i, supr_le (λ hi, adjoin_simple_le_iff.mpr hi))) (λ x hx, adjoin_simple_le_iff.mp (le_supr_of_le x (le_supr_of_le hx le_rfl))))⟩⟩⟩ lemma exists_finset_of_mem_supr {ι : Type*} {f : ι → intermediate_field F E} {x : E} (hx : x ∈ ⨆ i, f i) : ∃ s : finset ι, x ∈ ⨆ i ∈ s, f i := begin have := (adjoin_simple_is_compact_element x).exists_finset_of_le_supr (intermediate_field F E) f, simp only [adjoin_simple_le_iff] at this, exact this hx, end lemma exists_finset_of_mem_supr' {ι : Type*} {f : ι → intermediate_field F E} {x : E} (hx : x ∈ ⨆ i, f i) : ∃ s : finset (Σ i, f i), x ∈ ⨆ i ∈ s, F⟮(i.2 : E)⟯ := exists_finset_of_mem_supr (set_like.le_def.mp (supr_le (λ i x h, set_like.le_def.mp (le_supr_of_le ⟨i, x, h⟩ le_rfl) (mem_adjoin_simple_self F x))) hx) lemma exists_finset_of_mem_supr'' {ι : Type*} {f : ι → intermediate_field F E} (h : ∀ i, algebra.is_algebraic F (f i)) {x : E} (hx : x ∈ ⨆ i, f i) : ∃ s : finset (Σ i, f i), x ∈ ⨆ i ∈ s, adjoin F ((minpoly F (i.2 : _)).root_set E) := begin refine exists_finset_of_mem_supr (set_like.le_def.mp (supr_le (λ i x hx, set_like.le_def.mp (le_supr_of_le ⟨i, x, hx⟩ le_rfl) (subset_adjoin F _ _))) hx), rw [intermediate_field.minpoly_eq, subtype.coe_mk, polynomial.mem_root_set, minpoly.aeval], exact minpoly.ne_zero (is_integral_iff.mp (is_algebraic_iff_is_integral.mp (h i ⟨x, hx⟩))) end end adjoin_simple end adjoin_def section adjoin_intermediate_field_lattice variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E] {α : E} {S : set E} @[simp] lemma adjoin_eq_bot_iff : adjoin F S = ⊥ ↔ S ⊆ (⊥ : intermediate_field F E) := by { rw [eq_bot_iff, adjoin_le_iff], refl, } @[simp] lemma adjoin_simple_eq_bot_iff : F⟮α⟯ = ⊥ ↔ α ∈ (⊥ : intermediate_field F E) := by { rw adjoin_eq_bot_iff, exact set.singleton_subset_iff } @[simp] lemma adjoin_zero : F⟮(0 : E)⟯ = ⊥ := adjoin_simple_eq_bot_iff.mpr (zero_mem ⊥) @[simp] lemma adjoin_one : F⟮(1 : E)⟯ = ⊥ := adjoin_simple_eq_bot_iff.mpr (one_mem ⊥) @[simp] lemma adjoin_int (n : ℤ) : F⟮(n : E)⟯ = ⊥ := adjoin_simple_eq_bot_iff.mpr (coe_int_mem ⊥ n) @[simp] lemma adjoin_nat (n : ℕ) : F⟮(n : E)⟯ = ⊥ := adjoin_simple_eq_bot_iff.mpr (coe_nat_mem ⊥ n) section adjoin_dim open finite_dimensional module variables {K L : intermediate_field F E} @[simp] lemma dim_eq_one_iff : module.rank F K = 1 ↔ K = ⊥ := by rw [← to_subalgebra_eq_iff, ← dim_eq_dim_subalgebra, subalgebra.dim_eq_one_iff, bot_to_subalgebra] @[simp] lemma finrank_eq_one_iff : finrank F K = 1 ↔ K = ⊥ := by rw [← to_subalgebra_eq_iff, ← finrank_eq_finrank_subalgebra, subalgebra.finrank_eq_one_iff, bot_to_subalgebra] @[simp] lemma dim_bot : module.rank F (⊥ : intermediate_field F E) = 1 := by rw dim_eq_one_iff @[simp] lemma finrank_bot : finrank F (⊥ : intermediate_field F E) = 1 := by rw finrank_eq_one_iff lemma dim_adjoin_eq_one_iff : module.rank F (adjoin F S) = 1 ↔ S ⊆ (⊥ : intermediate_field F E) := iff.trans dim_eq_one_iff adjoin_eq_bot_iff lemma dim_adjoin_simple_eq_one_iff : module.rank F F⟮α⟯ = 1 ↔ α ∈ (⊥ : intermediate_field F E) := by { rw dim_adjoin_eq_one_iff, exact set.singleton_subset_iff } lemma finrank_adjoin_eq_one_iff : finrank F (adjoin F S) = 1 ↔ S ⊆ (⊥ : intermediate_field F E) := iff.trans finrank_eq_one_iff adjoin_eq_bot_iff lemma finrank_adjoin_simple_eq_one_iff : finrank F F⟮α⟯ = 1 ↔ α ∈ (⊥ : intermediate_field F E) := by { rw [finrank_adjoin_eq_one_iff], exact set.singleton_subset_iff } /-- If `F⟮x⟯` has dimension `1` over `F` for every `x ∈ E` then `F = E`. -/ lemma bot_eq_top_of_dim_adjoin_eq_one (h : ∀ x : E, module.rank F F⟮x⟯ = 1) : (⊥ : intermediate_field F E) = ⊤ := begin ext, rw iff_true_right intermediate_field.mem_top, exact dim_adjoin_simple_eq_one_iff.mp (h x), end lemma bot_eq_top_of_finrank_adjoin_eq_one (h : ∀ x : E, finrank F F⟮x⟯ = 1) : (⊥ : intermediate_field F E) = ⊤ := begin ext, rw iff_true_right intermediate_field.mem_top, exact finrank_adjoin_simple_eq_one_iff.mp (h x), end lemma subsingleton_of_dim_adjoin_eq_one (h : ∀ x : E, module.rank F F⟮x⟯ = 1) : subsingleton (intermediate_field F E) := subsingleton_of_bot_eq_top (bot_eq_top_of_dim_adjoin_eq_one h) lemma subsingleton_of_finrank_adjoin_eq_one (h : ∀ x : E, finrank F F⟮x⟯ = 1) : subsingleton (intermediate_field F E) := subsingleton_of_bot_eq_top (bot_eq_top_of_finrank_adjoin_eq_one h) /-- If `F⟮x⟯` has dimension `≤1` over `F` for every `x ∈ E` then `F = E`. -/ lemma bot_eq_top_of_finrank_adjoin_le_one [finite_dimensional F E] (h : ∀ x : E, finrank F F⟮x⟯ ≤ 1) : (⊥ : intermediate_field F E) = ⊤ := begin apply bot_eq_top_of_finrank_adjoin_eq_one, exact λ x, by linarith [h x, show 0 < finrank F F⟮x⟯, from finrank_pos], end lemma subsingleton_of_finrank_adjoin_le_one [finite_dimensional F E] (h : ∀ x : E, finrank F F⟮x⟯ ≤ 1) : subsingleton (intermediate_field F E) := subsingleton_of_bot_eq_top (bot_eq_top_of_finrank_adjoin_le_one h) end adjoin_dim end adjoin_intermediate_field_lattice section adjoin_integral_element variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E] {α : E} variables {K : Type*} [field K] [algebra F K] lemma minpoly_gen {α : E} (h : is_integral F α) : minpoly F (adjoin_simple.gen F α) = minpoly F α := begin rw ← adjoin_simple.algebra_map_gen F α at h, have inj := (algebra_map F⟮α⟯ E).injective, exact minpoly.eq_of_algebra_map_eq inj ((is_integral_algebra_map_iff inj).mp h) (adjoin_simple.algebra_map_gen _ _).symm end variables (F) lemma aeval_gen_minpoly (α : E) : aeval (adjoin_simple.gen F α) (minpoly F α) = 0 := begin ext, convert minpoly.aeval F α, conv in (aeval α) { rw [← adjoin_simple.algebra_map_gen F α] }, exact (aeval_algebra_map_apply E (adjoin_simple.gen F α) _).symm end /-- algebra isomorphism between `adjoin_root` and `F⟮α⟯` -/ noncomputable def adjoin_root_equiv_adjoin (h : is_integral F α) : adjoin_root (minpoly F α) ≃ₐ[F] F⟮α⟯ := alg_equiv.of_bijective (adjoin_root.lift_hom (minpoly F α) (adjoin_simple.gen F α) (aeval_gen_minpoly F α)) (begin set f := adjoin_root.lift _ _ (aeval_gen_minpoly F α : _), haveI := fact.mk (minpoly.irreducible h), split, { exact ring_hom.injective f }, { suffices : F⟮α⟯.to_subfield ≤ ring_hom.field_range ((F⟮α⟯.to_subfield.subtype).comp f), { exact λ x, Exists.cases_on (this (subtype.mem x)) (λ y hy, ⟨y, subtype.ext hy⟩) }, exact subfield.closure_le.mpr (set.union_subset (λ x hx, Exists.cases_on hx (λ y hy, ⟨y, by { rw [ring_hom.comp_apply, adjoin_root.lift_of], exact hy }⟩)) (set.singleton_subset_iff.mpr ⟨adjoin_root.root (minpoly F α), by { rw [ring_hom.comp_apply, adjoin_root.lift_root], refl }⟩)) } end) lemma adjoin_root_equiv_adjoin_apply_root (h : is_integral F α) : adjoin_root_equiv_adjoin F h (adjoin_root.root (minpoly F α)) = adjoin_simple.gen F α := adjoin_root.lift_root (aeval_gen_minpoly F α) section power_basis variables {L : Type*} [field L] [algebra K L] /-- The elements `1, x, ..., x ^ (d - 1)` form a basis for `K⟮x⟯`, where `d` is the degree of the minimal polynomial of `x`. -/ noncomputable def power_basis_aux {x : L} (hx : is_integral K x) : basis (fin (minpoly K x).nat_degree) K K⟮x⟯ := (adjoin_root.power_basis (minpoly.ne_zero hx)).basis.map (adjoin_root_equiv_adjoin K hx).to_linear_equiv /-- The power basis `1, x, ..., x ^ (d - 1)` for `K⟮x⟯`, where `d` is the degree of the minimal polynomial of `x`. -/ @[simps] noncomputable def adjoin.power_basis {x : L} (hx : is_integral K x) : power_basis K K⟮x⟯ := { gen := adjoin_simple.gen K x, dim := (minpoly K x).nat_degree, basis := power_basis_aux hx, basis_eq_pow := λ i, by rw [power_basis_aux, basis.map_apply, power_basis.basis_eq_pow, alg_equiv.to_linear_equiv_apply, alg_equiv.map_pow, adjoin_root.power_basis_gen, adjoin_root_equiv_adjoin_apply_root] } lemma adjoin.finite_dimensional {x : L} (hx : is_integral K x) : finite_dimensional K K⟮x⟯ := power_basis.finite_dimensional (adjoin.power_basis hx) lemma adjoin.finrank {x : L} (hx : is_integral K x) : finite_dimensional.finrank K K⟮x⟯ = (minpoly K x).nat_degree := begin rw power_basis.finrank (adjoin.power_basis hx : _), refl end lemma _root_.minpoly.nat_degree_le {x : L} [finite_dimensional K L] (hx : is_integral K x) : (minpoly K x).nat_degree ≤ finrank K L := le_of_eq_of_le (intermediate_field.adjoin.finrank hx).symm K⟮x⟯.to_submodule.finrank_le lemma _root_.minpoly.degree_le {x : L} [finite_dimensional K L] (hx : is_integral K x) : (minpoly K x).degree ≤ finrank K L := degree_le_of_nat_degree_le (minpoly.nat_degree_le hx) end power_basis /-- Algebra homomorphism `F⟮α⟯ →ₐ[F] K` are in bijection with the set of roots of `minpoly α` in `K`. -/ noncomputable def alg_hom_adjoin_integral_equiv (h : is_integral F α) : (F⟮α⟯ →ₐ[F] K) ≃ {x // x ∈ ((minpoly F α).map (algebra_map F K)).roots} := (adjoin.power_basis h).lift_equiv'.trans ((equiv.refl _).subtype_equiv (λ x, by rw [adjoin.power_basis_gen, minpoly_gen h, equiv.refl_apply])) /-- Fintype of algebra homomorphism `F⟮α⟯ →ₐ[F] K` -/ noncomputable def fintype_of_alg_hom_adjoin_integral (h : is_integral F α) : fintype (F⟮α⟯ →ₐ[F] K) := power_basis.alg_hom.fintype (adjoin.power_basis h) lemma card_alg_hom_adjoin_integral (h : is_integral F α) (h_sep : (minpoly F α).separable) (h_splits : (minpoly F α).splits (algebra_map F K)) : @fintype.card (F⟮α⟯ →ₐ[F] K) (fintype_of_alg_hom_adjoin_integral F h) = (minpoly F α).nat_degree := begin rw alg_hom.card_of_power_basis; simp only [adjoin.power_basis_dim, adjoin.power_basis_gen, minpoly_gen h, h_sep, h_splits], end end adjoin_integral_element section induction variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E] /-- An intermediate field `S` is finitely generated if there exists `t : finset E` such that `intermediate_field.adjoin F t = S`. -/ def fg (S : intermediate_field F E) : Prop := ∃ (t : finset E), adjoin F ↑t = S lemma fg_adjoin_finset (t : finset E) : (adjoin F (↑t : set E)).fg := ⟨t, rfl⟩ theorem fg_def {S : intermediate_field F E} : S.fg ↔ ∃ t : set E, set.finite t ∧ adjoin F t = S := iff.symm set.exists_finite_iff_finset theorem fg_bot : (⊥ : intermediate_field F E).fg := ⟨∅, adjoin_empty F E⟩ lemma fg_of_fg_to_subalgebra (S : intermediate_field F E) (h : S.to_subalgebra.fg) : S.fg := begin cases h with t ht, exact ⟨t, (eq_adjoin_of_eq_algebra_adjoin _ _ _ ht.symm).symm⟩ end lemma fg_of_noetherian (S : intermediate_field F E) [is_noetherian F E] : S.fg := S.fg_of_fg_to_subalgebra S.to_subalgebra.fg_of_noetherian lemma induction_on_adjoin_finset (S : finset E) (P : intermediate_field F E → Prop) (base : P ⊥) (ih : ∀ (K : intermediate_field F E) (x ∈ S), P K → P (K⟮x⟯.restrict_scalars F)) : P (adjoin F ↑S) := begin apply finset.induction_on' S, { exact base }, { intros a s h1 _ _ h4, rw [finset.coe_insert, set.insert_eq, set.union_comm, ←adjoin_adjoin_left], exact ih (adjoin F s) a h1 h4 } end lemma induction_on_adjoin_fg (P : intermediate_field F E → Prop) (base : P ⊥) (ih : ∀ (K : intermediate_field F E) (x : E), P K → P (K⟮x⟯.restrict_scalars F)) (K : intermediate_field F E) (hK : K.fg) : P K := begin obtain ⟨S, rfl⟩ := hK, exact induction_on_adjoin_finset S P base (λ K x _ hK, ih K x hK), end lemma induction_on_adjoin [fd : finite_dimensional F E] (P : intermediate_field F E → Prop) (base : P ⊥) (ih : ∀ (K : intermediate_field F E) (x : E), P K → P (K⟮x⟯.restrict_scalars F)) (K : intermediate_field F E) : P K := begin letI : is_noetherian F E := is_noetherian.iff_fg.2 infer_instance, exact induction_on_adjoin_fg P base ih K K.fg_of_noetherian end end induction section alg_hom_mk_adjoin_splits variables (F E K : Type*) [field F] [field E] [field K] [algebra F E] [algebra F K] {S : set E} /-- Lifts `L → K` of `F → K` -/ def lifts := Σ (L : intermediate_field F E), (L →ₐ[F] K) variables {F E K} instance : partial_order (lifts F E K) := { le := λ x y, x.1 ≤ y.1 ∧ (∀ (s : x.1) (t : y.1), (s : E) = t → x.2 s = y.2 t), le_refl := λ x, ⟨le_refl x.1, λ s t hst, congr_arg x.2 (subtype.ext hst)⟩, le_trans := λ x y z hxy hyz, ⟨le_trans hxy.1 hyz.1, λ s u hsu, eq.trans (hxy.2 s ⟨s, hxy.1 s.mem⟩ rfl) (hyz.2 ⟨s, hxy.1 s.mem⟩ u hsu)⟩, le_antisymm := begin rintros ⟨x1, x2⟩ ⟨y1, y2⟩ ⟨hxy1, hxy2⟩ ⟨hyx1, hyx2⟩, obtain rfl : x1 = y1 := le_antisymm hxy1 hyx1, congr, exact alg_hom.ext (λ s, hxy2 s s rfl), end } noncomputable instance : order_bot (lifts F E K) := { bot := ⟨⊥, (algebra.of_id F K).comp (bot_equiv F E).to_alg_hom⟩, bot_le := λ x, ⟨bot_le, λ s t hst, begin cases intermediate_field.mem_bot.mp s.mem with u hu, rw [show s = (algebra_map F _) u, from subtype.ext hu.symm, alg_hom.commutes], rw [show t = (algebra_map F _) u, from subtype.ext (eq.trans hu hst).symm, alg_hom.commutes], end⟩ } noncomputable instance : inhabited (lifts F E K) := ⟨⊥⟩ lemma lifts.eq_of_le {x y : lifts F E K} (hxy : x ≤ y) (s : x.1) : x.2 s = y.2 ⟨s, hxy.1 s.mem⟩ := hxy.2 s ⟨s, hxy.1 s.mem⟩ rfl lemma lifts.exists_max_two {c : set (lifts F E K)} {x y : lifts F E K} (hc : is_chain (≤) c) (hx : x ∈ has_insert.insert ⊥ c) (hy : y ∈ has_insert.insert ⊥ c) : ∃ z : lifts F E K, z ∈ has_insert.insert ⊥ c ∧ x ≤ z ∧ y ≤ z := begin cases (hc.insert $ λ _ _ _, or.inl bot_le).total hx hy with hxy hyx, { exact ⟨y, hy, hxy, le_refl y⟩ }, { exact ⟨x, hx, le_refl x, hyx⟩ }, end lemma lifts.exists_max_three {c : set (lifts F E K)} {x y z : lifts F E K} (hc : is_chain (≤) c) (hx : x ∈ has_insert.insert ⊥ c) (hy : y ∈ has_insert.insert ⊥ c) (hz : z ∈ has_insert.insert ⊥ c) : ∃ w : lifts F E K, w ∈ has_insert.insert ⊥ c ∧ x ≤ w ∧ y ≤ w ∧ z ≤ w := begin obtain ⟨v, hv, hxv, hyv⟩ := lifts.exists_max_two hc hx hy, obtain ⟨w, hw, hzw, hvw⟩ := lifts.exists_max_two hc hz hv, exact ⟨w, hw, le_trans hxv hvw, le_trans hyv hvw, hzw⟩, end /-- An upper bound on a chain of lifts -/ def lifts.upper_bound_intermediate_field {c : set (lifts F E K)} (hc : is_chain (≤) c) : intermediate_field F E := { carrier := λ s, ∃ x : (lifts F E K), x ∈ has_insert.insert ⊥ c ∧ (s ∈ x.1 : Prop), zero_mem' := ⟨⊥, set.mem_insert ⊥ c, zero_mem ⊥⟩, one_mem' := ⟨⊥, set.mem_insert ⊥ c, one_mem ⊥⟩, neg_mem' := by { rintros _ ⟨x, y, h⟩, exact ⟨x, ⟨y, x.1.neg_mem h⟩⟩ }, inv_mem' := by { rintros _ ⟨x, y, h⟩, exact ⟨x, ⟨y, x.1.inv_mem h⟩⟩ }, add_mem' := by { rintros _ _ ⟨x, hx, ha⟩ ⟨y, hy, hb⟩, obtain ⟨z, hz, hxz, hyz⟩ := lifts.exists_max_two hc hx hy, exact ⟨z, hz, z.1.add_mem (hxz.1 ha) (hyz.1 hb)⟩ }, mul_mem' := by { rintros _ _ ⟨x, hx, ha⟩ ⟨y, hy, hb⟩, obtain ⟨z, hz, hxz, hyz⟩ := lifts.exists_max_two hc hx hy, exact ⟨z, hz, z.1.mul_mem (hxz.1 ha) (hyz.1 hb)⟩ }, algebra_map_mem' := λ s, ⟨⊥, set.mem_insert ⊥ c, algebra_map_mem ⊥ s⟩ } /-- The lift on the upper bound on a chain of lifts -/ noncomputable def lifts.upper_bound_alg_hom {c : set (lifts F E K)} (hc : is_chain (≤) c) : lifts.upper_bound_intermediate_field hc →ₐ[F] K := { to_fun := λ s, (classical.some s.mem).2 ⟨s, (classical.some_spec s.mem).2⟩, map_zero' := alg_hom.map_zero _, map_one' := alg_hom.map_one _, map_add' := λ s t, begin obtain ⟨w, hw, hxw, hyw, hzw⟩ := lifts.exists_max_three hc (classical.some_spec s.mem).1 (classical.some_spec t.mem).1 (classical.some_spec (s + t).mem).1, rw [lifts.eq_of_le hxw, lifts.eq_of_le hyw, lifts.eq_of_le hzw, ←w.2.map_add], refl, end, map_mul' := λ s t, begin obtain ⟨w, hw, hxw, hyw, hzw⟩ := lifts.exists_max_three hc (classical.some_spec s.mem).1 (classical.some_spec t.mem).1 (classical.some_spec (s * t).mem).1, rw [lifts.eq_of_le hxw, lifts.eq_of_le hyw, lifts.eq_of_le hzw, ←w.2.map_mul], refl, end, commutes' := λ _, alg_hom.commutes _ _ } /-- An upper bound on a chain of lifts -/ noncomputable def lifts.upper_bound {c : set (lifts F E K)} (hc : is_chain (≤) c) : lifts F E K := ⟨lifts.upper_bound_intermediate_field hc, lifts.upper_bound_alg_hom hc⟩ lemma lifts.exists_upper_bound (c : set (lifts F E K)) (hc : is_chain (≤) c) : ∃ ub, ∀ a ∈ c, a ≤ ub := ⟨lifts.upper_bound hc, begin intros x hx, split, { exact λ s hs, ⟨x, set.mem_insert_of_mem ⊥ hx, hs⟩ }, { intros s t hst, change x.2 s = (classical.some t.mem).2 ⟨t, (classical.some_spec t.mem).2⟩, obtain ⟨z, hz, hxz, hyz⟩ := lifts.exists_max_two hc (set.mem_insert_of_mem ⊥ hx) (classical.some_spec t.mem).1, rw [lifts.eq_of_le hxz, lifts.eq_of_le hyz], exact congr_arg z.2 (subtype.ext hst) }, end⟩ /-- Extend a lift `x : lifts F E K` to an element `s : E` whose conjugates are all in `K` -/ noncomputable def lifts.lift_of_splits (x : lifts F E K) {s : E} (h1 : is_integral F s) (h2 : (minpoly F s).splits (algebra_map F K)) : lifts F E K := let h3 : is_integral x.1 s := is_integral_of_is_scalar_tower h1 in let key : (minpoly x.1 s).splits x.2.to_ring_hom := splits_of_splits_of_dvd _ (map_ne_zero (minpoly.ne_zero h1)) ((splits_map_iff _ _).mpr (by {convert h2, exact ring_hom.ext (λ y, x.2.commutes y)})) (minpoly.dvd_map_of_is_scalar_tower _ _ _) in ⟨x.1⟮s⟯.restrict_scalars F, (@alg_hom_equiv_sigma F x.1 (x.1⟮s⟯.restrict_scalars F) K _ _ _ _ _ _ _ (intermediate_field.algebra x.1⟮s⟯) (is_scalar_tower.of_algebra_map_eq (λ _, rfl))).inv_fun ⟨x.2, (@alg_hom_adjoin_integral_equiv x.1 _ E _ _ s K _ x.2.to_ring_hom.to_algebra h3).inv_fun ⟨root_of_splits x.2.to_ring_hom key (ne_of_gt (minpoly.degree_pos h3)), by { simp_rw [mem_roots (map_ne_zero (minpoly.ne_zero h3)), is_root, ←eval₂_eq_eval_map], exact map_root_of_splits x.2.to_ring_hom key (ne_of_gt (minpoly.degree_pos h3)) }⟩⟩⟩ lemma lifts.le_lifts_of_splits (x : lifts F E K) {s : E} (h1 : is_integral F s) (h2 : (minpoly F s).splits (algebra_map F K)) : x ≤ x.lift_of_splits h1 h2 := ⟨λ z hz, algebra_map_mem x.1⟮s⟯ ⟨z, hz⟩, λ t u htu, eq.symm begin rw [←(show algebra_map x.1 x.1⟮s⟯ t = u, from subtype.ext htu)], letI : algebra x.1 K := x.2.to_ring_hom.to_algebra, exact (alg_hom.commutes _ t), end⟩ lemma lifts.mem_lifts_of_splits (x : lifts F E K) {s : E} (h1 : is_integral F s) (h2 : (minpoly F s).splits (algebra_map F K)) : s ∈ (x.lift_of_splits h1 h2).1 := mem_adjoin_simple_self x.1 s lemma lifts.exists_lift_of_splits (x : lifts F E K) {s : E} (h1 : is_integral F s) (h2 : (minpoly F s).splits (algebra_map F K)) : ∃ y, x ≤ y ∧ s ∈ y.1 := ⟨x.lift_of_splits h1 h2, x.le_lifts_of_splits h1 h2, x.mem_lifts_of_splits h1 h2⟩ lemma alg_hom_mk_adjoin_splits (hK : ∀ s ∈ S, is_integral F (s : E) ∧ (minpoly F s).splits (algebra_map F K)) : nonempty (adjoin F S →ₐ[F] K) := begin obtain ⟨x : lifts F E K, hx⟩ := zorn_partial_order lifts.exists_upper_bound, refine ⟨alg_hom.mk (λ s, x.2 ⟨s, adjoin_le_iff.mpr (λ s hs, _) s.mem⟩) x.2.map_one (λ s t, x.2.map_mul ⟨s, _⟩ ⟨t, _⟩) x.2.map_zero (λ s t, x.2.map_add ⟨s, _⟩ ⟨t, _⟩) x.2.commutes⟩, rcases (x.exists_lift_of_splits (hK s hs).1 (hK s hs).2) with ⟨y, h1, h2⟩, rwa hx y h1 at h2 end lemma alg_hom_mk_adjoin_splits' (hS : adjoin F S = ⊤) (hK : ∀ x ∈ S, is_integral F (x : E) ∧ (minpoly F x).splits (algebra_map F K)) : nonempty (E →ₐ[F] K) := begin cases alg_hom_mk_adjoin_splits hK with ϕ, rw hS at ϕ, exact ⟨ϕ.comp top_equiv.symm.to_alg_hom⟩, end end alg_hom_mk_adjoin_splits section supremum variables {K L : Type*} [field K] [field L] [algebra K L] (E1 E2 : intermediate_field K L) lemma le_sup_to_subalgebra : E1.to_subalgebra ⊔ E2.to_subalgebra ≤ (E1 ⊔ E2).to_subalgebra := sup_le (show E1 ≤ E1 ⊔ E2, from le_sup_left) (show E2 ≤ E1 ⊔ E2, from le_sup_right) lemma sup_to_subalgebra [h1 : finite_dimensional K E1] [h2 : finite_dimensional K E2] : (E1 ⊔ E2).to_subalgebra = E1.to_subalgebra ⊔ E2.to_subalgebra := begin let S1 := E1.to_subalgebra, let S2 := E2.to_subalgebra, refine le_antisymm (show _ ≤ (S1 ⊔ S2).to_intermediate_field _, from (sup_le (show S1 ≤ _, from le_sup_left) (show S2 ≤ _, from le_sup_right))) (le_sup_to_subalgebra E1 E2), suffices : is_field ↥(S1 ⊔ S2), { intros x hx, by_cases hx' : (⟨x, hx⟩ : S1 ⊔ S2) = 0, { rw [←subtype.coe_mk x hx, hx', subalgebra.coe_zero, inv_zero], exact (S1 ⊔ S2).zero_mem }, { obtain ⟨y, h⟩ := this.mul_inv_cancel hx', exact (congr_arg (∈ S1 ⊔ S2) $ eq_inv_of_mul_eq_one_right $ subtype.ext_iff.mp h).mp y.2 } }, exact is_field_of_is_integral_of_is_field' (is_integral_sup.mpr ⟨algebra.is_integral_of_finite K E1, algebra.is_integral_of_finite K E2⟩) (field.to_is_field K), end instance finite_dimensional_sup [h1 : finite_dimensional K E1] [h2 : finite_dimensional K E2] : finite_dimensional K ↥(E1 ⊔ E2) := begin let g := algebra.tensor_product.product_map E1.val E2.val, suffices : g.range = (E1 ⊔ E2).to_subalgebra, { have h : finite_dimensional K g.range.to_submodule := g.to_linear_map.finite_dimensional_range, rwa this at h }, rw [algebra.tensor_product.product_map_range, E1.range_val, E2.range_val, sup_to_subalgebra], end instance finite_dimensional_supr_of_finite {ι : Type*} {t : ι → intermediate_field K L} [h : finite ι] [Π i, finite_dimensional K (t i)] : finite_dimensional K (⨆ i, t i : intermediate_field K L) := begin rw ← supr_univ, let P : set ι → Prop := λ s, finite_dimensional K (⨆ i ∈ s, t i : intermediate_field K L), change P set.univ, apply set.finite.induction_on, { exact set.finite_univ }, all_goals { dsimp only [P] }, { rw supr_emptyset, exact (bot_equiv K L).symm.to_linear_equiv.finite_dimensional }, { intros _ s _ _ hs, rw supr_insert, exactI intermediate_field.finite_dimensional_sup _ _ }, end instance finite_dimensional_supr_of_finset {ι : Type*} {f : ι → intermediate_field K L} {s : finset ι} [h : Π i ∈ s, finite_dimensional K (f i)] : finite_dimensional K (⨆ i ∈ s, f i : intermediate_field K L) := begin haveI : Π i : {i // i ∈ s}, finite_dimensional K (f i) := λ i, h i i.2, have : (⨆ i ∈ s, f i) = ⨆ i : {i // i ∈ s}, f i := le_antisymm (supr_le (λ i, supr_le (λ h, le_supr (λ i : {i // i ∈ s}, f i) ⟨i, h⟩))) (supr_le (λ i, le_supr_of_le i (le_supr_of_le i.2 le_rfl))), exact this.symm ▸ intermediate_field.finite_dimensional_supr_of_finite, end /-- A compositum of algebraic extensions is algebraic -/ lemma is_algebraic_supr {ι : Type*} {f : ι → intermediate_field K L} (h : ∀ i, algebra.is_algebraic K (f i)) : algebra.is_algebraic K (⨆ i, f i : intermediate_field K L) := begin rintros ⟨x, hx⟩, obtain ⟨s, hx⟩ := exists_finset_of_mem_supr' hx, rw [is_algebraic_iff, subtype.coe_mk, ←subtype.coe_mk x hx, ←is_algebraic_iff], haveI : ∀ i : (Σ i, f i), finite_dimensional K K⟮(i.2 : L)⟯ := λ ⟨i, x⟩, adjoin.finite_dimensional (is_integral_iff.1 (is_algebraic_iff_is_integral.1 (h i x))), apply algebra.is_algebraic_of_finite, end end supremum end intermediate_field section power_basis variables {K L : Type*} [field K] [field L] [algebra K L] namespace power_basis open intermediate_field /-- `pb.equiv_adjoin_simple` is the equivalence between `K⟮pb.gen⟯` and `L` itself. -/ noncomputable def equiv_adjoin_simple (pb : power_basis K L) : K⟮pb.gen⟯ ≃ₐ[K] L := (adjoin.power_basis pb.is_integral_gen).equiv_of_minpoly pb (minpoly.eq_of_algebra_map_eq (algebra_map K⟮pb.gen⟯ L).injective (adjoin.power_basis pb.is_integral_gen).is_integral_gen (by rw [adjoin.power_basis_gen, adjoin_simple.algebra_map_gen])) @[simp] lemma equiv_adjoin_simple_aeval (pb : power_basis K L) (f : K[X]) : pb.equiv_adjoin_simple (aeval (adjoin_simple.gen K pb.gen) f) = aeval pb.gen f := equiv_of_minpoly_aeval _ pb _ f @[simp] lemma equiv_adjoin_simple_gen (pb : power_basis K L) : pb.equiv_adjoin_simple (adjoin_simple.gen K pb.gen) = pb.gen := equiv_of_minpoly_gen _ pb _ @[simp] lemma equiv_adjoin_simple_symm_aeval (pb : power_basis K L) (f : K[X]) : pb.equiv_adjoin_simple.symm (aeval pb.gen f) = aeval (adjoin_simple.gen K pb.gen) f := by rw [equiv_adjoin_simple, equiv_of_minpoly_symm, equiv_of_minpoly_aeval, adjoin.power_basis_gen] @[simp] lemma equiv_adjoin_simple_symm_gen (pb : power_basis K L) : pb.equiv_adjoin_simple.symm pb.gen = (adjoin_simple.gen K pb.gen) := by rw [equiv_adjoin_simple, equiv_of_minpoly_symm, equiv_of_minpoly_gen, adjoin.power_basis_gen] end power_basis end power_basis
666e282e82b3ab3abdd529932f68b40b225e0509
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/sites/sieves.lean
fcb14e3bb6273b8948a16ef711132ab503f2a3e5
[ "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
25,047
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta, E. W. Ayers -/ import order.complete_lattice import category_theory.over import category_theory.yoneda import category_theory.limits.shapes.pullbacks import data.set.lattice /-! # Theory of sieves - For an object `X` of a category `C`, a `sieve X` is a set of morphisms to `X` which is closed under left-composition. - The complete lattice structure on sieves is given, as well as the Galois insertion given by downward-closing. - A `sieve X` (functorially) induces a presheaf on `C` together with a monomorphism to the yoneda embedding of `X`. ## Tags sieve, pullback -/ universes v₁ v₂ v₃ u₁ u₂ u₃ namespace category_theory open category limits variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D] (F : C ⥤ D) variables {X Y Z : C} (f : Y ⟶ X) /-- A set of arrows all with codomain `X`. -/ @[derive complete_lattice] def presieve (X : C) := Π ⦃Y⦄, set (Y ⟶ X) namespace presieve instance : inhabited (presieve X) := ⟨⊤⟩ /-- Given a sieve `S` on `X : C`, its associated diagram `S.diagram` is defined to be the natural functor from the full subcategory of the over category `C/X` consisting of arrows in `S` to `C`. -/ abbreviation diagram (S : presieve X) : full_subcategory (λ (f : over X), S f.hom) ⥤ C := full_subcategory_inclusion _ ⋙ over.forget X /-- Given a sieve `S` on `X : C`, its associated cocone `S.cocone` is defined to be the natural cocone over the diagram defined above with cocone point `X`. -/ abbreviation cocone (S : presieve X) : cocone S.diagram := (over.forget_cocone X).whisker (full_subcategory_inclusion _) /-- Given a set of arrows `S` all with codomain `X`, and a set of arrows with codomain `Y` for each `f : Y ⟶ X` in `S`, produce a set of arrows with codomain `X`: `{ g ≫ f | (f : Y ⟶ X) ∈ S, (g : Z ⟶ Y) ∈ R f }`. -/ def bind (S : presieve X) (R : Π ⦃Y⦄ ⦃f : Y ⟶ X⦄, S f → presieve Y) : presieve X := λ Z h, ∃ (Y : C) (g : Z ⟶ Y) (f : Y ⟶ X) (H : S f), R H g ∧ g ≫ f = h @[simp] lemma bind_comp {S : presieve X} {R : Π ⦃Y : C⦄ ⦃f : Y ⟶ X⦄, S f → presieve Y} {g : Z ⟶ Y} (h₁ : S f) (h₂ : R h₁ g) : bind S R (g ≫ f) := ⟨_, _, _, h₁, h₂, rfl⟩ /-- The singleton presieve. -/ -- Note we can't make this into `has_singleton` because of the out-param. inductive singleton : presieve X | mk : singleton f @[simp] lemma singleton_eq_iff_domain (f g : Y ⟶ X) : singleton f g ↔ f = g := begin split, { rintro ⟨a, rfl⟩, refl }, { rintro rfl, apply singleton.mk, } end lemma singleton_self : singleton f f := singleton.mk /-- Pullback a set of arrows with given codomain along a fixed map, by taking the pullback in the category. This is not the same as the arrow set of `sieve.pullback`, but there is a relation between them in `pullback_arrows_comm`. -/ inductive pullback_arrows [has_pullbacks C] (R : presieve X) : presieve Y | mk (Z : C) (h : Z ⟶ X) : R h → pullback_arrows (pullback.snd : pullback h f ⟶ Y) lemma pullback_singleton [has_pullbacks C] (g : Z ⟶ X) : pullback_arrows f (singleton g) = singleton (pullback.snd : pullback g f ⟶ _) := begin ext W h, split, { rintro ⟨W, _, _, _⟩, exact singleton.mk }, { rintro ⟨_⟩, exact pullback_arrows.mk Z g singleton.mk } end /-- Construct the presieve given by the family of arrows indexed by `ι`. -/ inductive of_arrows {ι : Type*} (Y : ι → C) (f : Π i, Y i ⟶ X) : presieve X | mk (i : ι) : of_arrows (f i) lemma of_arrows_punit : of_arrows _ (λ _ : punit, f) = singleton f := begin ext Y g, split, { rintro ⟨_⟩, apply singleton.mk }, { rintro ⟨_⟩, exact of_arrows.mk punit.star }, end lemma of_arrows_pullback [has_pullbacks C] {ι : Type*} (Z : ι → C) (g : Π (i : ι), Z i ⟶ X) : of_arrows (λ i, pullback (g i) f) (λ i, pullback.snd) = pullback_arrows f (of_arrows Z g) := begin ext T h, split, { rintro ⟨hk⟩, exact pullback_arrows.mk _ _ (of_arrows.mk hk) }, { rintro ⟨W, k, hk₁⟩, cases hk₁ with i hi, apply of_arrows.mk }, end lemma of_arrows_bind {ι : Type*} (Z : ι → C) (g : Π (i : ι), Z i ⟶ X) (j : Π ⦃Y⦄ (f : Y ⟶ X), of_arrows Z g f → Type*) (W : Π ⦃Y⦄ (f : Y ⟶ X) H, j f H → C) (k : Π ⦃Y⦄ (f : Y ⟶ X) H i, W f H i ⟶ Y) : (of_arrows Z g).bind (λ Y f H, of_arrows (W f H) (k f H)) = of_arrows (λ (i : Σ i, j _ (of_arrows.mk i)), W (g i.1) _ i.2) (λ ij, k (g ij.1) _ ij.2 ≫ g ij.1) := begin ext Y f, split, { rintro ⟨_, _, _, ⟨i⟩, ⟨i'⟩, rfl⟩, exact of_arrows.mk (sigma.mk _ _) }, { rintro ⟨i⟩, exact bind_comp _ (of_arrows.mk _) (of_arrows.mk _) } end /-- Given a presieve on `F(X)`, we can define a presieve on `X` by taking the preimage via `F`. -/ def functor_pullback (R : presieve (F.obj X)) : presieve X := λ _ f, R (F.map f) @[simp] lemma functor_pullback_mem (R : presieve (F.obj X)) {Y} (f : Y ⟶ X) : R.functor_pullback F f ↔ R (F.map f) := iff.rfl @[simp] lemma functor_pullback_id (R : presieve X) : R.functor_pullback (𝟭 _) = R := rfl section functor_pushforward variables {E : Type u₃} [category.{v₃} E] (G : D ⥤ E) /-- Given a presieve on `X`, we can define a presieve on `F(X)` (which is actually a sieve) by taking the sieve generated by the image via `F`. -/ def functor_pushforward (S : presieve X) : presieve (F.obj X) := λ Y f, ∃ (Z : C) (g : Z ⟶ X) (h : Y ⟶ F.obj Z), S g ∧ f = h ≫ F.map g /-- An auxillary definition in order to fix the choice of the preimages between various definitions. -/ @[nolint has_nonempty_instance] structure functor_pushforward_structure (S : presieve X) {Y} (f : Y ⟶ F.obj X) := (preobj : C) (premap : preobj ⟶ X) (lift : Y ⟶ F.obj preobj) (cover : S premap) (fac : f = lift ≫ F.map premap) /-- The fixed choice of a preimage. -/ noncomputable def get_functor_pushforward_structure {F : C ⥤ D} {S : presieve X} {Y : D} {f : Y ⟶ F.obj X} (h : S.functor_pushforward F f) : functor_pushforward_structure F S f := by { choose Z f' g h₁ h using h, exact ⟨Z, f', g, h₁, h⟩ } lemma functor_pushforward_comp (R : presieve X) : R.functor_pushforward (F ⋙ G) = (R.functor_pushforward F).functor_pushforward G := begin ext x f, split, { rintro ⟨X, f₁, g₁, h₁, rfl⟩, exact ⟨F.obj X, F.map f₁, g₁, ⟨X, f₁, 𝟙 _, h₁, by simp⟩, rfl⟩ }, { rintro ⟨X, f₁, g₁, ⟨X', f₂, g₂, h₁, rfl⟩, rfl⟩, use ⟨X', f₂, g₁ ≫ G.map g₂, h₁, by simp⟩ } end lemma image_mem_functor_pushforward (R : presieve X) {f : Y ⟶ X} (h : R f) : R.functor_pushforward F (F.map f) := ⟨Y, f, 𝟙 _, h, by simp⟩ end functor_pushforward end presieve /-- For an object `X` of a category `C`, a `sieve X` is a set of morphisms to `X` which is closed under left-composition. -/ structure sieve {C : Type u₁} [category.{v₁} C] (X : C) := (arrows : presieve X) (downward_closed' : ∀ {Y Z f} (hf : arrows f) (g : Z ⟶ Y), arrows (g ≫ f)) namespace sieve instance : has_coe_to_fun (sieve X) (λ _, presieve X) := ⟨sieve.arrows⟩ initialize_simps_projections sieve (arrows → apply) variables {S R : sieve X} @[simp, priority 100] lemma downward_closed (S : sieve X) {f : Y ⟶ X} (hf : S f) (g : Z ⟶ Y) : S (g ≫ f) := S.downward_closed' hf g lemma arrows_ext : Π {R S : sieve X}, R.arrows = S.arrows → R = S | ⟨Ra, _⟩ ⟨Sa, _⟩ rfl := rfl @[ext] protected lemma ext {R S : sieve X} (h : ∀ ⦃Y⦄ (f : Y ⟶ X), R f ↔ S f) : R = S := arrows_ext $ funext $ λ x, funext $ λ f, propext $ h f protected lemma ext_iff {R S : sieve X} : R = S ↔ (∀ ⦃Y⦄ (f : Y ⟶ X), R f ↔ S f) := ⟨λ h Y f, h ▸ iff.rfl, sieve.ext⟩ open lattice /-- The supremum of a collection of sieves: the union of them all. -/ protected def Sup (𝒮 : set (sieve X)) : (sieve X) := { arrows := λ Y, {f | ∃ S ∈ 𝒮, sieve.arrows S f}, downward_closed' := λ Y Z f, by { rintro ⟨S, hS, hf⟩ g, exact ⟨S, hS, S.downward_closed hf _⟩ } } /-- The infimum of a collection of sieves: the intersection of them all. -/ protected def Inf (𝒮 : set (sieve X)) : (sieve X) := { arrows := λ Y, {f | ∀ S ∈ 𝒮, sieve.arrows S f}, downward_closed' := λ Y Z f hf g S H, S.downward_closed (hf S H) g } /-- The union of two sieves is a sieve. -/ protected def union (S R : sieve X) : sieve X := { arrows := λ Y f, S f ∨ R f, downward_closed' := by { rintros Y Z f (h | h) g; simp [h] } } /-- The intersection of two sieves is a sieve. -/ protected def inter (S R : sieve X) : sieve X := { arrows := λ Y f, S f ∧ R f, downward_closed' := by { rintros Y Z f ⟨h₁, h₂⟩ g, simp [h₁, h₂] } } /-- Sieves on an object `X` form a complete lattice. We generate this directly rather than using the galois insertion for nicer definitional properties. -/ instance : complete_lattice (sieve X) := { le := λ S R, ∀ ⦃Y⦄ (f : Y ⟶ X), S f → R f, le_refl := λ S f q, id, le_trans := λ S₁ S₂ S₃ S₁₂ S₂₃ Y f h, S₂₃ _ (S₁₂ _ h), le_antisymm := λ S R p q, sieve.ext (λ Y f, ⟨p _, q _⟩), top := { arrows := λ _, set.univ, downward_closed' := λ Y Z f g h, ⟨⟩ }, bot := { arrows := λ _, ∅, downward_closed' := λ _ _ _ p _, false.elim p }, sup := sieve.union, inf := sieve.inter, Sup := sieve.Sup, Inf := sieve.Inf, le_Sup := λ 𝒮 S hS Y f hf, ⟨S, hS, hf⟩, Sup_le := λ ℰ S hS Y f, by { rintro ⟨R, hR, hf⟩, apply hS R hR _ hf }, Inf_le := λ _ _ hS _ _ h, h _ hS, le_Inf := λ _ _ hS _ _ hf _ hR, hS _ hR _ hf, le_sup_left := λ _ _ _ _, or.inl, le_sup_right := λ _ _ _ _, or.inr, sup_le := λ _ _ _ a b _ _ hf, hf.elim (a _) (b _), inf_le_left := λ _ _ _ _, and.left, inf_le_right := λ _ _ _ _, and.right, le_inf := λ _ _ _ p q _ _ z, ⟨p _ z, q _ z⟩, le_top := λ _ _ _ _, trivial, bot_le := λ _ _ _, false.elim } /-- The maximal sieve always exists. -/ instance sieve_inhabited : inhabited (sieve X) := ⟨⊤⟩ @[simp] lemma Inf_apply {Ss : set (sieve X)} {Y} (f : Y ⟶ X) : Inf Ss f ↔ ∀ (S : sieve X) (H : S ∈ Ss), S f := iff.rfl @[simp] lemma Sup_apply {Ss : set (sieve X)} {Y} (f : Y ⟶ X) : Sup Ss f ↔ ∃ (S : sieve X) (H : S ∈ Ss), S f := iff.rfl @[simp] lemma inter_apply {R S : sieve X} {Y} (f : Y ⟶ X) : (R ⊓ S) f ↔ R f ∧ S f := iff.rfl @[simp] lemma union_apply {R S : sieve X} {Y} (f : Y ⟶ X) : (R ⊔ S) f ↔ R f ∨ S f := iff.rfl @[simp] lemma top_apply (f : Y ⟶ X) : (⊤ : sieve X) f := trivial /-- Generate the smallest sieve containing the given set of arrows. -/ @[simps] def generate (R : presieve X) : sieve X := { arrows := λ Z f, ∃ Y (h : Z ⟶ Y) (g : Y ⟶ X), R g ∧ h ≫ g = f, downward_closed' := begin rintro Y Z _ ⟨W, g, f, hf, rfl⟩ h, exact ⟨_, h ≫ g, _, hf, by simp⟩, end } /-- Given a presieve on `X`, and a sieve on each domain of an arrow in the presieve, we can bind to produce a sieve on `X`. -/ @[simps] def bind (S : presieve X) (R : Π ⦃Y⦄ ⦃f : Y ⟶ X⦄, S f → sieve Y) : sieve X := { arrows := S.bind (λ Y f h, R h), downward_closed' := begin rintro Y Z f ⟨W, f, h, hh, hf, rfl⟩ g, exact ⟨_, g ≫ f, _, hh, by simp [hf]⟩, end } open order lattice lemma sets_iff_generate (R : presieve X) (S : sieve X) : generate R ≤ S ↔ R ≤ S := ⟨λ H Y g hg, H _ ⟨_, 𝟙 _, _, hg, id_comp _⟩, λ ss Y f, begin rintro ⟨Z, f, g, hg, rfl⟩, exact S.downward_closed (ss Z hg) f, end⟩ /-- Show that there is a galois insertion (generate, set_over). -/ def gi_generate : galois_insertion (generate : presieve X → sieve X) arrows := { gc := sets_iff_generate, choice := λ 𝒢 _, generate 𝒢, choice_eq := λ _ _, rfl, le_l_u := λ S Y f hf, ⟨_, 𝟙 _, _, hf, id_comp _⟩ } lemma le_generate (R : presieve X) : R ≤ generate R := gi_generate.gc.le_u_l R @[simp] lemma generate_sieve (S : sieve X) : generate S = S := gi_generate.l_u_eq S /-- If the identity arrow is in a sieve, the sieve is maximal. -/ lemma id_mem_iff_eq_top : S (𝟙 X) ↔ S = ⊤ := ⟨λ h, top_unique $ λ Y f _, by simpa using downward_closed _ h f, λ h, h.symm ▸ trivial⟩ /-- If an arrow set contains a split epi, it generates the maximal sieve. -/ lemma generate_of_contains_is_split_epi {R : presieve X} (f : Y ⟶ X) [is_split_epi f] (hf : R f) : generate R = ⊤ := begin rw ← id_mem_iff_eq_top, exact ⟨_, section_ f, f, hf, by simp⟩, end @[simp] lemma generate_of_singleton_is_split_epi (f : Y ⟶ X) [is_split_epi f] : generate (presieve.singleton f) = ⊤ := generate_of_contains_is_split_epi f (presieve.singleton_self _) @[simp] lemma generate_top : generate (⊤ : presieve X) = ⊤ := generate_of_contains_is_split_epi (𝟙 _) ⟨⟩ /-- Given a morphism `h : Y ⟶ X`, send a sieve S on X to a sieve on Y as the inverse image of S with `_ ≫ h`. That is, `sieve.pullback S h := (≫ h) '⁻¹ S`. -/ @[simps] def pullback (h : Y ⟶ X) (S : sieve X) : sieve Y := { arrows := λ Y sl, S (sl ≫ h), downward_closed' := λ Z W f g h, by simp [g] } @[simp] lemma pullback_id : S.pullback (𝟙 _) = S := by simp [sieve.ext_iff] @[simp] lemma pullback_top {f : Y ⟶ X} : (⊤ : sieve X).pullback f = ⊤ := top_unique (λ _ g, id) lemma pullback_comp {f : Y ⟶ X} {g : Z ⟶ Y} (S : sieve X) : S.pullback (g ≫ f) = (S.pullback f).pullback g := by simp [sieve.ext_iff] @[simp] lemma pullback_inter {f : Y ⟶ X} (S R : sieve X) : (S ⊓ R).pullback f = S.pullback f ⊓ R.pullback f := by simp [sieve.ext_iff] lemma pullback_eq_top_iff_mem (f : Y ⟶ X) : S f ↔ S.pullback f = ⊤ := by rw [← id_mem_iff_eq_top, pullback_apply, id_comp] lemma pullback_eq_top_of_mem (S : sieve X) {f : Y ⟶ X} : S f → S.pullback f = ⊤ := (pullback_eq_top_iff_mem f).1 /-- Push a sieve `R` on `Y` forward along an arrow `f : Y ⟶ X`: `gf : Z ⟶ X` is in the sieve if `gf` factors through some `g : Z ⟶ Y` which is in `R`. -/ @[simps] def pushforward (f : Y ⟶ X) (R : sieve Y) : sieve X := { arrows := λ Z gf, ∃ g, g ≫ f = gf ∧ R g, downward_closed' := λ Z₁ Z₂ g ⟨j, k, z⟩ h, ⟨h ≫ j, by simp [k], by simp [z]⟩ } lemma pushforward_apply_comp {R : sieve Y} {Z : C} {g : Z ⟶ Y} (hg : R g) (f : Y ⟶ X) : R.pushforward f (g ≫ f) := ⟨g, rfl, hg⟩ lemma pushforward_comp {f : Y ⟶ X} {g : Z ⟶ Y} (R : sieve Z) : R.pushforward (g ≫ f) = (R.pushforward g).pushforward f := sieve.ext (λ W h, ⟨λ ⟨f₁, hq, hf₁⟩, ⟨f₁ ≫ g, by simpa, f₁, rfl, hf₁⟩, λ ⟨y, hy, z, hR, hz⟩, ⟨z, by rwa reassoc_of hR, hz⟩⟩) lemma galois_connection (f : Y ⟶ X) : galois_connection (sieve.pushforward f) (sieve.pullback f) := λ S R, ⟨λ hR Z g hg, hR _ ⟨g, rfl, hg⟩, λ hS Z g ⟨h, hg, hh⟩, hg ▸ hS h hh⟩ lemma pullback_monotone (f : Y ⟶ X) : monotone (sieve.pullback f) := (galois_connection f).monotone_u lemma pushforward_monotone (f : Y ⟶ X) : monotone (sieve.pushforward f) := (galois_connection f).monotone_l lemma le_pushforward_pullback (f : Y ⟶ X) (R : sieve Y) : R ≤ (R.pushforward f).pullback f := (galois_connection f).le_u_l _ lemma pullback_pushforward_le (f : Y ⟶ X) (R : sieve X) : (R.pullback f).pushforward f ≤ R := (galois_connection f).l_u_le _ lemma pushforward_union {f : Y ⟶ X} (S R : sieve Y) : (S ⊔ R).pushforward f = S.pushforward f ⊔ R.pushforward f := (galois_connection f).l_sup lemma pushforward_le_bind_of_mem (S : presieve X) (R : Π ⦃Y : C⦄ ⦃f : Y ⟶ X⦄, S f → sieve Y) (f : Y ⟶ X) (h : S f) : (R h).pushforward f ≤ bind S R := begin rintro Z _ ⟨g, rfl, hg⟩, exact ⟨_, g, f, h, hg, rfl⟩, end lemma le_pullback_bind (S : presieve X) (R : Π ⦃Y : C⦄ ⦃f : Y ⟶ X⦄, S f → sieve Y) (f : Y ⟶ X) (h : S f) : R h ≤ (bind S R).pullback f := begin rw ← galois_connection f, apply pushforward_le_bind_of_mem, end /-- If `f` is a monomorphism, the pushforward-pullback adjunction on sieves is coreflective. -/ def galois_coinsertion_of_mono (f : Y ⟶ X) [mono f] : galois_coinsertion (sieve.pushforward f) (sieve.pullback f) := begin apply (galois_connection f).to_galois_coinsertion, rintros S Z g ⟨g₁, hf, hg₁⟩, rw cancel_mono f at hf, rwa ← hf, end /-- If `f` is a split epi, the pushforward-pullback adjunction on sieves is reflective. -/ def galois_insertion_of_is_split_epi (f : Y ⟶ X) [is_split_epi f] : galois_insertion (sieve.pushforward f) (sieve.pullback f) := begin apply (galois_connection f).to_galois_insertion, intros S Z g hg, refine ⟨g ≫ section_ f, by simpa⟩, end lemma pullback_arrows_comm [has_pullbacks C] {X Y : C} (f : Y ⟶ X) (R : presieve X) : sieve.generate (R.pullback_arrows f) = (sieve.generate R).pullback f := begin ext Z g, split, { rintro ⟨_, h, k, hk, rfl⟩, cases hk with W g hg, change (sieve.generate R).pullback f (h ≫ pullback.snd), rw [sieve.pullback_apply, assoc, ← pullback.condition, ← assoc], exact sieve.downward_closed _ (sieve.le_generate R W hg) (h ≫ pullback.fst)}, { rintro ⟨W, h, k, hk, comm⟩, exact ⟨_, _, _, presieve.pullback_arrows.mk _ _ hk, pullback.lift_snd _ _ comm⟩ }, end section functor variables {E : Type u₃} [category.{v₃} E] (G : D ⥤ E) /-- If `R` is a sieve, then the `category_theory.presieve.functor_pullback` of `R` is actually a sieve. -/ @[simps] def functor_pullback (R : sieve (F.obj X)) : sieve X := { arrows := presieve.functor_pullback F R, downward_closed' := λ _ _ f hf g, begin unfold presieve.functor_pullback, rw F.map_comp, exact R.downward_closed hf (F.map g), end } @[simp] lemma functor_pullback_arrows (R : sieve (F.obj X)) : (R.functor_pullback F).arrows = R.arrows.functor_pullback F := rfl @[simp] lemma functor_pullback_id (R : sieve X) : R.functor_pullback (𝟭 _) = R := by { ext, refl } lemma functor_pullback_comp (R : sieve ((F ⋙ G).obj X)) : R.functor_pullback (F ⋙ G) = (R.functor_pullback G).functor_pullback F := by { ext, refl } lemma functor_pushforward_extend_eq {R : presieve X} : (generate R).arrows.functor_pushforward F = R.functor_pushforward F := begin ext Y f, split, { rintro ⟨X', g, f', ⟨X'', g', f'', h₁, rfl⟩, rfl⟩, exact ⟨X'', f'', f' ≫ F.map g', h₁, by simp⟩ }, { rintro ⟨X', g, f', h₁, h₂⟩, exact ⟨X', g, f', le_generate R _ h₁, h₂⟩ } end /-- The sieve generated by the image of `R` under `F`. -/ @[simps] def functor_pushforward (R : sieve X) : sieve (F.obj X) := { arrows := R.arrows.functor_pushforward F, downward_closed' := λ Y Z f h g, by { obtain ⟨X, α, β, hα, rfl⟩ := h, exact ⟨X, α, g ≫ β, hα, by simp⟩ } } @[simp] lemma functor_pushforward_id (R : sieve X) : R.functor_pushforward (𝟭 _) = R := begin ext X f, split, { intro hf, obtain ⟨X, g, h, hg, rfl⟩ := hf, exact R.downward_closed hg h, }, { intro hf, exact ⟨X, f, 𝟙 _, hf, by simp⟩ } end lemma functor_pushforward_comp (R : sieve X) : R.functor_pushforward (F ⋙ G) = (R.functor_pushforward F).functor_pushforward G := by { ext, simpa [R.arrows.functor_pushforward_comp F G] } lemma functor_galois_connection (X : C) : _root_.galois_connection (sieve.functor_pushforward F : sieve X → sieve (F.obj X)) (sieve.functor_pullback F) := begin intros R S, split, { intros hle X f hf, apply hle, refine ⟨X, f, 𝟙 _, hf, _⟩, rw id_comp, }, { rintros hle Y f ⟨X, g, h, hg, rfl⟩, apply sieve.downward_closed S, exact hle g hg, } end lemma functor_pullback_monotone (X : C) : monotone (sieve.functor_pullback F : sieve (F.obj X) → sieve X) := (functor_galois_connection F X).monotone_u lemma functor_pushforward_monotone (X : C) : monotone (sieve.functor_pushforward F : sieve X → sieve (F.obj X)) := (functor_galois_connection F X).monotone_l lemma le_functor_pushforward_pullback (R : sieve X) : R ≤ (R.functor_pushforward F).functor_pullback F := (functor_galois_connection F X).le_u_l _ lemma functor_pullback_pushforward_le (R : sieve (F.obj X)) : (R.functor_pullback F).functor_pushforward F ≤ R := (functor_galois_connection F X).l_u_le _ lemma functor_pushforward_union (S R : sieve X) : (S ⊔ R).functor_pushforward F = S.functor_pushforward F ⊔ R.functor_pushforward F := (functor_galois_connection F X).l_sup lemma functor_pullback_union (S R : sieve (F.obj X)) : (S ⊔ R).functor_pullback F = S.functor_pullback F ⊔ R.functor_pullback F := rfl lemma functor_pullback_inter (S R : sieve (F.obj X)) : (S ⊓ R).functor_pullback F = S.functor_pullback F ⊓ R.functor_pullback F := rfl @[simp] lemma functor_pushforward_bot (F : C ⥤ D) (X : C) : (⊥ : sieve X).functor_pushforward F = ⊥ := (functor_galois_connection F X).l_bot @[simp] lemma functor_pushforward_top (F : C ⥤ D) (X : C) : (⊤ : sieve X).functor_pushforward F = ⊤ := begin refine (generate_sieve _).symm.trans _, apply generate_of_contains_is_split_epi (𝟙 (F.obj X)), refine ⟨X, 𝟙 _, 𝟙 _, trivial, by simp⟩ end @[simp] lemma functor_pullback_bot (F : C ⥤ D) (X : C) : (⊥ : sieve (F.obj X)).functor_pullback F = ⊥ := rfl @[simp] lemma functor_pullback_top (F : C ⥤ D) (X : C) : (⊤ : sieve (F.obj X)).functor_pullback F = ⊤ := rfl lemma image_mem_functor_pushforward (R : sieve X) {V} {f : V ⟶ X} (h : R f) : R.functor_pushforward F (F.map f) := ⟨V, f, 𝟙 _, h, by simp⟩ /-- When `F` is essentially surjective and full, the galois connection is a galois insertion. -/ def ess_surj_full_functor_galois_insertion [ess_surj F] [full F] (X : C) : galois_insertion (sieve.functor_pushforward F : sieve X → sieve (F.obj X)) (sieve.functor_pullback F) := begin apply (functor_galois_connection F X).to_galois_insertion, intros S Y f hf, refine ⟨_, F.preimage ((F.obj_obj_preimage_iso Y).hom ≫ f), (F.obj_obj_preimage_iso Y).inv, _⟩, simpa using S.downward_closed hf _, end /-- When `F` is fully faithful, the galois connection is a galois coinsertion. -/ def fully_faithful_functor_galois_coinsertion [full F] [faithful F] (X : C) : galois_coinsertion (sieve.functor_pushforward F : sieve X → sieve (F.obj X)) (sieve.functor_pullback F) := begin apply (functor_galois_connection F X).to_galois_coinsertion, rintros S Y f ⟨Z, g, h, h₁, h₂⟩, rw [←F.image_preimage h, ←F.map_comp] at h₂, rw F.map_injective h₂, exact S.downward_closed h₁ _, end end functor /-- A sieve induces a presheaf. -/ @[simps] def functor (S : sieve X) : Cᵒᵖ ⥤ Type v₁ := { obj := λ Y, {g : Y.unop ⟶ X // S g}, map := λ Y Z f g, ⟨f.unop ≫ g.1, downward_closed _ g.2 _⟩ } /-- If a sieve S is contained in a sieve T, then we have a morphism of presheaves on their induced presheaves. -/ @[simps] def nat_trans_of_le {S T : sieve X} (h : S ≤ T) : S.functor ⟶ T.functor := { app := λ Y f, ⟨f.1, h _ f.2⟩ }. /-- The natural inclusion from the functor induced by a sieve to the yoneda embedding. -/ @[simps] def functor_inclusion (S : sieve X) : S.functor ⟶ yoneda.obj X := { app := λ Y f, f.1 }. lemma nat_trans_of_le_comm {S T : sieve X} (h : S ≤ T) : nat_trans_of_le h ≫ functor_inclusion _ = functor_inclusion _ := rfl /-- The presheaf induced by a sieve is a subobject of the yoneda embedding. -/ instance functor_inclusion_is_mono : mono S.functor_inclusion := ⟨λ Z f g h, by { ext Y y, apply congr_fun (nat_trans.congr_app h Y) y }⟩ /-- A natural transformation to a representable functor induces a sieve. This is the left inverse of `functor_inclusion`, shown in `sieve_of_functor_inclusion`. -/ -- TODO: Show that when `f` is mono, this is right inverse to `functor_inclusion` up to isomorphism. @[simps] def sieve_of_subfunctor {R} (f : R ⟶ yoneda.obj X) : sieve X := { arrows := λ Y g, ∃ t, f.app (opposite.op Y) t = g, downward_closed' := λ Y Z _, begin rintro ⟨t, rfl⟩ g, refine ⟨R.map g.op t, _⟩, rw functor_to_types.naturality _ _ f, simp, end } lemma sieve_of_subfunctor_functor_inclusion : sieve_of_subfunctor S.functor_inclusion = S := begin ext, simp only [functor_inclusion_app, sieve_of_subfunctor_apply, subtype.val_eq_coe], split, { rintro ⟨⟨f, hf⟩, rfl⟩, exact hf }, { intro hf, exact ⟨⟨_, hf⟩, rfl⟩ } end instance functor_inclusion_top_is_iso : is_iso ((⊤ : sieve X).functor_inclusion) := ⟨⟨{ app := λ Y a, ⟨a, ⟨⟩⟩ }, by tidy⟩⟩ end sieve end category_theory
809454eaf107a660618ceb9d48a0ba829cdc483b
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/geometry/euclidean/circumcenter.lean
aea4719f39aa815cc9bc07cfc581129f321dd0d3
[ "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
38,431
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers -/ import geometry.euclidean.basic import linear_algebra.affine_space.finite_dimensional import tactic.derive_fintype /-! # Circumcenter and circumradius This file proves some lemmas on points equidistant from a set of points, and defines the circumradius and circumcenter of a simplex. There are also some definitions for use in calculations where it is convenient to work with affine combinations of vertices together with the circumcenter. ## Main definitions * `circumcenter` and `circumradius` are the circumcenter and circumradius of a simplex. ## References * https://en.wikipedia.org/wiki/Circumscribed_circle -/ noncomputable theory open_locale big_operators open_locale classical open_locale real open_locale real_inner_product_space namespace euclidean_geometry open inner_product_geometry variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] include V open affine_subspace /-- `p` is equidistant from two points in `s` if and only if its `orthogonal_projection` is. -/ lemma dist_eq_iff_dist_orthogonal_projection_eq {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p1 p2 : P} (p3 : P) (hp1 : p1 ∈ s) (hp2 : p2 ∈ s) : dist p1 p3 = dist p2 p3 ↔ dist p1 (orthogonal_projection s p3) = dist p2 (orthogonal_projection s p3) := begin rw [←mul_self_inj_of_nonneg dist_nonneg dist_nonneg, ←mul_self_inj_of_nonneg dist_nonneg dist_nonneg, dist_sq_eq_dist_orthogonal_projection_sq_add_dist_orthogonal_projection_sq p3 hp1, dist_sq_eq_dist_orthogonal_projection_sq_add_dist_orthogonal_projection_sq p3 hp2], simp end /-- `p` is equidistant from a set of points in `s` if and only if its `orthogonal_projection` is. -/ lemma dist_set_eq_iff_dist_orthogonal_projection_eq {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {ps : set P} (hps : ps ⊆ s) (p : P) : (set.pairwise_on ps (λ p1 p2, dist p1 p = dist p2 p) ↔ (set.pairwise_on ps (λ p1 p2, dist p1 (orthogonal_projection s p) = dist p2 (orthogonal_projection s p)))) := ⟨λ h p1 hp1 p2 hp2 hne, (dist_eq_iff_dist_orthogonal_projection_eq p (hps hp1) (hps hp2)).1 (h p1 hp1 p2 hp2 hne), λ h p1 hp1 p2 hp2 hne, (dist_eq_iff_dist_orthogonal_projection_eq p (hps hp1) (hps hp2)).2 (h p1 hp1 p2 hp2 hne)⟩ /-- There exists `r` such that `p` has distance `r` from all the points of a set of points in `s` if and only if there exists (possibly different) `r` such that its `orthogonal_projection` has that distance from all the points in that set. -/ lemma exists_dist_eq_iff_exists_dist_orthogonal_projection_eq {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {ps : set P} (hps : ps ⊆ s) (p : P) : (∃ r, ∀ p1 ∈ ps, dist p1 p = r) ↔ ∃ r, ∀ p1 ∈ ps, dist p1 ↑(orthogonal_projection s p) = r := begin have h := dist_set_eq_iff_dist_orthogonal_projection_eq hps p, simp_rw set.pairwise_on_eq_iff_exists_eq at h, exact h end /-- The induction step for the existence and uniqueness of the circumcenter. Given a nonempty set of points in a nonempty affine subspace whose direction is complete, such that there is a unique (circumcenter, circumradius) pair for those points in that subspace, and a point `p` not in that subspace, there is a unique (circumcenter, circumradius) pair for the set with `p` added, in the span of the subspace with `p` added. -/ lemma exists_unique_dist_eq_of_insert {s : affine_subspace ℝ P} [complete_space s.direction] {ps : set P} (hnps : ps.nonempty) {p : P} (hps : ps ⊆ s) (hp : p ∉ s) (hu : ∃! cccr : (P × ℝ), cccr.fst ∈ s ∧ ∀ p1 ∈ ps, dist p1 cccr.fst = cccr.snd) : ∃! cccr₂ : (P × ℝ), cccr₂.fst ∈ affine_span ℝ (insert p (s : set P)) ∧ ∀ p1 ∈ insert p ps, dist p1 cccr₂.fst = cccr₂.snd := begin haveI : nonempty s := set.nonempty.to_subtype (hnps.mono hps), rcases hu with ⟨⟨cc, cr⟩, ⟨hcc, hcr⟩, hcccru⟩, simp only [prod.fst, prod.snd] at hcc hcr hcccru, let x := dist cc (orthogonal_projection s p), let y := dist p (orthogonal_projection s p), have hy0 : y ≠ 0 := dist_orthogonal_projection_ne_zero_of_not_mem hp, let ycc₂ := (x * x + y * y - cr * cr) / (2 * y), let cc₂ := (ycc₂ / y) • (p -ᵥ orthogonal_projection s p : V) +ᵥ cc, let cr₂ := real.sqrt (cr * cr + ycc₂ * ycc₂), use (cc₂, cr₂), simp only [prod.fst, prod.snd], have hpo : p = (1 : ℝ) • (p -ᵥ orthogonal_projection s p : V) +ᵥ orthogonal_projection s p, { simp }, split, { split, { refine vadd_mem_of_mem_direction _ (mem_affine_span ℝ (set.mem_insert_of_mem _ hcc)), rw direction_affine_span, exact submodule.smul_mem _ _ (vsub_mem_vector_span ℝ (set.mem_insert _ _) (set.mem_insert_of_mem _ (orthogonal_projection_mem _))) }, { intros p1 hp1, rw [←mul_self_inj_of_nonneg dist_nonneg (real.sqrt_nonneg _), real.mul_self_sqrt (add_nonneg (mul_self_nonneg _) (mul_self_nonneg _))], cases hp1, { rw hp1, rw [hpo, dist_sq_smul_orthogonal_vadd_smul_orthogonal_vadd (orthogonal_projection_mem p) hcc _ _ (vsub_orthogonal_projection_mem_direction_orthogonal s p), ←dist_eq_norm_vsub V p, dist_comm _ cc], field_simp [hy0], ring }, { rw [dist_sq_eq_dist_orthogonal_projection_sq_add_dist_orthogonal_projection_sq _ (hps hp1), orthogonal_projection_vadd_smul_vsub_orthogonal_projection _ _ hcc, subtype.coe_mk, hcr _ hp1, dist_eq_norm_vsub V cc₂ cc, vadd_vsub, norm_smul, ←dist_eq_norm_vsub V, real.norm_eq_abs, abs_div, abs_of_nonneg dist_nonneg, div_mul_cancel _ hy0, abs_mul_abs_self] } } }, { rintros ⟨cc₃, cr₃⟩ ⟨hcc₃, hcr₃⟩, simp only [prod.fst, prod.snd] at hcc₃ hcr₃, obtain ⟨t₃, cc₃', hcc₃', hcc₃''⟩ : ∃ (r : ℝ) (p0 : P) (hp0 : p0 ∈ s), cc₃ = r • (p -ᵥ ↑((orthogonal_projection s) p)) +ᵥ p0, { rwa mem_affine_span_insert_iff (orthogonal_projection_mem p) at hcc₃ }, have hcr₃' : ∃ r, ∀ p1 ∈ ps, dist p1 cc₃ = r := ⟨cr₃, λ p1 hp1, hcr₃ p1 (set.mem_insert_of_mem _ hp1)⟩, rw [exists_dist_eq_iff_exists_dist_orthogonal_projection_eq hps cc₃, hcc₃'', orthogonal_projection_vadd_smul_vsub_orthogonal_projection _ _ hcc₃'] at hcr₃', cases hcr₃' with cr₃' hcr₃', have hu := hcccru (cc₃', cr₃'), simp only [prod.fst, prod.snd] at hu, replace hu := hu ⟨hcc₃', hcr₃'⟩, rw prod.ext_iff at hu, simp only [prod.fst, prod.snd] at hu, cases hu with hucc hucr, substs hucc hucr, have hcr₃val : cr₃ = real.sqrt (cr₃' * cr₃' + (t₃ * y) * (t₃ * y)), { cases hnps with p0 hp0, have h' : ↑(⟨cc₃', hcc₃'⟩ : s) = cc₃' := rfl, rw [←hcr₃ p0 (set.mem_insert_of_mem _ hp0), hcc₃'', ←mul_self_inj_of_nonneg dist_nonneg (real.sqrt_nonneg _), real.mul_self_sqrt (add_nonneg (mul_self_nonneg _) (mul_self_nonneg _)), dist_sq_eq_dist_orthogonal_projection_sq_add_dist_orthogonal_projection_sq _ (hps hp0), orthogonal_projection_vadd_smul_vsub_orthogonal_projection _ _ hcc₃', h', hcr p0 hp0, dist_eq_norm_vsub V _ cc₃', vadd_vsub, norm_smul, ←dist_eq_norm_vsub V p, real.norm_eq_abs, ←mul_assoc, mul_comm _ (abs t₃), ←mul_assoc, abs_mul_abs_self], ring }, replace hcr₃ := hcr₃ p (set.mem_insert _ _), rw [hpo, hcc₃'', hcr₃val, ←mul_self_inj_of_nonneg dist_nonneg (real.sqrt_nonneg _), dist_sq_smul_orthogonal_vadd_smul_orthogonal_vadd (orthogonal_projection_mem p) hcc₃' _ _ (vsub_orthogonal_projection_mem_direction_orthogonal s p), dist_comm, ←dist_eq_norm_vsub V p, real.mul_self_sqrt (add_nonneg (mul_self_nonneg _) (mul_self_nonneg _))] at hcr₃, change x * x + _ * (y * y) = _ at hcr₃, rw [(show x * x + (1 - t₃) * (1 - t₃) * (y * y) = x * x + y * y - 2 * y * (t₃ * y) + t₃ * y * (t₃ * y), by ring), add_left_inj] at hcr₃, have ht₃ : t₃ = ycc₂ / y, { field_simp [←hcr₃, hy0], ring }, subst ht₃, change cc₃ = cc₂ at hcc₃'', congr', rw hcr₃val, congr' 2, field_simp [hy0], ring } end /-- Given a finite nonempty affinely independent family of points, there is a unique (circumcenter, circumradius) pair for those points in the affine subspace they span. -/ lemma exists_unique_dist_eq_of_affine_independent {ι : Type*} [hne : nonempty ι] [fintype ι] {p : ι → P} (ha : affine_independent ℝ p) : ∃! cccr : (P × ℝ), cccr.fst ∈ affine_span ℝ (set.range p) ∧ ∀ i, dist (p i) cccr.fst = cccr.snd := begin generalize' hn : fintype.card ι = n, unfreezingI { induction n with m hm generalizing ι }, { exfalso, have h := fintype.card_pos_iff.2 hne, rw hn at h, exact lt_irrefl 0 h }, { cases m, { rw fintype.card_eq_one_iff at hn, cases hn with i hi, haveI : unique ι := ⟨⟨i⟩, hi⟩, use (p i, 0), simp only [prod.fst, prod.snd, set.range_unique, affine_subspace.mem_affine_span_singleton], split, { simp_rw [hi (default ι)], use rfl, intro i1, rw hi i1, exact dist_self _ }, { rintros ⟨cc, cr⟩, simp only [prod.fst, prod.snd], rintros ⟨rfl, hdist⟩, rw hi (default ι), congr', rw ←hdist (default ι), exact dist_self _ } }, { have i := hne.some, let ι2 := {x // x ≠ i}, have hc : fintype.card ι2 = m + 1, { rw fintype.card_of_subtype (finset.univ.filter (λ x, x ≠ i)), { rw finset.filter_not, simp_rw eq_comm, rw [finset.filter_eq, if_pos (finset.mem_univ _), finset.card_sdiff (finset.subset_univ _), finset.card_singleton, finset.card_univ, hn], simp }, { simp } }, haveI : nonempty ι2 := fintype.card_pos_iff.1 (hc.symm ▸ nat.zero_lt_succ _), have ha2 : affine_independent ℝ (λ i2 : ι2, p i2) := affine_independent_subtype_of_affine_independent ha _, replace hm := hm ha2 hc, have hr : set.range p = insert (p i) (set.range (λ i2 : ι2, p i2)), { change _ = insert _ (set.range (λ i2 : {x | x ≠ i}, p i2)), rw [←set.image_eq_range, ←set.image_univ, ←set.image_insert_eq], congr' with j, simp [classical.em] }, change ∃! (cccr : P × ℝ), (_ ∧ ∀ i2, (λ q, dist q cccr.fst = cccr.snd) (p i2)), conv { congr, funext, conv { congr, skip, rw ←set.forall_range_iff } }, dsimp only, rw hr, change ∃! (cccr : P × ℝ), (_ ∧ ∀ (i2 : ι2), (λ q, dist q cccr.fst = cccr.snd) (p i2)) at hm, conv at hm { congr, funext, conv { congr, skip, rw ←set.forall_range_iff } }, rw ←affine_span_insert_affine_span, refine exists_unique_dist_eq_of_insert (set.range_nonempty _) (subset_span_points ℝ _) _ hm, convert not_mem_affine_span_diff_of_affine_independent ha i set.univ, change set.range (λ i2 : {x | x ≠ i}, p i2) = _, rw ←set.image_eq_range, congr' with j, simp, refl } } end end euclidean_geometry namespace affine namespace simplex open finset affine_subspace euclidean_geometry variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] include V /-- The pair (circumcenter, circumradius) of a simplex. -/ def circumcenter_circumradius {n : ℕ} (s : simplex ℝ P n) : (P × ℝ) := (exists_unique_dist_eq_of_affine_independent s.independent).some /-- The property satisfied by the (circumcenter, circumradius) pair. -/ lemma circumcenter_circumradius_unique_dist_eq {n : ℕ} (s : simplex ℝ P n) : (s.circumcenter_circumradius.fst ∈ affine_span ℝ (set.range s.points) ∧ ∀ i, dist (s.points i) s.circumcenter_circumradius.fst = s.circumcenter_circumradius.snd) ∧ (∀ cccr : (P × ℝ), (cccr.fst ∈ affine_span ℝ (set.range s.points) ∧ ∀ i, dist (s.points i) cccr.fst = cccr.snd) → cccr = s.circumcenter_circumradius) := (exists_unique_dist_eq_of_affine_independent s.independent).some_spec /-- The circumcenter of a simplex. -/ def circumcenter {n : ℕ} (s : simplex ℝ P n) : P := s.circumcenter_circumradius.fst /-- The circumradius of a simplex. -/ def circumradius {n : ℕ} (s : simplex ℝ P n) : ℝ := s.circumcenter_circumradius.snd /-- The circumcenter lies in the affine span. -/ lemma circumcenter_mem_affine_span {n : ℕ} (s : simplex ℝ P n) : s.circumcenter ∈ affine_span ℝ (set.range s.points) := s.circumcenter_circumradius_unique_dist_eq.1.1 /-- All points have distance from the circumcenter equal to the circumradius. -/ @[simp] lemma dist_circumcenter_eq_circumradius {n : ℕ} (s : simplex ℝ P n) : ∀ i, dist (s.points i) s.circumcenter = s.circumradius := s.circumcenter_circumradius_unique_dist_eq.1.2 /-- All points have distance to the circumcenter equal to the circumradius. -/ @[simp] lemma dist_circumcenter_eq_circumradius' {n : ℕ} (s : simplex ℝ P n) : ∀ i, dist s.circumcenter (s.points i) = s.circumradius := begin intro i, rw dist_comm, exact dist_circumcenter_eq_circumradius _ _ end /-- Given a point in the affine span from which all the points are equidistant, that point is the circumcenter. -/ lemma eq_circumcenter_of_dist_eq {n : ℕ} (s : simplex ℝ P n) {p : P} (hp : p ∈ affine_span ℝ (set.range s.points)) {r : ℝ} (hr : ∀ i, dist (s.points i) p = r) : p = s.circumcenter := begin have h := s.circumcenter_circumradius_unique_dist_eq.2 (p, r), simp only [hp, hr, forall_const, eq_self_iff_true, and_self, prod.ext_iff] at h, exact h.1 end /-- Given a point in the affine span from which all the points are equidistant, that distance is the circumradius. -/ lemma eq_circumradius_of_dist_eq {n : ℕ} (s : simplex ℝ P n) {p : P} (hp : p ∈ affine_span ℝ (set.range s.points)) {r : ℝ} (hr : ∀ i, dist (s.points i) p = r) : r = s.circumradius := begin have h := s.circumcenter_circumradius_unique_dist_eq.2 (p, r), simp only [hp, hr, forall_const, eq_self_iff_true, and_self, prod.ext_iff] at h, exact h.2 end /-- The circumradius is non-negative. -/ lemma circumradius_nonneg {n : ℕ} (s : simplex ℝ P n) : 0 ≤ s.circumradius := s.dist_circumcenter_eq_circumradius 0 ▸ dist_nonneg /-- The circumradius of a simplex with at least two points is positive. -/ lemma circumradius_pos {n : ℕ} (s : simplex ℝ P (n + 1)) : 0 < s.circumradius := begin refine lt_of_le_of_ne s.circumradius_nonneg _, intro h, have hr := s.dist_circumcenter_eq_circumradius, simp_rw [←h, dist_eq_zero] at hr, have h01 := (injective_of_affine_independent s.independent).ne (dec_trivial : (0 : fin (n + 2)) ≠ 1), simpa [hr] using h01 end /-- The circumcenter of a 0-simplex equals its unique point. -/ lemma circumcenter_eq_point (s : simplex ℝ P 0) (i : fin 1) : s.circumcenter = s.points i := begin have h := s.circumcenter_mem_affine_span, rw [set.range_unique, mem_affine_span_singleton] at h, rw h, congr end /-- The circumcenter of a 1-simplex equals its centroid. -/ lemma circumcenter_eq_centroid (s : simplex ℝ P 1) : s.circumcenter = finset.univ.centroid ℝ s.points := begin have hr : set.pairwise_on set.univ (λ i j : fin 2, dist (s.points i) (finset.univ.centroid ℝ s.points) = dist (s.points j) (finset.univ.centroid ℝ s.points)), { intros i hi j hj hij, rw [finset.centroid_insert_singleton_fin, dist_eq_norm_vsub V (s.points i), dist_eq_norm_vsub V (s.points j), vsub_vadd_eq_vsub_sub, vsub_vadd_eq_vsub_sub, ←one_smul ℝ (s.points i -ᵥ s.points 0), ←one_smul ℝ (s.points j -ᵥ s.points 0)], fin_cases i; fin_cases j; simp [-one_smul, ←sub_smul]; norm_num }, rw set.pairwise_on_eq_iff_exists_eq at hr, cases hr with r hr, exact (s.eq_circumcenter_of_dist_eq (centroid_mem_affine_span_of_card_eq_add_one ℝ _ (finset.card_fin 2)) (λ i, hr i (set.mem_univ _))).symm end /-- If there exists a distance that a point has from all vertices of a simplex, the orthogonal projection of that point onto the subspace spanned by that simplex is its circumcenter. -/ lemma orthogonal_projection_eq_circumcenter_of_exists_dist_eq {n : ℕ} (s : simplex ℝ P n) {p : P} (hr : ∃ r, ∀ i, dist (s.points i) p = r) : ↑(orthogonal_projection (affine_span ℝ (set.range s.points)) p) = s.circumcenter := begin change ∃ r : ℝ, ∀ i, (λ x, dist x p = r) (s.points i) at hr, conv at hr { congr, funext, rw ←set.forall_range_iff }, rw exists_dist_eq_iff_exists_dist_orthogonal_projection_eq (subset_affine_span ℝ _) p at hr, cases hr with r hr, exact s.eq_circumcenter_of_dist_eq (orthogonal_projection_mem p) (λ i, hr _ (set.mem_range_self i)), end /-- If a point has the same distance from all vertices of a simplex, the orthogonal projection of that point onto the subspace spanned by that simplex is its circumcenter. -/ lemma orthogonal_projection_eq_circumcenter_of_dist_eq {n : ℕ} (s : simplex ℝ P n) {p : P} {r : ℝ} (hr : ∀ i, dist (s.points i) p = r) : ↑(orthogonal_projection (affine_span ℝ (set.range s.points)) p) = s.circumcenter := s.orthogonal_projection_eq_circumcenter_of_exists_dist_eq ⟨r, hr⟩ /-- The orthogonal projection of the circumcenter onto a face is the circumcenter of that face. -/ lemma orthogonal_projection_circumcenter {n : ℕ} (s : simplex ℝ P n) {fs : finset (fin (n + 1))} {m : ℕ} (h : fs.card = m + 1) : ↑(orthogonal_projection (affine_span ℝ (set.range (s.face h).points)) s.circumcenter) = (s.face h).circumcenter := begin have hr : ∃ r, ∀ i, dist ((s.face h).points i) s.circumcenter = r, { use s.circumradius, simp [face_points] }, exact orthogonal_projection_eq_circumcenter_of_exists_dist_eq _ hr end /-- Two simplices with the same points have the same circumcenter. -/ lemma circumcenter_eq_of_range_eq {n : ℕ} {s₁ s₂ : simplex ℝ P n} (h : set.range s₁.points = set.range s₂.points) : s₁.circumcenter = s₂.circumcenter := begin have hs : s₁.circumcenter ∈ affine_span ℝ (set.range s₂.points) := h ▸ s₁.circumcenter_mem_affine_span, have hr : ∀ i, dist (s₂.points i) s₁.circumcenter = s₁.circumradius, { intro i, have hi : s₂.points i ∈ set.range s₂.points := set.mem_range_self _, rw [←h, set.mem_range] at hi, rcases hi with ⟨j, hj⟩, rw [←hj, s₁.dist_circumcenter_eq_circumradius j] }, exact s₂.eq_circumcenter_of_dist_eq hs hr end omit V /-- An index type for the vertices of a simplex plus its circumcenter. This is for use in calculations where it is convenient to work with affine combinations of vertices together with the circumcenter. (An equivalent form sometimes used in the literature is placing the circumcenter at the origin and working with vectors for the vertices.) -/ @[derive fintype] inductive points_with_circumcenter_index (n : ℕ) | point_index : fin (n + 1) → points_with_circumcenter_index | circumcenter_index : points_with_circumcenter_index open points_with_circumcenter_index instance points_with_circumcenter_index_inhabited (n : ℕ) : inhabited (points_with_circumcenter_index n) := ⟨circumcenter_index⟩ /-- `point_index` as an embedding. -/ def point_index_embedding (n : ℕ) : fin (n + 1) ↪ points_with_circumcenter_index n := ⟨λ i, point_index i, λ _ _ h, by injection h⟩ /-- The sum of a function over `points_with_circumcenter_index`. -/ lemma sum_points_with_circumcenter {α : Type*} [add_comm_monoid α] {n : ℕ} (f : points_with_circumcenter_index n → α) : ∑ i, f i = (∑ (i : fin (n + 1)), f (point_index i)) + f circumcenter_index := begin have h : univ = insert circumcenter_index (univ.map (point_index_embedding n)), { ext x, refine ⟨λ h, _, λ _, mem_univ _⟩, cases x with i, { exact mem_insert_of_mem (mem_map_of_mem _ (mem_univ i)) }, { exact mem_insert_self _ _ } }, change _ = ∑ i, f (point_index_embedding n i) + _, rw [add_comm, h, ←sum_map, sum_insert], simp_rw [mem_map, not_exists], intros x hx h, injection h end include V /-- The vertices of a simplex plus its circumcenter. -/ def points_with_circumcenter {n : ℕ} (s : simplex ℝ P n) : points_with_circumcenter_index n → P | (point_index i) := s.points i | circumcenter_index := s.circumcenter /-- `points_with_circumcenter`, applied to a `point_index` value, equals `points` applied to that value. -/ @[simp] lemma points_with_circumcenter_point {n : ℕ} (s : simplex ℝ P n) (i : fin (n + 1)) : s.points_with_circumcenter (point_index i) = s.points i := rfl /-- `points_with_circumcenter`, applied to `circumcenter_index`, equals the circumcenter. -/ @[simp] lemma points_with_circumcenter_eq_circumcenter {n : ℕ} (s : simplex ℝ P n) : s.points_with_circumcenter circumcenter_index = s.circumcenter := rfl omit V /-- The weights for a single vertex of a simplex, in terms of `points_with_circumcenter`. -/ def point_weights_with_circumcenter {n : ℕ} (i : fin (n + 1)) : points_with_circumcenter_index n → ℝ | (point_index j) := if j = i then 1 else 0 | circumcenter_index := 0 /-- `point_weights_with_circumcenter` sums to 1. -/ @[simp] lemma sum_point_weights_with_circumcenter {n : ℕ} (i : fin (n + 1)) : ∑ j, point_weights_with_circumcenter i j = 1 := begin convert sum_ite_eq' univ (point_index i) (function.const _ (1 : ℝ)), { ext j, cases j ; simp [point_weights_with_circumcenter] }, { simp } end include V /-- A single vertex, in terms of `points_with_circumcenter`. -/ lemma point_eq_affine_combination_of_points_with_circumcenter {n : ℕ} (s : simplex ℝ P n) (i : fin (n + 1)) : s.points i = (univ : finset (points_with_circumcenter_index n)).affine_combination s.points_with_circumcenter (point_weights_with_circumcenter i) := begin rw ←points_with_circumcenter_point, symmetry, refine affine_combination_of_eq_one_of_eq_zero _ _ _ (mem_univ _) (by simp [point_weights_with_circumcenter]) _, intros i hi hn, cases i, { have h : i_1 ≠ i := λ h, hn (h ▸ rfl), simp [point_weights_with_circumcenter, h] }, { refl } end omit V /-- The weights for the centroid of some vertices of a simplex, in terms of `points_with_circumcenter`. -/ def centroid_weights_with_circumcenter {n : ℕ} (fs : finset (fin (n + 1))) : points_with_circumcenter_index n → ℝ | (point_index i) := if i ∈ fs then ((card fs : ℝ) ⁻¹) else 0 | circumcenter_index := 0 /-- `centroid_weights_with_circumcenter` sums to 1, if the `finset` is nonempty. -/ @[simp] lemma sum_centroid_weights_with_circumcenter {n : ℕ} {fs : finset (fin (n + 1))} (h : fs.nonempty) : ∑ i, centroid_weights_with_circumcenter fs i = 1 := begin simp_rw [sum_points_with_circumcenter, centroid_weights_with_circumcenter, add_zero, ←fs.sum_centroid_weights_eq_one_of_nonempty ℝ h, set.sum_indicator_subset _ fs.subset_univ], rcongr end include V /-- The centroid of some vertices of a simplex, in terms of `points_with_circumcenter`. -/ lemma centroid_eq_affine_combination_of_points_with_circumcenter {n : ℕ} (s : simplex ℝ P n) (fs : finset (fin (n + 1))) : fs.centroid ℝ s.points = (univ : finset (points_with_circumcenter_index n)).affine_combination s.points_with_circumcenter (centroid_weights_with_circumcenter fs) := begin simp_rw [centroid_def, affine_combination_apply, weighted_vsub_of_point_apply, sum_points_with_circumcenter, centroid_weights_with_circumcenter, points_with_circumcenter_point, zero_smul, add_zero, centroid_weights, set.sum_indicator_subset_of_eq_zero (function.const (fin (n + 1)) ((card fs : ℝ)⁻¹)) (λ i wi, wi • (s.points i -ᵥ classical.choice add_torsor.nonempty)) fs.subset_univ (λ i, zero_smul ℝ _), set.indicator_apply], congr, funext, congr' 2 end omit V /-- The weights for the circumcenter of a simplex, in terms of `points_with_circumcenter`. -/ def circumcenter_weights_with_circumcenter (n : ℕ) : points_with_circumcenter_index n → ℝ | (point_index i) := 0 | circumcenter_index := 1 /-- `circumcenter_weights_with_circumcenter` sums to 1. -/ @[simp] lemma sum_circumcenter_weights_with_circumcenter (n : ℕ) : ∑ i, circumcenter_weights_with_circumcenter n i = 1 := begin convert sum_ite_eq' univ circumcenter_index (function.const _ (1 : ℝ)), { ext ⟨j⟩ ; simp [circumcenter_weights_with_circumcenter] }, { simp } end include V /-- The circumcenter of a simplex, in terms of `points_with_circumcenter`. -/ lemma circumcenter_eq_affine_combination_of_points_with_circumcenter {n : ℕ} (s : simplex ℝ P n) : s.circumcenter = (univ : finset (points_with_circumcenter_index n)).affine_combination s.points_with_circumcenter (circumcenter_weights_with_circumcenter n) := begin rw ←points_with_circumcenter_eq_circumcenter, symmetry, refine affine_combination_of_eq_one_of_eq_zero _ _ _ (mem_univ _) rfl _, rintros ⟨i⟩ hi hn ; tauto end omit V /-- The weights for the reflection of the circumcenter in an edge of a simplex. This definition is only valid with `i₁ ≠ i₂`. -/ def reflection_circumcenter_weights_with_circumcenter {n : ℕ} (i₁ i₂ : fin (n + 1)) : points_with_circumcenter_index n → ℝ | (point_index i) := if i = i₁ ∨ i = i₂ then 1 else 0 | circumcenter_index := -1 /-- `reflection_circumcenter_weights_with_circumcenter` sums to 1. -/ @[simp] lemma sum_reflection_circumcenter_weights_with_circumcenter {n : ℕ} {i₁ i₂ : fin (n + 1)} (h : i₁ ≠ i₂) : ∑ i, reflection_circumcenter_weights_with_circumcenter i₁ i₂ i = 1 := begin simp_rw [sum_points_with_circumcenter, reflection_circumcenter_weights_with_circumcenter, sum_ite, sum_const, filter_or, filter_eq'], rw card_union_eq, { simp }, { simp [h.symm] } end include V /-- The reflection of the circumcenter of a simplex in an edge, in terms of `points_with_circumcenter`. -/ lemma reflection_circumcenter_eq_affine_combination_of_points_with_circumcenter {n : ℕ} (s : simplex ℝ P n) {i₁ i₂ : fin (n + 1)} (h : i₁ ≠ i₂) : reflection (affine_span ℝ (s.points '' {i₁, i₂})) s.circumcenter = (univ : finset (points_with_circumcenter_index n)).affine_combination s.points_with_circumcenter (reflection_circumcenter_weights_with_circumcenter i₁ i₂) := begin have hc : card ({i₁, i₂} : finset (fin (n + 1))) = 2, { simp [h] }, have h_faces : ↑(orthogonal_projection (affine_span ℝ (s.points '' {i₁, i₂})) s.circumcenter) = ↑(orthogonal_projection (affine_span ℝ (set.range (s.face hc).points)) s.circumcenter), { apply eq_orthogonal_projection_of_eq_subspace, simp }, rw [reflection_apply, h_faces, s.orthogonal_projection_circumcenter hc, circumcenter_eq_centroid, s.face_centroid_eq_centroid hc, centroid_eq_affine_combination_of_points_with_circumcenter, circumcenter_eq_affine_combination_of_points_with_circumcenter, ←@vsub_eq_zero_iff_eq V, affine_combination_vsub, weighted_vsub_vadd_affine_combination, affine_combination_vsub, weighted_vsub_apply, sum_points_with_circumcenter], simp_rw [pi.sub_apply, pi.add_apply, pi.sub_apply, sub_smul, add_smul, sub_smul, centroid_weights_with_circumcenter, circumcenter_weights_with_circumcenter, reflection_circumcenter_weights_with_circumcenter, ite_smul, zero_smul, sub_zero, apply_ite2 (+), add_zero, ←add_smul, hc, zero_sub, neg_smul, sub_self, add_zero], convert sum_const_zero, norm_num end end simplex end affine namespace euclidean_geometry open affine affine_subspace finite_dimensional variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] include V /-- Given a nonempty affine subspace, whose direction is complete, that contains a set of points, those points are cospherical if and only if they are equidistant from some point in that subspace. -/ lemma cospherical_iff_exists_mem_of_complete {s : affine_subspace ℝ P} {ps : set P} (h : ps ⊆ s) [nonempty s] [complete_space s.direction] : cospherical ps ↔ ∃ (center ∈ s) (radius : ℝ), ∀ p ∈ ps, dist p center = radius := begin split, { rintro ⟨c, hcr⟩, rw exists_dist_eq_iff_exists_dist_orthogonal_projection_eq h c at hcr, exact ⟨orthogonal_projection s c, orthogonal_projection_mem _, hcr⟩ }, { exact λ ⟨c, hc, hd⟩, ⟨c, hd⟩ } end /-- Given a nonempty affine subspace, whose direction is finite-dimensional, that contains a set of points, those points are cospherical if and only if they are equidistant from some point in that subspace. -/ lemma cospherical_iff_exists_mem_of_finite_dimensional {s : affine_subspace ℝ P} {ps : set P} (h : ps ⊆ s) [nonempty s] [finite_dimensional ℝ s.direction] : cospherical ps ↔ ∃ (center ∈ s) (radius : ℝ), ∀ p ∈ ps, dist p center = radius := cospherical_iff_exists_mem_of_complete h /-- All n-simplices among cospherical points in an n-dimensional subspace have the same circumradius. -/ lemma exists_circumradius_eq_of_cospherical_subset {s : affine_subspace ℝ P} {ps : set P} (h : ps ⊆ s) [nonempty s] {n : ℕ} [finite_dimensional ℝ s.direction] (hd : finrank ℝ s.direction = n) (hc : cospherical ps) : ∃ r : ℝ, ∀ sx : simplex ℝ P n, set.range sx.points ⊆ ps → sx.circumradius = r := begin rw cospherical_iff_exists_mem_of_finite_dimensional h at hc, rcases hc with ⟨c, hc, r, hcr⟩, use r, intros sx hsxps, have hsx : affine_span ℝ (set.range sx.points) = s, { refine affine_span_eq_of_le_of_affine_independent_of_card_eq_finrank_add_one sx.independent (span_points_subset_coe_of_subset_coe (set.subset.trans hsxps h)) _, simp [hd] }, have hc : c ∈ affine_span ℝ (set.range sx.points) := hsx.symm ▸ hc, exact (sx.eq_circumradius_of_dist_eq hc (λ i, hcr (sx.points i) (hsxps (set.mem_range_self i)))).symm end /-- Two n-simplices among cospherical points in an n-dimensional subspace have the same circumradius. -/ lemma circumradius_eq_of_cospherical_subset {s : affine_subspace ℝ P} {ps : set P} (h : ps ⊆ s) [nonempty s] {n : ℕ} [finite_dimensional ℝ s.direction] (hd : finrank ℝ s.direction = n) (hc : cospherical ps) {sx₁ sx₂ : simplex ℝ P n} (hsx₁ : set.range sx₁.points ⊆ ps) (hsx₂ : set.range sx₂.points ⊆ ps) : sx₁.circumradius = sx₂.circumradius := begin rcases exists_circumradius_eq_of_cospherical_subset h hd hc with ⟨r, hr⟩, rw [hr sx₁ hsx₁, hr sx₂ hsx₂] end /-- All n-simplices among cospherical points in n-space have the same circumradius. -/ lemma exists_circumradius_eq_of_cospherical {ps : set P} {n : ℕ} [finite_dimensional ℝ V] (hd : finrank ℝ V = n) (hc : cospherical ps) : ∃ r : ℝ, ∀ sx : simplex ℝ P n, set.range sx.points ⊆ ps → sx.circumradius = r := begin haveI : nonempty (⊤ : affine_subspace ℝ P) := set.univ.nonempty, rw [←finrank_top, ←direction_top ℝ V P] at hd, refine exists_circumradius_eq_of_cospherical_subset _ hd hc, exact set.subset_univ _ end /-- Two n-simplices among cospherical points in n-space have the same circumradius. -/ lemma circumradius_eq_of_cospherical {ps : set P} {n : ℕ} [finite_dimensional ℝ V] (hd : finrank ℝ V = n) (hc : cospherical ps) {sx₁ sx₂ : simplex ℝ P n} (hsx₁ : set.range sx₁.points ⊆ ps) (hsx₂ : set.range sx₂.points ⊆ ps) : sx₁.circumradius = sx₂.circumradius := begin rcases exists_circumradius_eq_of_cospherical hd hc with ⟨r, hr⟩, rw [hr sx₁ hsx₁, hr sx₂ hsx₂] end /-- All n-simplices among cospherical points in an n-dimensional subspace have the same circumcenter. -/ lemma exists_circumcenter_eq_of_cospherical_subset {s : affine_subspace ℝ P} {ps : set P} (h : ps ⊆ s) [nonempty s] {n : ℕ} [finite_dimensional ℝ s.direction] (hd : finrank ℝ s.direction = n) (hc : cospherical ps) : ∃ c : P, ∀ sx : simplex ℝ P n, set.range sx.points ⊆ ps → sx.circumcenter = c := begin rw cospherical_iff_exists_mem_of_finite_dimensional h at hc, rcases hc with ⟨c, hc, r, hcr⟩, use c, intros sx hsxps, have hsx : affine_span ℝ (set.range sx.points) = s, { refine affine_span_eq_of_le_of_affine_independent_of_card_eq_finrank_add_one sx.independent (span_points_subset_coe_of_subset_coe (set.subset.trans hsxps h)) _, simp [hd] }, have hc : c ∈ affine_span ℝ (set.range sx.points) := hsx.symm ▸ hc, exact (sx.eq_circumcenter_of_dist_eq hc (λ i, hcr (sx.points i) (hsxps (set.mem_range_self i)))).symm end /-- Two n-simplices among cospherical points in an n-dimensional subspace have the same circumcenter. -/ lemma circumcenter_eq_of_cospherical_subset {s : affine_subspace ℝ P} {ps : set P} (h : ps ⊆ s) [nonempty s] {n : ℕ} [finite_dimensional ℝ s.direction] (hd : finrank ℝ s.direction = n) (hc : cospherical ps) {sx₁ sx₂ : simplex ℝ P n} (hsx₁ : set.range sx₁.points ⊆ ps) (hsx₂ : set.range sx₂.points ⊆ ps) : sx₁.circumcenter = sx₂.circumcenter := begin rcases exists_circumcenter_eq_of_cospherical_subset h hd hc with ⟨r, hr⟩, rw [hr sx₁ hsx₁, hr sx₂ hsx₂] end /-- All n-simplices among cospherical points in n-space have the same circumcenter. -/ lemma exists_circumcenter_eq_of_cospherical {ps : set P} {n : ℕ} [finite_dimensional ℝ V] (hd : finrank ℝ V = n) (hc : cospherical ps) : ∃ c : P, ∀ sx : simplex ℝ P n, set.range sx.points ⊆ ps → sx.circumcenter = c := begin haveI : nonempty (⊤ : affine_subspace ℝ P) := set.univ.nonempty, rw [←finrank_top, ←direction_top ℝ V P] at hd, refine exists_circumcenter_eq_of_cospherical_subset _ hd hc, exact set.subset_univ _ end /-- Two n-simplices among cospherical points in n-space have the same circumcenter. -/ lemma circumcenter_eq_of_cospherical {ps : set P} {n : ℕ} [finite_dimensional ℝ V] (hd : finrank ℝ V = n) (hc : cospherical ps) {sx₁ sx₂ : simplex ℝ P n} (hsx₁ : set.range sx₁.points ⊆ ps) (hsx₂ : set.range sx₂.points ⊆ ps) : sx₁.circumcenter = sx₂.circumcenter := begin rcases exists_circumcenter_eq_of_cospherical hd hc with ⟨r, hr⟩, rw [hr sx₁ hsx₁, hr sx₂ hsx₂] end /-- Suppose all distances from `p₁` and `p₂` to the points of a simplex are equal, and that `p₁` and `p₂` lie in the affine span of `p` with the vertices of that simplex. Then `p₁` and `p₂` are equal or reflections of each other in the affine span of the vertices of the simplex. -/ lemma eq_or_eq_reflection_of_dist_eq {n : ℕ} {s : simplex ℝ P n} {p p₁ p₂ : P} {r : ℝ} (hp₁ : p₁ ∈ affine_span ℝ (insert p (set.range s.points))) (hp₂ : p₂ ∈ affine_span ℝ (insert p (set.range s.points))) (h₁ : ∀ i, dist (s.points i) p₁ = r) (h₂ : ∀ i, dist (s.points i) p₂ = r) : p₁ = p₂ ∨ p₁ = reflection (affine_span ℝ (set.range s.points)) p₂ := begin let span_s := affine_span ℝ (set.range s.points), have h₁' := s.orthogonal_projection_eq_circumcenter_of_dist_eq h₁, have h₂' := s.orthogonal_projection_eq_circumcenter_of_dist_eq h₂, rw [←affine_span_insert_affine_span, mem_affine_span_insert_iff (orthogonal_projection_mem p)] at hp₁ hp₂, obtain ⟨r₁, p₁o, hp₁o, hp₁⟩ := hp₁, obtain ⟨r₂, p₂o, hp₂o, hp₂⟩ := hp₂, obtain rfl : ↑(orthogonal_projection span_s p₁) = p₁o, { have := orthogonal_projection_vadd_smul_vsub_orthogonal_projection _ _ hp₁o, rw ← hp₁ at this, rw this, refl }, rw h₁' at hp₁, obtain rfl : ↑(orthogonal_projection span_s p₂) = p₂o, { have := orthogonal_projection_vadd_smul_vsub_orthogonal_projection _ _ hp₂o, rw ← hp₂ at this, rw this, refl }, rw h₂' at hp₂, have h : s.points 0 ∈ span_s := mem_affine_span ℝ (set.mem_range_self _), have hd₁ : dist p₁ s.circumcenter * dist p₁ s.circumcenter = r * r - s.circumradius * s.circumradius, { rw [dist_comm, ←h₁ 0, dist_sq_eq_dist_orthogonal_projection_sq_add_dist_orthogonal_projection_sq p₁ h], simp only [h₁', dist_comm p₁, add_sub_cancel', simplex.dist_circumcenter_eq_circumradius] }, have hd₂ : dist p₂ s.circumcenter * dist p₂ s.circumcenter = r * r - s.circumradius * s.circumradius, { rw [dist_comm, ←h₂ 0, dist_sq_eq_dist_orthogonal_projection_sq_add_dist_orthogonal_projection_sq p₂ h], simp only [h₂', dist_comm p₂, add_sub_cancel', simplex.dist_circumcenter_eq_circumradius] }, rw [←hd₂, hp₁, hp₂, dist_eq_norm_vsub V _ s.circumcenter, dist_eq_norm_vsub V _ s.circumcenter, vadd_vsub, vadd_vsub, ←real_inner_self_eq_norm_sq, ←real_inner_self_eq_norm_sq, real_inner_smul_left, real_inner_smul_left, real_inner_smul_right, real_inner_smul_right, ←mul_assoc, ←mul_assoc] at hd₁, by_cases hp : p = orthogonal_projection span_s p, { rw [hp₁, hp₂, ←hp], simp only [true_or, eq_self_iff_true, smul_zero, vsub_self] }, { have hz : ⟪p -ᵥ orthogonal_projection span_s p, p -ᵥ orthogonal_projection span_s p⟫ ≠ 0, by simpa only [ne.def, vsub_eq_zero_iff_eq, inner_self_eq_zero] using hp, rw [mul_left_inj' hz, mul_self_eq_mul_self_iff] at hd₁, rw [hp₁, hp₂], cases hd₁, { left, rw hd₁ }, { right, rw [hd₁, reflection_vadd_smul_vsub_orthogonal_projection p r₂ s.circumcenter_mem_affine_span, neg_smul] } } end end euclidean_geometry
cde5d7fe33fad6b0b04bfed30084013a12ba4d99
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/ring_theory/subring/basic.lean
be9c61b3ea2bdbe889ec72b900583f4eaf09a350
[ "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
39,816
lean
/- Copyright (c) 2020 Ashvni Narayanan. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Ashvni Narayanan -/ import group_theory.subgroup.basic import ring_theory.subsemiring.basic /-! # Subrings Let `R` be a ring. This file defines the "bundled" subring type `subring R`, a type whose terms correspond to subrings of `R`. This is the preferred way to talk about subrings in mathlib. Unbundled subrings (`s : set R` and `is_subring s`) are not in this file, and they will ultimately be deprecated. We prove that subrings are a complete lattice, and that you can `map` (pushforward) and `comap` (pull back) them along ring homomorphisms. We define the `closure` construction from `set R` to `subring R`, sending a subset of `R` to the subring it generates, and prove that it is a Galois insertion. ## Main definitions Notation used here: `(R : Type u) [ring R] (S : Type u) [ring S] (f g : R →+* S)` `(A : subring R) (B : subring S) (s : set R)` * `subring R` : the type of subrings of a ring `R`. * `instance : complete_lattice (subring R)` : the complete lattice structure on the subrings. * `subring.center` : the center of a ring `R`. * `subring.closure` : subring closure of a set, i.e., the smallest subring that includes the set. * `subring.gi` : `closure : set M → subring M` and coercion `coe : subring M → set M` form a `galois_insertion`. * `comap f B : subring A` : the preimage of a subring `B` along the ring homomorphism `f` * `map f A : subring B` : the image of a subring `A` along the ring homomorphism `f`. * `prod A B : subring (R × S)` : the product of subrings * `f.range : subring B` : the range of the ring homomorphism `f`. * `eq_locus f g : subring R` : given ring homomorphisms `f g : R →+* S`, the subring of `R` where `f x = g x` ## Implementation notes A subring is implemented as a subsemiring which is also an additive subgroup. The initial PR was as a submonoid which is also an additive subgroup. Lattice inclusion (e.g. `≤` and `⊓`) is used rather than set notation (`⊆` and `∩`), although `∈` is defined as membership of a subring's underlying set. ## Tags subring, subrings -/ open_locale big_operators universes u v w variables {R : Type u} {S : Type v} {T : Type w} [ring R] [ring S] [ring T] set_option old_structure_cmd true /-- `subring R` is the type of subrings of `R`. A subring of `R` is a subset `s` that is a multiplicative submonoid and an additive subgroup. Note in particular that it shares the same 0 and 1 as R. -/ structure subring (R : Type u) [ring R] extends subsemiring R, add_subgroup R /-- Reinterpret a `subring` as a `subsemiring`. -/ add_decl_doc subring.to_subsemiring /-- Reinterpret a `subring` as an `add_subgroup`. -/ add_decl_doc subring.to_add_subgroup namespace subring /-- The underlying submonoid of a subring. -/ def to_submonoid (s : subring R) : submonoid R := { carrier := s.carrier, ..s.to_subsemiring.to_submonoid } instance : set_like (subring R) R := ⟨subring.carrier, λ p q h, by cases p; cases q; congr'⟩ @[simp] lemma mem_carrier {s : subring R} {x : R} : x ∈ s.carrier ↔ x ∈ s := iff.rfl @[simp] lemma mem_mk {S : set R} {x : R} (h₁ h₂ h₃ h₄ h₅) : x ∈ (⟨S, h₁, h₂, h₃, h₄, h₅⟩ : subring R) ↔ x ∈ S := iff.rfl @[simp] lemma coe_set_mk (S : set R) (h₁ h₂ h₃ h₄ h₅) : ((⟨S, h₁, h₂, h₃, h₄, h₅⟩ : subring R) : set R) = S := rfl @[simp] lemma mk_le_mk {S S' : set R} (h₁ h₂ h₃ h₄ h₅ h₁' h₂' h₃' h₄' h₅') : (⟨S, h₁, h₂, h₃, h₄, h₅⟩ : subring R) ≤ (⟨S', h₁', h₂', h₃', h₄', h₅'⟩ : subring R) ↔ S ⊆ S' := iff.rfl /-- Two subrings are equal if they have the same elements. -/ @[ext] theorem ext {S T : subring R} (h : ∀ x, x ∈ S ↔ x ∈ T) : S = T := set_like.ext h /-- Copy of a subring with a new `carrier` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (S : subring R) (s : set R) (hs : s = ↑S) : subring R := { carrier := s, neg_mem' := hs.symm ▸ S.neg_mem', ..S.to_subsemiring.copy s hs } @[simp] lemma coe_copy (S : subring R) (s : set R) (hs : s = ↑S) : (S.copy s hs : set R) = s := rfl lemma copy_eq (S : subring R) (s : set R) (hs : s = ↑S) : S.copy s hs = S := set_like.coe_injective hs lemma to_subsemiring_injective : function.injective (to_subsemiring : subring R → subsemiring R) | r s h := ext (set_like.ext_iff.mp h : _) @[mono] lemma to_subsemiring_strict_mono : strict_mono (to_subsemiring : subring R → subsemiring R) := λ _ _, id @[mono] lemma to_subsemiring_mono : monotone (to_subsemiring : subring R → subsemiring R) := to_subsemiring_strict_mono.monotone lemma to_add_subgroup_injective : function.injective (to_add_subgroup : subring R → add_subgroup R) | r s h := ext (set_like.ext_iff.mp h : _) @[mono] lemma to_add_subgroup_strict_mono : strict_mono (to_add_subgroup : subring R → add_subgroup R) := λ _ _, id @[mono] lemma to_add_subgroup_mono : monotone (to_add_subgroup : subring R → add_subgroup R) := to_add_subgroup_strict_mono.monotone lemma to_submonoid_injective : function.injective (to_submonoid : subring R → submonoid R) | r s h := ext (set_like.ext_iff.mp h : _) @[mono] lemma to_submonoid_strict_mono : strict_mono (to_submonoid : subring R → submonoid R) := λ _ _, id @[mono] lemma to_submonoid_mono : monotone (to_submonoid : subring R → submonoid R) := to_submonoid_strict_mono.monotone /-- Construct a `subring R` from a set `s`, a submonoid `sm`, and an additive subgroup `sa` such that `x ∈ s ↔ x ∈ sm ↔ x ∈ sa`. -/ protected def mk' (s : set R) (sm : submonoid R) (sa : add_subgroup R) (hm : ↑sm = s) (ha : ↑sa = s) : subring R := { carrier := s, zero_mem' := ha ▸ sa.zero_mem, one_mem' := hm ▸ sm.one_mem, add_mem' := λ x y, by simpa only [← ha] using sa.add_mem, mul_mem' := λ x y, by simpa only [← hm] using sm.mul_mem, neg_mem' := λ x, by simpa only [← ha] using sa.neg_mem, } @[simp] lemma coe_mk' {s : set R} {sm : submonoid R} (hm : ↑sm = s) {sa : add_subgroup R} (ha : ↑sa = s) : (subring.mk' s sm sa hm ha : set R) = s := rfl @[simp] lemma mem_mk' {s : set R} {sm : submonoid R} (hm : ↑sm = s) {sa : add_subgroup R} (ha : ↑sa = s) {x : R} : x ∈ subring.mk' s sm sa hm ha ↔ x ∈ s := iff.rfl @[simp] lemma mk'_to_submonoid {s : set R} {sm : submonoid R} (hm : ↑sm = s) {sa : add_subgroup R} (ha : ↑sa = s) : (subring.mk' s sm sa hm ha).to_submonoid = sm := set_like.coe_injective hm.symm @[simp] lemma mk'_to_add_subgroup {s : set R} {sm : submonoid R} (hm : ↑sm = s) {sa : add_subgroup R} (ha : ↑sa =s) : (subring.mk' s sm sa hm ha).to_add_subgroup = sa := set_like.coe_injective ha.symm end subring /-- A `subsemiring` containing -1 is a `subring`. -/ def subsemiring.to_subring (s : subsemiring R) (hneg : (-1 : R) ∈ s) : subring R := { neg_mem' := by { rintros x, rw <-neg_one_mul, apply subsemiring.mul_mem, exact hneg, } ..s.to_submonoid, ..s.to_add_submonoid } namespace subring variables (s : subring R) /-- A subring contains the ring's 1. -/ theorem one_mem : (1 : R) ∈ s := s.one_mem' /-- A subring contains the ring's 0. -/ theorem zero_mem : (0 : R) ∈ s := s.zero_mem' /-- A subring is closed under multiplication. -/ theorem mul_mem : ∀ {x y : R}, x ∈ s → y ∈ s → x * y ∈ s := s.mul_mem' /-- A subring is closed under addition. -/ theorem add_mem : ∀ {x y : R}, x ∈ s → y ∈ s → x + y ∈ s := s.add_mem' /-- A subring is closed under negation. -/ theorem neg_mem : ∀ {x : R}, x ∈ s → -x ∈ s := s.neg_mem' /-- A subring is closed under subtraction -/ theorem sub_mem {x y : R} (hx : x ∈ s) (hy : y ∈ s) : x - y ∈ s := by { rw sub_eq_add_neg, exact s.add_mem hx (s.neg_mem hy) } /-- Product of a list of elements in a subring is in the subring. -/ lemma list_prod_mem {l : list R} : (∀x ∈ l, x ∈ s) → l.prod ∈ s := s.to_submonoid.list_prod_mem /-- Sum of a list of elements in a subring is in the subring. -/ lemma list_sum_mem {l : list R} : (∀x ∈ l, x ∈ s) → l.sum ∈ s := s.to_add_subgroup.list_sum_mem /-- Product of a multiset of elements in a subring of a `comm_ring` is in the subring. -/ lemma multiset_prod_mem {R} [comm_ring R] (s : subring R) (m : multiset R) : (∀a ∈ m, a ∈ s) → m.prod ∈ s := s.to_submonoid.multiset_prod_mem m /-- Sum of a multiset of elements in an `subring` of a `ring` is in the `subring`. -/ lemma multiset_sum_mem {R} [ring R] (s : subring R) (m : multiset R) : (∀a ∈ m, a ∈ s) → m.sum ∈ s := s.to_add_subgroup.multiset_sum_mem m /-- Product of elements of a subring of a `comm_ring` indexed by a `finset` is in the subring. -/ lemma prod_mem {R : Type*} [comm_ring R] (s : subring R) {ι : Type*} {t : finset ι} {f : ι → R} (h : ∀c ∈ t, f c ∈ s) : ∏ i in t, f i ∈ s := s.to_submonoid.prod_mem h /-- Sum of elements in a `subring` of a `ring` indexed by a `finset` is in the `subring`. -/ lemma sum_mem {R : Type*} [ring R] (s : subring R) {ι : Type*} {t : finset ι} {f : ι → R} (h : ∀c ∈ t, f c ∈ s) : ∑ i in t, f i ∈ s := s.to_add_subgroup.sum_mem h lemma pow_mem {x : R} (hx : x ∈ s) (n : ℕ) : x^n ∈ s := s.to_submonoid.pow_mem hx n lemma zsmul_mem {x : R} (hx : x ∈ s) (n : ℤ) : n • x ∈ s := s.to_add_subgroup.zsmul_mem hx n lemma coe_int_mem (n : ℤ) : (n : R) ∈ s := by simp only [← zsmul_one, zsmul_mem, one_mem] /-- A subring of a ring inherits a ring structure -/ instance to_ring : ring s := { right_distrib := λ x y z, subtype.eq $ right_distrib x y z, left_distrib := λ x y z, subtype.eq $ left_distrib x y z, .. s.to_submonoid.to_monoid, .. s.to_add_subgroup.to_add_comm_group } @[simp, norm_cast] lemma coe_add (x y : s) : (↑(x + y) : R) = ↑x + ↑y := rfl @[simp, norm_cast] lemma coe_neg (x : s) : (↑(-x) : R) = -↑x := rfl @[simp, norm_cast] lemma coe_mul (x y : s) : (↑(x * y) : R) = ↑x * ↑y := rfl @[simp, norm_cast] lemma coe_zero : ((0 : s) : R) = 0 := rfl @[simp, norm_cast] lemma coe_one : ((1 : s) : R) = 1 := rfl @[simp, norm_cast] lemma coe_pow (x : s) (n : ℕ) : (↑(x ^ n) : R) = x ^ n := s.to_submonoid.coe_pow x n @[simp] lemma coe_eq_zero_iff {x : s} : (x : R) = 0 ↔ x = 0 := ⟨λ h, subtype.ext (trans h s.coe_zero.symm), λ h, h.symm ▸ s.coe_zero⟩ /-- A subring of a `comm_ring` is a `comm_ring`. -/ instance to_comm_ring {R} [comm_ring R] (s : subring R) : comm_ring s := { mul_comm := λ _ _, subtype.eq $ mul_comm _ _, ..subring.to_ring s} /-- A subring of a non-trivial ring is non-trivial. -/ instance {R} [ring R] [nontrivial R] (s : subring R) : nontrivial s := s.to_subsemiring.nontrivial /-- A subring of a ring with no zero divisors has no zero divisors. -/ instance {R} [ring R] [no_zero_divisors R] (s : subring R) : no_zero_divisors s := s.to_subsemiring.no_zero_divisors /-- A subring of a domain is a domain. -/ instance {R} [ring R] [is_domain R] (s : subring R) : is_domain s := { .. s.nontrivial, .. s.no_zero_divisors, .. s.to_ring } /-- A subring of an `ordered_ring` is an `ordered_ring`. -/ instance to_ordered_ring {R} [ordered_ring R] (s : subring R) : ordered_ring s := subtype.coe_injective.ordered_ring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) /-- A subring of an `ordered_comm_ring` is an `ordered_comm_ring`. -/ instance to_ordered_comm_ring {R} [ordered_comm_ring R] (s : subring R) : ordered_comm_ring s := subtype.coe_injective.ordered_comm_ring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) /-- A subring of a `linear_ordered_ring` is a `linear_ordered_ring`. -/ instance to_linear_ordered_ring {R} [linear_ordered_ring R] (s : subring R) : linear_ordered_ring s := subtype.coe_injective.linear_ordered_ring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) /-- A subring of a `linear_ordered_comm_ring` is a `linear_ordered_comm_ring`. -/ instance to_linear_ordered_comm_ring {R} [linear_ordered_comm_ring R] (s : subring R) : linear_ordered_comm_ring s := subtype.coe_injective.linear_ordered_comm_ring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) /-- The natural ring hom from a subring of ring `R` to `R`. -/ def subtype (s : subring R) : s →+* R := { to_fun := coe, .. s.to_submonoid.subtype, .. s.to_add_subgroup.subtype } @[simp] theorem coe_subtype : ⇑s.subtype = coe := rfl @[simp, norm_cast] lemma coe_nat_cast : ∀ (n : ℕ), ((n : s) : R) = n := map_nat_cast s.subtype @[simp, norm_cast] lemma coe_int_cast (n : ℤ) : ((n : s) : R) = n := s.subtype.map_int_cast n /-! ## Partial order -/ @[simp] lemma mem_to_submonoid {s : subring R} {x : R} : x ∈ s.to_submonoid ↔ x ∈ s := iff.rfl @[simp] lemma coe_to_submonoid (s : subring R) : (s.to_submonoid : set R) = s := rfl @[simp] lemma mem_to_add_subgroup {s : subring R} {x : R} : x ∈ s.to_add_subgroup ↔ x ∈ s := iff.rfl @[simp] lemma coe_to_add_subgroup (s : subring R) : (s.to_add_subgroup : set R) = s := rfl /-! ## top -/ /-- The subring `R` of the ring `R`. -/ instance : has_top (subring R) := ⟨{ .. (⊤ : submonoid R), .. (⊤ : add_subgroup R) }⟩ @[simp] lemma mem_top (x : R) : x ∈ (⊤ : subring R) := set.mem_univ x @[simp] lemma coe_top : ((⊤ : subring R) : set R) = set.univ := rfl /-! ## comap -/ /-- The preimage of a subring along a ring homomorphism is a subring. -/ def comap {R : Type u} {S : Type v} [ring R] [ring S] (f : R →+* S) (s : subring S) : subring R := { carrier := f ⁻¹' s.carrier, .. s.to_submonoid.comap (f : R →* S), .. s.to_add_subgroup.comap (f : R →+ S) } @[simp] lemma coe_comap (s : subring S) (f : R →+* S) : (s.comap f : set R) = f ⁻¹' s := rfl @[simp] lemma mem_comap {s : subring S} {f : R →+* S} {x : R} : x ∈ s.comap f ↔ f x ∈ s := iff.rfl lemma comap_comap (s : subring T) (g : S →+* T) (f : R →+* S) : (s.comap g).comap f = s.comap (g.comp f) := rfl /-! ## map -/ /-- The image of a subring along a ring homomorphism is a subring. -/ def map {R : Type u} {S : Type v} [ring R] [ring S] (f : R →+* S) (s : subring R) : subring S := { carrier := f '' s.carrier, .. s.to_submonoid.map (f : R →* S), .. s.to_add_subgroup.map (f : R →+ S) } @[simp] lemma coe_map (f : R →+* S) (s : subring R) : (s.map f : set S) = f '' s := rfl @[simp] lemma mem_map {f : R →+* S} {s : subring R} {y : S} : y ∈ s.map f ↔ ∃ x ∈ s, f x = y := set.mem_image_iff_bex @[simp] lemma map_id : s.map (ring_hom.id R) = s := set_like.coe_injective $ set.image_id _ lemma map_map (g : S →+* T) (f : R →+* S) : (s.map f).map g = s.map (g.comp f) := set_like.coe_injective $ set.image_image _ _ _ lemma map_le_iff_le_comap {f : R →+* S} {s : subring R} {t : subring S} : s.map f ≤ t ↔ s ≤ t.comap f := set.image_subset_iff lemma gc_map_comap (f : R →+* S) : galois_connection (map f) (comap f) := λ S T, map_le_iff_le_comap /-- A subring is isomorphic to its image under an injective function -/ noncomputable def equiv_map_of_injective (f : R →+* S) (hf : function.injective f) : s ≃+* s.map f := { map_mul' := λ _ _, subtype.ext (f.map_mul _ _), map_add' := λ _ _, subtype.ext (f.map_add _ _), ..equiv.set.image f s hf } @[simp] lemma coe_equiv_map_of_injective_apply (f : R →+* S) (hf : function.injective f) (x : s) : (equiv_map_of_injective s f hf x : S) = f x := rfl end subring namespace ring_hom variables (g : S →+* T) (f : R →+* S) /-! ## range -/ /-- The range of a ring homomorphism, as a subring of the target. See Note [range copy pattern]. -/ def range {R : Type u} {S : Type v} [ring R] [ring S] (f : R →+* S) : subring S := ((⊤ : subring R).map f).copy (set.range f) set.image_univ.symm @[simp] lemma coe_range : (f.range : set S) = set.range f := rfl @[simp] lemma mem_range {f : R →+* S} {y : S} : y ∈ f.range ↔ ∃ x, f x = y := iff.rfl lemma range_eq_map (f : R →+* S) : f.range = subring.map f ⊤ := by { ext, simp } lemma mem_range_self (f : R →+* S) (x : R) : f x ∈ f.range := mem_range.mpr ⟨x, rfl⟩ lemma map_range : f.range.map g = (g.comp f).range := by simpa only [range_eq_map] using (⊤ : subring R).map_map g f -- TODO -- rename to `cod_restrict` when is_ring_hom is deprecated /-- Restrict the codomain of a ring homomorphism to a subring that includes the range. -/ def cod_restrict' {R : Type u} {S : Type v} [ring R] [ring S] (f : R →+* S) (s : subring S) (h : ∀ x, f x ∈ s) : R →+* s := { to_fun := λ x, ⟨f x, h x⟩, map_add' := λ x y, subtype.eq $ f.map_add x y, map_zero' := subtype.eq f.map_zero, map_mul' := λ x y, subtype.eq $ f.map_mul x y, map_one' := subtype.eq f.map_one } /-- The range of a ring homomorphism is a fintype, if the domain is a fintype. Note: this instance can form a diamond with `subtype.fintype` in the presence of `fintype S`. -/ instance fintype_range [fintype R] [decidable_eq S] (f : R →+* S) : fintype (range f) := set.fintype_range f end ring_hom namespace subring /-! ## bot -/ instance : has_bot (subring R) := ⟨(int.cast_ring_hom R).range⟩ instance : inhabited (subring R) := ⟨⊥⟩ lemma coe_bot : ((⊥ : subring R) : set R) = set.range (coe : ℤ → R) := ring_hom.coe_range (int.cast_ring_hom R) lemma mem_bot {x : R} : x ∈ (⊥ : subring R) ↔ ∃ (n : ℤ), ↑n = x := ring_hom.mem_range /-! ## inf -/ /-- The inf of two subrings is their intersection. -/ instance : has_inf (subring R) := ⟨λ s t, { carrier := s ∩ t, .. s.to_submonoid ⊓ t.to_submonoid, .. s.to_add_subgroup ⊓ t.to_add_subgroup }⟩ @[simp] lemma coe_inf (p p' : subring R) : ((p ⊓ p' : subring R) : set R) = p ∩ p' := rfl @[simp] lemma mem_inf {p p' : subring R} {x : R} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl instance : has_Inf (subring R) := ⟨λ s, subring.mk' (⋂ t ∈ s, ↑t) (⨅ t ∈ s, subring.to_submonoid t ) (⨅ t ∈ s, subring.to_add_subgroup t) (by simp) (by simp)⟩ @[simp, norm_cast] lemma coe_Inf (S : set (subring R)) : ((Inf S : subring R) : set R) = ⋂ s ∈ S, ↑s := rfl lemma mem_Inf {S : set (subring R)} {x : R} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_Inter₂ @[simp] lemma Inf_to_submonoid (s : set (subring R)) : (Inf s).to_submonoid = ⨅ t ∈ s, subring.to_submonoid t := mk'_to_submonoid _ _ @[simp] lemma Inf_to_add_subgroup (s : set (subring R)) : (Inf s).to_add_subgroup = ⨅ t ∈ s, subring.to_add_subgroup t := mk'_to_add_subgroup _ _ /-- Subrings of a ring form a complete lattice. -/ instance : complete_lattice (subring R) := { bot := (⊥), bot_le := λ s x hx, let ⟨n, hn⟩ := mem_bot.1 hx in hn ▸ s.coe_int_mem n, top := (⊤), le_top := λ s x hx, trivial, inf := (⊓), inf_le_left := λ s t x, and.left, inf_le_right := λ s t x, and.right, le_inf := λ s t₁ t₂ h₁ h₂ x hx, ⟨h₁ hx, h₂ hx⟩, .. complete_lattice_of_Inf (subring R) (λ s, is_glb.of_image (λ s t, show (s : set R) ≤ t ↔ s ≤ t, from set_like.coe_subset_coe) is_glb_binfi)} lemma eq_top_iff' (A : subring R) : A = ⊤ ↔ ∀ x : R, x ∈ A := eq_top_iff.trans ⟨λ h m, h $ mem_top m, λ h m _, h m⟩ /-! ## Center of a ring -/ section variables (R) /-- The center of a ring `R` is the set of elements that commute with everything in `R` -/ def center : subring R := { carrier := set.center R, neg_mem' := λ a, set.neg_mem_center, .. subsemiring.center R } lemma coe_center : ↑(center R) = set.center R := rfl @[simp] lemma center_to_subsemiring : (center R).to_subsemiring = subsemiring.center R := rfl variables {R} lemma mem_center_iff {z : R} : z ∈ center R ↔ ∀ g, g * z = z * g := iff.rfl instance decidable_mem_center [decidable_eq R] [fintype R] : decidable_pred (∈ center R) := λ _, decidable_of_iff' _ mem_center_iff @[simp] lemma center_eq_top (R) [comm_ring R] : center R = ⊤ := set_like.coe_injective (set.center_eq_univ R) /-- The center is commutative. -/ instance : comm_ring (center R) := { ..subsemiring.center.comm_semiring, ..(center R).to_ring} end section division_ring variables {K : Type u} [division_ring K] instance : field (center K) := { inv := λ a, ⟨a⁻¹, set.inv_mem_center₀ a.prop⟩, mul_inv_cancel := λ ⟨a, ha⟩ h, subtype.ext $ mul_inv_cancel $ subtype.coe_injective.ne h, div := λ a b, ⟨a / b, set.div_mem_center₀ a.prop b.prop⟩, div_eq_mul_inv := λ a b, subtype.ext $ div_eq_mul_inv _ _, inv_zero := subtype.ext inv_zero, ..(center K).nontrivial, ..center.comm_ring } @[simp] lemma center.coe_inv (a : center K) : ((a⁻¹ : center K) : K) = (a : K)⁻¹ := rfl @[simp] lemma center.coe_div (a b : center K) : ((a / b : center K) : K) = (a : K) / (b : K) := rfl end division_ring /-! ## subring closure of a subset -/ /-- The `subring` generated by a set. -/ def closure (s : set R) : subring R := Inf {S | s ⊆ S} lemma mem_closure {x : R} {s : set R} : x ∈ closure s ↔ ∀ S : subring R, s ⊆ S → x ∈ S := mem_Inf /-- The subring generated by a set includes the set. -/ @[simp] lemma subset_closure {s : set R} : s ⊆ closure s := λ x hx, mem_closure.2 $ λ S hS, hS hx lemma not_mem_of_not_mem_closure {s : set R} {P : R} (hP : P ∉ closure s) : P ∉ s := λ h, hP (subset_closure h) /-- A subring `t` includes `closure s` if and only if it includes `s`. -/ @[simp] lemma closure_le {s : set R} {t : subring R} : closure s ≤ t ↔ s ⊆ t := ⟨set.subset.trans subset_closure, λ h, Inf_le h⟩ /-- Subring closure of a set is monotone in its argument: if `s ⊆ t`, then `closure s ≤ closure t`. -/ lemma closure_mono ⦃s t : set R⦄ (h : s ⊆ t) : closure s ≤ closure t := closure_le.2 $ set.subset.trans h subset_closure lemma closure_eq_of_le {s : set R} {t : subring R} (h₁ : s ⊆ t) (h₂ : t ≤ closure s) : closure s = t := le_antisymm (closure_le.2 h₁) h₂ /-- An induction principle for closure membership. If `p` holds for `0`, `1`, and all elements of `s`, and is preserved under addition, negation, and multiplication, then `p` holds for all elements of the closure of `s`. -/ @[elab_as_eliminator] lemma closure_induction {s : set R} {p : R → Prop} {x} (h : x ∈ closure s) (Hs : ∀ x ∈ s, p x) (H0 : p 0) (H1 : p 1) (Hadd : ∀ x y, p x → p y → p (x + y)) (Hneg : ∀ (x : R), p x → p (-x)) (Hmul : ∀ x y, p x → p y → p (x * y)) : p x := (@closure_le _ _ _ ⟨p, H1, Hmul, H0, Hadd, Hneg⟩).2 Hs h lemma mem_closure_iff {s : set R} {x} : x ∈ closure s ↔ x ∈ add_subgroup.closure (submonoid.closure s : set R) := ⟨ λ h, closure_induction h (λ x hx, add_subgroup.subset_closure $ submonoid.subset_closure hx ) (add_subgroup.zero_mem _) (add_subgroup.subset_closure ( submonoid.one_mem (submonoid.closure s)) ) (λ x y hx hy, add_subgroup.add_mem _ hx hy ) (λ x hx, add_subgroup.neg_mem _ hx ) ( λ x y hx hy, add_subgroup.closure_induction hy (λ q hq, add_subgroup.closure_induction hx ( λ p hp, add_subgroup.subset_closure ((submonoid.closure s).mul_mem hp hq) ) ( begin rw zero_mul q, apply add_subgroup.zero_mem _, end ) ( λ p₁ p₂ ihp₁ ihp₂, begin rw add_mul p₁ p₂ q, apply add_subgroup.add_mem _ ihp₁ ihp₂, end ) ( λ x hx, begin have f : -x * q = -(x*q) := by simp, rw f, apply add_subgroup.neg_mem _ hx, end ) ) ( begin rw mul_zero x, apply add_subgroup.zero_mem _, end ) ( λ q₁ q₂ ihq₁ ihq₂, begin rw mul_add x q₁ q₂, apply add_subgroup.add_mem _ ihq₁ ihq₂ end ) ( λ z hz, begin have f : x * -z = -(x*z) := by simp, rw f, apply add_subgroup.neg_mem _ hz, end ) ), λ h, add_subgroup.closure_induction h ( λ x hx, submonoid.closure_induction hx ( λ x hx, subset_closure hx ) ( one_mem _ ) ( λ x y hx hy, mul_mem _ hx hy ) ) ( zero_mem _ ) (λ x y hx hy, add_mem _ hx hy) ( λ x hx, neg_mem _ hx ) ⟩ theorem exists_list_of_mem_closure {s : set R} {x : R} (h : x ∈ closure s) : (∃ L : list (list R), (∀ t ∈ L, ∀ y ∈ t, y ∈ s ∨ y = (-1:R)) ∧ (L.map list.prod).sum = x) := add_subgroup.closure_induction (mem_closure_iff.1 h) (λ x hx, let ⟨l, hl, h⟩ :=submonoid.exists_list_of_mem_closure hx in ⟨[l], by simp [h]; clear_aux_decl; tauto!⟩) ⟨[], by simp⟩ (λ x y ⟨l, hl1, hl2⟩ ⟨m, hm1, hm2⟩, ⟨l ++ m, λ t ht, (list.mem_append.1 ht).elim (hl1 t) (hm1 t), by simp [hl2, hm2]⟩) (λ x ⟨L, hL⟩, ⟨L.map (list.cons (-1)), list.forall_mem_map_iff.2 $ λ j hj, list.forall_mem_cons.2 ⟨or.inr rfl, hL.1 j hj⟩, hL.2 ▸ list.rec_on L (by simp) (by simp [list.map_cons, add_comm] {contextual := tt})⟩) variable (R) /-- `closure` forms a Galois insertion with the coercion to set. -/ protected def gi : galois_insertion (@closure R _) coe := { choice := λ s _, closure s, gc := λ s t, closure_le, le_l_u := λ s, subset_closure, choice_eq := λ s h, rfl } variable {R} /-- Closure of a subring `S` equals `S`. -/ lemma closure_eq (s : subring R) : closure (s : set R) = s := (subring.gi R).l_u_eq s @[simp] lemma closure_empty : closure (∅ : set R) = ⊥ := (subring.gi R).gc.l_bot @[simp] lemma closure_univ : closure (set.univ : set R) = ⊤ := @coe_top R _ ▸ closure_eq ⊤ lemma closure_union (s t : set R) : closure (s ∪ t) = closure s ⊔ closure t := (subring.gi R).gc.l_sup lemma closure_Union {ι} (s : ι → set R) : closure (⋃ i, s i) = ⨆ i, closure (s i) := (subring.gi R).gc.l_supr lemma closure_sUnion (s : set (set R)) : closure (⋃₀ s) = ⨆ t ∈ s, closure t := (subring.gi R).gc.l_Sup lemma map_sup (s t : subring R) (f : R →+* S) : (s ⊔ t).map f = s.map f ⊔ t.map f := (gc_map_comap f).l_sup lemma map_supr {ι : Sort*} (f : R →+* S) (s : ι → subring R) : (supr s).map f = ⨆ i, (s i).map f := (gc_map_comap f).l_supr lemma comap_inf (s t : subring S) (f : R →+* S) : (s ⊓ t).comap f = s.comap f ⊓ t.comap f := (gc_map_comap f).u_inf lemma comap_infi {ι : Sort*} (f : R →+* S) (s : ι → subring S) : (infi s).comap f = ⨅ i, (s i).comap f := (gc_map_comap f).u_infi @[simp] lemma map_bot (f : R →+* S) : (⊥ : subring R).map f = ⊥ := (gc_map_comap f).l_bot @[simp] lemma comap_top (f : R →+* S) : (⊤ : subring S).comap f = ⊤ := (gc_map_comap f).u_top /-- Given `subring`s `s`, `t` of rings `R`, `S` respectively, `s.prod t` is `s ×̂ t` as a subring of `R × S`. -/ def prod (s : subring R) (t : subring S) : subring (R × S) := { carrier := (s : set R) ×ˢ (t : set S), .. s.to_submonoid.prod t.to_submonoid, .. s.to_add_subgroup.prod t.to_add_subgroup} @[norm_cast] lemma coe_prod (s : subring R) (t : subring S) : (s.prod t : set (R × S)) = (s : set R) ×ˢ (t : set S) := rfl lemma mem_prod {s : subring R} {t : subring S} {p : R × S} : p ∈ s.prod t ↔ p.1 ∈ s ∧ p.2 ∈ t := iff.rfl @[mono] lemma prod_mono ⦃s₁ s₂ : subring R⦄ (hs : s₁ ≤ s₂) ⦃t₁ t₂ : subring S⦄ (ht : t₁ ≤ t₂) : s₁.prod t₁ ≤ s₂.prod t₂ := set.prod_mono hs ht lemma prod_mono_right (s : subring R) : monotone (λ t : subring S, s.prod t) := prod_mono (le_refl s) lemma prod_mono_left (t : subring S) : monotone (λ s : subring R, s.prod t) := λ s₁ s₂ hs, prod_mono hs (le_refl t) lemma prod_top (s : subring R) : s.prod (⊤ : subring S) = s.comap (ring_hom.fst R S) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_fst] lemma top_prod (s : subring S) : (⊤ : subring R).prod s = s.comap (ring_hom.snd R S) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_snd] @[simp] lemma top_prod_top : (⊤ : subring R).prod (⊤ : subring S) = ⊤ := (top_prod _).trans $ comap_top _ /-- Product of subrings is isomorphic to their product as rings. -/ def prod_equiv (s : subring R) (t : subring S) : s.prod t ≃+* s × t := { map_mul' := λ x y, rfl, map_add' := λ x y, rfl, .. equiv.set.prod ↑s ↑t } /-- The underlying set of a non-empty directed Sup of subrings is just a union of the subrings. Note that this fails without the directedness assumption (the union of two subrings is typically not a subring) -/ lemma mem_supr_of_directed {ι} [hι : nonempty ι] {S : ι → subring R} (hS : directed (≤) S) {x : R} : x ∈ (⨆ i, S i) ↔ ∃ i, x ∈ S i := begin refine ⟨_, λ ⟨i, hi⟩, (set_like.le_def.1 $ le_supr S i) hi⟩, let U : subring R := subring.mk' (⋃ i, (S i : set R)) (⨆ i, (S i).to_submonoid) (⨆ i, (S i).to_add_subgroup) (submonoid.coe_supr_of_directed $ hS.mono_comp _ (λ _ _, id)) (add_subgroup.coe_supr_of_directed $ hS.mono_comp _ (λ _ _, id)), suffices : (⨆ i, S i) ≤ U, by simpa using @this x, exact supr_le (λ i x hx, set.mem_Union.2 ⟨i, hx⟩), end lemma coe_supr_of_directed {ι} [hι : nonempty ι] {S : ι → subring R} (hS : directed (≤) S) : ((⨆ i, S i : subring R) : set R) = ⋃ i, ↑(S i) := set.ext $ λ x, by simp [mem_supr_of_directed hS] lemma mem_Sup_of_directed_on {S : set (subring R)} (Sne : S.nonempty) (hS : directed_on (≤) S) {x : R} : x ∈ Sup S ↔ ∃ s ∈ S, x ∈ s := begin haveI : nonempty S := Sne.to_subtype, simp only [Sup_eq_supr', mem_supr_of_directed hS.directed_coe, set_coe.exists, subtype.coe_mk] end lemma coe_Sup_of_directed_on {S : set (subring R)} (Sne : S.nonempty) (hS : directed_on (≤) S) : (↑(Sup S) : set R) = ⋃ s ∈ S, ↑s := set.ext $ λ x, by simp [mem_Sup_of_directed_on Sne hS] lemma mem_map_equiv {f : R ≃+* S} {K : subring R} {x : S} : x ∈ K.map (f : R →+* S) ↔ f.symm x ∈ K := @set.mem_image_equiv _ _ ↑K f.to_equiv x lemma map_equiv_eq_comap_symm (f : R ≃+* S) (K : subring R) : K.map (f : R →+* S) = K.comap f.symm := set_like.coe_injective (f.to_equiv.image_eq_preimage K) lemma comap_equiv_eq_map_symm (f : R ≃+* S) (K : subring S) : K.comap (f : R →+* S) = K.map f.symm := (map_equiv_eq_comap_symm f.symm K).symm end subring namespace ring_hom variables [ring T] {s : subring R} open subring /-- Restriction of a ring homomorphism to a subring of the domain. -/ def restrict (f : R →+* S) (s : subring R) : s →+* S := f.comp s.subtype @[simp] lemma restrict_apply (f : R →+* S) (x : s) : f.restrict s x = f x := rfl /-- Restriction of a ring homomorphism to its range interpreted as a subsemiring. This is the bundled version of `set.range_factorization`. -/ def range_restrict (f : R →+* S) : R →+* f.range := f.cod_restrict' f.range $ λ x, ⟨x, rfl⟩ @[simp] lemma coe_range_restrict (f : R →+* S) (x : R) : (f.range_restrict x : S) = f x := rfl lemma range_restrict_surjective (f : R →+* S) : function.surjective f.range_restrict := λ ⟨y, hy⟩, let ⟨x, hx⟩ := mem_range.mp hy in ⟨x, subtype.ext hx⟩ lemma range_top_iff_surjective {f : R →+* S} : f.range = (⊤ : subring S) ↔ function.surjective f := set_like.ext'_iff.trans $ iff.trans (by rw [coe_range, coe_top]) set.range_iff_surjective /-- The range of a surjective ring homomorphism is the whole of the codomain. -/ lemma range_top_of_surjective (f : R →+* S) (hf : function.surjective f) : f.range = (⊤ : subring S) := range_top_iff_surjective.2 hf /-- The subring of elements `x : R` such that `f x = g x`, i.e., the equalizer of f and g as a subring of R -/ def eq_locus (f g : R →+* S) : subring R := { carrier := {x | f x = g x}, .. (f : R →* S).eq_mlocus g, .. (f : R →+ S).eq_locus g } /-- If two ring homomorphisms are equal on a set, then they are equal on its subring closure. -/ lemma eq_on_set_closure {f g : R →+* S} {s : set R} (h : set.eq_on f g s) : set.eq_on f g (closure s) := show closure s ≤ f.eq_locus g, from closure_le.2 h lemma eq_of_eq_on_set_top {f g : R →+* S} (h : set.eq_on f g (⊤ : subring R)) : f = g := ext $ λ x, h trivial lemma eq_of_eq_on_set_dense {s : set R} (hs : closure s = ⊤) {f g : R →+* S} (h : s.eq_on f g) : f = g := eq_of_eq_on_set_top $ hs ▸ eq_on_set_closure h lemma closure_preimage_le (f : R →+* S) (s : set S) : closure (f ⁻¹' s) ≤ (closure s).comap f := closure_le.2 $ λ x hx, set_like.mem_coe.2 $ mem_comap.2 $ subset_closure hx /-- The image under a ring homomorphism of the subring generated by a set equals the subring generated by the image of the set. -/ lemma map_closure (f : R →+* S) (s : set R) : (closure s).map f = closure (f '' s) := le_antisymm (map_le_iff_le_comap.2 $ le_trans (closure_mono $ set.subset_preimage_image _ _) (closure_preimage_le _ _)) (closure_le.2 $ set.image_subset _ subset_closure) end ring_hom namespace subring open ring_hom /-- The ring homomorphism associated to an inclusion of subrings. -/ def inclusion {S T : subring R} (h : S ≤ T) : S →+* T := S.subtype.cod_restrict' _ (λ x, h x.2) @[simp] lemma range_subtype (s : subring R) : s.subtype.range = s := set_like.coe_injective $ (coe_srange _).trans subtype.range_coe @[simp] lemma range_fst : (fst R S).srange = ⊤ := (fst R S).srange_top_of_surjective $ prod.fst_surjective @[simp] lemma range_snd : (snd R S).srange = ⊤ := (snd R S).srange_top_of_surjective $ prod.snd_surjective @[simp] lemma prod_bot_sup_bot_prod (s : subring R) (t : subring S) : (s.prod ⊥) ⊔ (prod ⊥ t) = s.prod t := le_antisymm (sup_le (prod_mono_right s bot_le) (prod_mono_left t bot_le)) $ assume p hp, prod.fst_mul_snd p ▸ mul_mem _ ((le_sup_left : s.prod ⊥ ≤ s.prod ⊥ ⊔ prod ⊥ t) ⟨hp.1, set_like.mem_coe.2 $ one_mem ⊥⟩) ((le_sup_right : prod ⊥ t ≤ s.prod ⊥ ⊔ prod ⊥ t) ⟨set_like.mem_coe.2 $ one_mem ⊥, hp.2⟩) end subring namespace ring_equiv variables {s t : subring R} /-- Makes the identity isomorphism from a proof two subrings of a multiplicative monoid are equal. -/ def subring_congr (h : s = t) : s ≃+* t := { map_mul' := λ _ _, rfl, map_add' := λ _ _, rfl, ..equiv.set_congr $ congr_arg _ h } /-- Restrict a ring homomorphism with a left inverse to a ring isomorphism to its `ring_hom.range`. -/ def of_left_inverse {g : S → R} {f : R →+* S} (h : function.left_inverse g f) : R ≃+* f.range := { to_fun := λ x, f.range_restrict x, inv_fun := λ x, (g ∘ f.range.subtype) x, left_inv := h, right_inv := λ x, subtype.ext $ let ⟨x', hx'⟩ := ring_hom.mem_range.mp x.prop in show f (g x) = x, by rw [←hx', h x'], ..f.range_restrict } @[simp] lemma of_left_inverse_apply {g : S → R} {f : R →+* S} (h : function.left_inverse g f) (x : R) : ↑(of_left_inverse h x) = f x := rfl @[simp] lemma of_left_inverse_symm_apply {g : S → R} {f : R →+* S} (h : function.left_inverse g f) (x : f.range) : (of_left_inverse h).symm x = g x := rfl /-- Given an equivalence `e : R ≃+* S` of rings and a subring `s` of `R`, `subring_equiv_map e s` is the induced equivalence between `s` and `s.map e` -/ @[simps] def subring_map (e : R ≃+* S) : s ≃+* s.map e.to_ring_hom := e.subsemiring_map s.to_subsemiring end ring_equiv namespace subring variables {s : set R} local attribute [reducible] closure @[elab_as_eliminator] protected theorem in_closure.rec_on {C : R → Prop} {x : R} (hx : x ∈ closure s) (h1 : C 1) (hneg1 : C (-1)) (hs : ∀ z ∈ s, ∀ n, C n → C (z * n)) (ha : ∀ {x y}, C x → C y → C (x + y)) : C x := begin have h0 : C 0 := add_neg_self (1:R) ▸ ha h1 hneg1, rcases exists_list_of_mem_closure hx with ⟨L, HL, rfl⟩, clear hx, induction L with hd tl ih, { exact h0 }, rw list.forall_mem_cons at HL, suffices : C (list.prod hd), { rw [list.map_cons, list.sum_cons], exact ha this (ih HL.2) }, replace HL := HL.1, clear ih tl, suffices : ∃ L : list R, (∀ x ∈ L, x ∈ s) ∧ (list.prod hd = list.prod L ∨ list.prod hd = -list.prod L), { rcases this with ⟨L, HL', HP | HP⟩, { rw HP, clear HP HL hd, induction L with hd tl ih, { exact h1 }, rw list.forall_mem_cons at HL', rw list.prod_cons, exact hs _ HL'.1 _ (ih HL'.2) }, rw HP, clear HP HL hd, induction L with hd tl ih, { exact hneg1 }, rw [list.prod_cons, neg_mul_eq_mul_neg], rw list.forall_mem_cons at HL', exact hs _ HL'.1 _ (ih HL'.2) }, induction hd with hd tl ih, { exact ⟨[], list.forall_mem_nil _, or.inl rfl⟩ }, rw list.forall_mem_cons at HL, rcases ih HL.2 with ⟨L, HL', HP | HP⟩; cases HL.1 with hhd hhd, { exact ⟨hd :: L, list.forall_mem_cons.2 ⟨hhd, HL'⟩, or.inl $ by rw [list.prod_cons, list.prod_cons, HP]⟩ }, { exact ⟨L, HL', or.inr $ by rw [list.prod_cons, hhd, neg_one_mul, HP]⟩ }, { exact ⟨hd :: L, list.forall_mem_cons.2 ⟨hhd, HL'⟩, or.inr $ by rw [list.prod_cons, list.prod_cons, HP, neg_mul_eq_mul_neg]⟩ }, { exact ⟨L, HL', or.inl $ by rw [list.prod_cons, hhd, HP, neg_one_mul, neg_neg]⟩ } end lemma closure_preimage_le (f : R →+* S) (s : set S) : closure (f ⁻¹' s) ≤ (closure s).comap f := closure_le.2 $ λ x hx, set_like.mem_coe.2 $ mem_comap.2 $ subset_closure hx end subring lemma add_subgroup.int_mul_mem {G : add_subgroup R} (k : ℤ) {g : R} (h : g ∈ G) : (k : R) * g ∈ G := by { convert add_subgroup.zsmul_mem G h k, simp } /-! ## Actions by `subring`s These are just copies of the definitions about `subsemiring` starting from `subsemiring.mul_action`. When `R` is commutative, `algebra.of_subring` provides a stronger result than those found in this file, which uses the same scalar action. -/ section actions namespace subring variables {α β : Type*} /-- The action by a subring is the action by the underlying ring. -/ instance [mul_action R α] (S : subring R) : mul_action S α := S.to_subsemiring.mul_action lemma smul_def [mul_action R α] {S : subring R} (g : S) (m : α) : g • m = (g : R) • m := rfl instance smul_comm_class_left [mul_action R β] [has_scalar α β] [smul_comm_class R α β] (S : subring R) : smul_comm_class S α β := S.to_subsemiring.smul_comm_class_left instance smul_comm_class_right [has_scalar α β] [mul_action R β] [smul_comm_class α R β] (S : subring R) : smul_comm_class α S β := S.to_subsemiring.smul_comm_class_right /-- Note that this provides `is_scalar_tower S R R` which is needed by `smul_mul_assoc`. -/ instance [has_scalar α β] [mul_action R α] [mul_action R β] [is_scalar_tower R α β] (S : subring R) : is_scalar_tower S α β := S.to_subsemiring.is_scalar_tower instance [mul_action R α] [has_faithful_scalar R α] (S : subring R) : has_faithful_scalar S α := S.to_subsemiring.has_faithful_scalar /-- The action by a subring is the action by the underlying ring. -/ instance [add_monoid α] [distrib_mul_action R α] (S : subring R) : distrib_mul_action S α := S.to_subsemiring.distrib_mul_action /-- The action by a subsemiring is the action by the underlying semiring. -/ instance [monoid α] [mul_distrib_mul_action R α] (S : subring R) : mul_distrib_mul_action S α := S.to_subsemiring.mul_distrib_mul_action /-- The action by a subring is the action by the underlying ring. -/ instance [add_comm_monoid α] [module R α] (S : subring R) : module S α := S.to_subsemiring.module end subring end actions -- while this definition is not about subrings, this is the earliest we have -- both ordered ring structures and submonoids available /-- The subgroup of positive units of a linear ordered semiring. -/ def units.pos_subgroup (R : Type*) [linear_ordered_semiring R] : subgroup Rˣ := { carrier := {x | (0 : R) < x}, inv_mem' := λ x, units.inv_pos.mpr, ..(pos_submonoid R).comap (units.coe_hom R)} @[simp] lemma units.mem_pos_subgroup {R : Type*} [linear_ordered_semiring R] (u : Rˣ) : u ∈ units.pos_subgroup R ↔ (0 : R) < u := iff.rfl
b99a5687351071938b6dee4af606d7bb167598ef
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Elab/Tactic/Split.lean
b44eff6fd00a05e8e569bb794ed33642b17fab4c
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,458
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Tactic.Split import Lean.Elab.Tactic.Basic import Lean.Elab.Tactic.Location namespace Lean.Elab.Tactic open Meta @[builtin_tactic Lean.Parser.Tactic.split] def evalSplit : Tactic := fun stx => do unless stx[1].isNone do throwError "'split' tactic, term to split is not supported yet" let loc := expandOptLocation stx[2] match loc with | Location.targets hyps simplifyTarget => if (hyps.size > 0 && simplifyTarget) || hyps.size > 1 then throwErrorAt stx[2] "'split' tactic failed, select a single target to split" if simplifyTarget then liftMetaTactic fun mvarId => do let some mvarIds ← splitTarget? mvarId | Meta.throwTacticEx `split mvarId "" return mvarIds else let fvarId ← getFVarId hyps[0]! liftMetaTactic fun mvarId => do let some mvarIds ← splitLocalDecl? mvarId fvarId | Meta.throwTacticEx `split mvarId "" return mvarIds | Location.wildcard => liftMetaTactic fun mvarId => do let fvarIds ← mvarId.getNondepPropHyps for fvarId in fvarIds do if let some mvarIds ← splitLocalDecl? mvarId fvarId then return mvarIds let some mvarIds ← splitTarget? mvarId | Meta.throwTacticEx `split mvarId "" return mvarIds end Lean.Elab.Tactic
39290e77d61d987291961a46e30f08e58eb202e7
626e312b5c1cb2d88fca108f5933076012633192
/src/set_theory/pgame.lean
199d020014465a6fa0a186c335a49feec2d7095a
[ "Apache-2.0" ]
permissive
Bioye97/mathlib
9db2f9ee54418d29dd06996279ba9dc874fd6beb
782a20a27ee83b523f801ff34efb1a9557085019
refs/heads/master
1,690,305,956,488
1,631,067,774,000
1,631,067,774,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
42,425
lean
/- Copyright (c) 2019 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Mario Carneiro, Isabel Longbottom, Scott Morrison -/ import logic.embedding import data.nat.cast import data.fin /-! # Combinatorial (pre-)games. The basic theory of combinatorial games, following Conway's book `On Numbers and Games`. We construct "pregames", define an ordering and arithmetic operations on them, then show that the operations descend to "games", defined via the equivalence relation `p ≈ q ↔ p ≤ q ∧ q ≤ p`. The surreal numbers will be built as a quotient of a subtype of pregames. A pregame (`pgame` below) is axiomatised via an inductive type, whose sole constructor takes two types (thought of as indexing the the possible moves for the players Left and Right), and a pair of functions out of these types to `pgame` (thought of as describing the resulting game after making a move). Combinatorial games themselves, as a quotient of pregames, are constructed in `game.lean`. ## Conway induction By construction, the induction principle for pregames is exactly "Conway induction". That is, to prove some predicate `pgame → Prop` holds for all pregames, it suffices to prove that for every pregame `g`, if the predicate holds for every game resulting from making a move, then it also holds for `g`. While it is often convenient to work "by induction" on pregames, in some situations this becomes awkward, so we also define accessor functions `left_moves`, `right_moves`, `move_left` and `move_right`. There is a relation `subsequent p q`, saying that `p` can be reached by playing some non-empty sequence of moves starting from `q`, an instance `well_founded subsequent`, and a local tactic `pgame_wf_tac` which is helpful for discharging proof obligations in inductive proofs relying on this relation. ## Order properties Pregames have both a `≤` and a `<` relation, which are related in quite a subtle way. In particular, it is worth noting that in Lean's (perhaps unfortunate?) definition of a `preorder`, we have `lt_iff_le_not_le : ∀ a b : α, a < b ↔ (a ≤ b ∧ ¬ b ≤ a)`, but this is _not_ satisfied by the usual `≤` and `<` relations on pregames. (It is satisfied once we restrict to the surreal numbers.) In particular, `<` is not transitive; there is an example below showing `0 < star ∧ star < 0`. We do have ``` theorem not_le {x y : pgame} : ¬ x ≤ y ↔ y < x := ... theorem not_lt {x y : pgame} : ¬ x < y ↔ y ≤ x := ... ``` The statement `0 ≤ x` means that Left has a good response to any move by Right; in particular, the theorem `zero_le` below states ``` 0 ≤ x ↔ ∀ j : x.right_moves, ∃ i : (x.move_right j).left_moves, 0 ≤ (x.move_right j).move_left i ``` On the other hand the statement `0 < x` means that Left has a good move right now; in particular the theorem `zero_lt` below states ``` 0 < x ↔ ∃ i : left_moves x, ∀ j : right_moves (x.move_left i), 0 < (x.move_left i).move_right j ``` The theorems `le_def`, `lt_def`, give a recursive characterisation of each relation, in terms of themselves two moves later. The theorems `le_def_lt` and `lt_def_lt` give recursive characterisations of each relation in terms of the other relation one move later. We define an equivalence relation `equiv p q ↔ p ≤ q ∧ q ≤ p`. Later, games will be defined as the quotient by this relation. ## Algebraic structures We next turn to defining the operations necessary to make games into a commutative additive group. Addition is defined for $x = \{xL | xR\}$ and $y = \{yL | yR\}$ by $x + y = \{xL + y, x + yL | xR + y, x + yR\}$. Negation is defined by $\{xL | xR\} = \{-xR | -xL\}$. The order structures interact in the expected way with addition, so we have ``` theorem le_iff_sub_nonneg {x y : pgame} : x ≤ y ↔ 0 ≤ y - x := sorry theorem lt_iff_sub_pos {x y : pgame} : x < y ↔ 0 < y - x := sorry ``` We show that these operations respect the equivalence relation, and hence descend to games. At the level of games, these operations satisfy all the laws of a commutative group. To prove the necessary equivalence relations at the level of pregames, we introduce the notion of a `relabelling` of a game, and show, for example, that there is a relabelling between `x + (y + z)` and `(x + y) + z`. ## Future work * The theory of dominated and reversible positions, and unique normal form for short games. * Analysis of basic domineering positions. * Hex. * Temperature. * The development of surreal numbers, based on this development of combinatorial games, is still quite incomplete. ## References The material here is all drawn from * [Conway, *On numbers and games*][conway2001] An interested reader may like to formalise some of the material from * [Andreas Blass, *A game semantics for linear logic*][MR1167694] * [André Joyal, *Remarques sur la théorie des jeux à deux personnes*][joyal1997] -/ universes u /-- The type of pre-games, before we have quotiented by extensionality. In ZFC, a combinatorial game is constructed from two sets of combinatorial games that have been constructed at an earlier stage. To do this in type theory, we say that a pre-game is built inductively from two families of pre-games indexed over any type in Type u. The resulting type `pgame.{u}` lives in `Type (u+1)`, reflecting that it is a proper class in ZFC. -/ inductive pgame : Type (u+1) | mk : ∀ α β : Type u, (α → pgame) → (β → pgame) → pgame namespace pgame /-- Construct a pre-game from list of pre-games describing the available moves for Left and Right. -/ -- TODO provide some API describing the interaction with -- `left_moves`, `right_moves`, `move_left` and `move_right` below. -- TODO define this at the level of games, as well, and perhaps also for finsets of games. def of_lists (L R : list pgame.{0}) : pgame.{0} := pgame.mk (fin L.length) (fin R.length) (λ i, L.nth_le i i.is_lt) (λ j, R.nth_le j.val j.is_lt) /-- The indexing type for allowable moves by Left. -/ def left_moves : pgame → Type u | (mk l _ _ _) := l /-- The indexing type for allowable moves by Right. -/ def right_moves : pgame → Type u | (mk _ r _ _) := r /-- The new game after Left makes an allowed move. -/ def move_left : Π (g : pgame), left_moves g → pgame | (mk l _ L _) i := L i /-- The new game after Right makes an allowed move. -/ def move_right : Π (g : pgame), right_moves g → pgame | (mk _ r _ R) j := R j @[simp] lemma left_moves_mk {xl xr xL xR} : (⟨xl, xr, xL, xR⟩ : pgame).left_moves = xl := rfl @[simp] lemma move_left_mk {xl xr xL xR i} : (⟨xl, xr, xL, xR⟩ : pgame).move_left i = xL i := rfl @[simp] lemma right_moves_mk {xl xr xL xR} : (⟨xl, xr, xL, xR⟩ : pgame).right_moves = xr := rfl @[simp] lemma move_right_mk {xl xr xL xR j} : (⟨xl, xr, xL, xR⟩ : pgame).move_right j = xR j := rfl /-- `subsequent p q` says that `p` can be obtained by playing some nonempty sequence of moves from `q`. -/ inductive subsequent : pgame → pgame → Prop | left : Π (x : pgame) (i : x.left_moves), subsequent (x.move_left i) x | right : Π (x : pgame) (j : x.right_moves), subsequent (x.move_right j) x | trans : Π (x y z : pgame), subsequent x y → subsequent y z → subsequent x z theorem wf_subsequent : well_founded subsequent := ⟨λ x, begin induction x with l r L R IHl IHr, refine ⟨_, λ y h, _⟩, generalize_hyp e : mk l r L R = x at h, induction h with _ i _ j a b _ h1 h2 IH1 IH2; subst e, { apply IHl }, { apply IHr }, { exact acc.inv (IH2 rfl) h1 } end⟩ instance : has_well_founded pgame := { r := subsequent, wf := wf_subsequent } /-- A move by Left produces a subsequent game. (For use in pgame_wf_tac.) -/ lemma subsequent.left_move {xl xr} {xL : xl → pgame} {xR : xr → pgame} {i : xl} : subsequent (xL i) (mk xl xr xL xR) := subsequent.left (mk xl xr xL xR) i /-- A move by Right produces a subsequent game. (For use in pgame_wf_tac.) -/ lemma subsequent.right_move {xl xr} {xL : xl → pgame} {xR : xr → pgame} {j : xr} : subsequent (xR j) (mk xl xr xL xR) := subsequent.right (mk xl xr xL xR) j /-- A local tactic for proving well-foundedness of recursive definitions involving pregames. -/ meta def pgame_wf_tac := `[solve_by_elim [psigma.lex.left, psigma.lex.right, subsequent.left_move, subsequent.right_move, subsequent.left, subsequent.right, subsequent.trans] { max_depth := 6 }] /-- The pre-game `zero` is defined by `0 = { | }`. -/ instance : has_zero pgame := ⟨⟨pempty, pempty, pempty.elim, pempty.elim⟩⟩ @[simp] lemma zero_left_moves : (0 : pgame).left_moves = pempty := rfl @[simp] lemma zero_right_moves : (0 : pgame).right_moves = pempty := rfl instance : inhabited pgame := ⟨0⟩ /-- The pre-game `one` is defined by `1 = { 0 | }`. -/ instance : has_one pgame := ⟨⟨punit, pempty, λ _, 0, pempty.elim⟩⟩ @[simp] lemma one_left_moves : (1 : pgame).left_moves = punit := rfl @[simp] lemma one_move_left : (1 : pgame).move_left punit.star = 0 := rfl @[simp] lemma one_right_moves : (1 : pgame).right_moves = pempty := rfl /-- Define simultaneously by mutual induction the `<=` and `<` relation on pre-games. The ZFC definition says that `x = {xL | xR}` is less or equal to `y = {yL | yR}` if `∀ x₁ ∈ xL, x₁ < y` and `∀ y₂ ∈ yR, x < y₂`, where `x < y` is the same as `¬ y <= x`. This is a tricky induction because it only decreases one side at a time, and it also swaps the arguments in the definition of `<`. The solution is to define `x < y` and `x <= y` simultaneously. -/ def le_lt : Π (x y : pgame), Prop × Prop | (mk xl xr xL xR) (mk yl yr yL yR) := -- the orderings of the clauses here are carefully chosen so that -- and.left/or.inl refer to moves by Left, and -- and.right/or.inr refer to moves by Right. ((∀ i : xl, (le_lt (xL i) ⟨yl, yr, yL, yR⟩).2) ∧ (∀ j : yr, (le_lt ⟨xl, xr, xL, xR⟩ (yR j)).2), (∃ i : yl, (le_lt ⟨xl, xr, xL, xR⟩ (yL i)).1) ∨ (∃ j : xr, (le_lt (xR j) ⟨yl, yr, yL, yR⟩).1)) using_well_founded { dec_tac := pgame_wf_tac } instance : has_le pgame := ⟨λ x y, (le_lt x y).1⟩ instance : has_lt pgame := ⟨λ x y, (le_lt x y).2⟩ /-- Definition of `x ≤ y` on pre-games built using the constructor. -/ @[simp] theorem mk_le_mk {xl xr xL xR yl yr yL yR} : (⟨xl, xr, xL, xR⟩ : pgame) ≤ ⟨yl, yr, yL, yR⟩ ↔ (∀ i, xL i < ⟨yl, yr, yL, yR⟩) ∧ (∀ j, (⟨xl, xr, xL, xR⟩ : pgame) < yR j) := show (le_lt _ _).1 ↔ _, by { rw le_lt, refl } /-- Definition of `x ≤ y` on pre-games, in terms of `<` -/ theorem le_def_lt {x y : pgame} : x ≤ y ↔ (∀ i : x.left_moves, x.move_left i < y) ∧ (∀ j : y.right_moves, x < y.move_right j) := by { cases x, cases y, rw mk_le_mk, refl } /-- Definition of `x < y` on pre-games built using the constructor. -/ @[simp] theorem mk_lt_mk {xl xr xL xR yl yr yL yR} : (⟨xl, xr, xL, xR⟩ : pgame) < ⟨yl, yr, yL, yR⟩ ↔ (∃ i, (⟨xl, xr, xL, xR⟩ : pgame) ≤ yL i) ∨ (∃ j, xR j ≤ ⟨yl, yr, yL, yR⟩) := show (le_lt _ _).2 ↔ _, by { rw le_lt, refl } /-- Definition of `x < y` on pre-games, in terms of `≤` -/ theorem lt_def_le {x y : pgame} : x < y ↔ (∃ i : y.left_moves, x ≤ y.move_left i) ∨ (∃ j : x.right_moves, x.move_right j ≤ y) := by { cases x, cases y, rw mk_lt_mk, refl } /-- The definition of `x ≤ y` on pre-games, in terms of `≤` two moves later. -/ theorem le_def {x y : pgame} : x ≤ y ↔ (∀ i : x.left_moves, (∃ i' : y.left_moves, x.move_left i ≤ y.move_left i') ∨ (∃ j : (x.move_left i).right_moves, (x.move_left i).move_right j ≤ y)) ∧ (∀ j : y.right_moves, (∃ i : (y.move_right j).left_moves, x ≤ (y.move_right j).move_left i) ∨ (∃ j' : x.right_moves, x.move_right j' ≤ y.move_right j)) := begin rw [le_def_lt], conv { to_lhs, simp only [lt_def_le] }, end /-- The definition of `x < y` on pre-games, in terms of `<` two moves later. -/ theorem lt_def {x y : pgame} : x < y ↔ (∃ i : y.left_moves, (∀ i' : x.left_moves, x.move_left i' < y.move_left i) ∧ (∀ j : (y.move_left i).right_moves, x < (y.move_left i).move_right j)) ∨ (∃ j : x.right_moves, (∀ i : (x.move_right j).left_moves, (x.move_right j).move_left i < y) ∧ (∀ j' : y.right_moves, x.move_right j < y.move_right j')) := begin rw [lt_def_le], conv { to_lhs, simp only [le_def_lt] }, end /-- The definition of `x ≤ 0` on pre-games, in terms of `≤ 0` two moves later. -/ theorem le_zero {x : pgame} : x ≤ 0 ↔ ∀ i : x.left_moves, ∃ j : (x.move_left i).right_moves, (x.move_left i).move_right j ≤ 0 := begin rw le_def, dsimp, simp [forall_pempty, exists_pempty] end /-- The definition of `0 ≤ x` on pre-games, in terms of `0 ≤` two moves later. -/ theorem zero_le {x : pgame} : 0 ≤ x ↔ ∀ j : x.right_moves, ∃ i : (x.move_right j).left_moves, 0 ≤ (x.move_right j).move_left i := begin rw le_def, dsimp, simp [forall_pempty, exists_pempty] end /-- The definition of `x < 0` on pre-games, in terms of `< 0` two moves later. -/ theorem lt_zero {x : pgame} : x < 0 ↔ ∃ j : x.right_moves, ∀ i : (x.move_right j).left_moves, (x.move_right j).move_left i < 0 := begin rw lt_def, dsimp, simp [forall_pempty, exists_pempty] end /-- The definition of `0 < x` on pre-games, in terms of `< x` two moves later. -/ theorem zero_lt {x : pgame} : 0 < x ↔ ∃ i : x.left_moves, ∀ j : (x.move_left i).right_moves, 0 < (x.move_left i).move_right j := begin rw lt_def, dsimp, simp [forall_pempty, exists_pempty] end /-- Given a right-player-wins game, provide a response to any move by left. -/ noncomputable def right_response {x : pgame} (h : x ≤ 0) (i : x.left_moves) : (x.move_left i).right_moves := classical.some $ (le_zero.1 h) i /-- Show that the response for right provided by `right_response` preserves the right-player-wins condition. -/ lemma right_response_spec {x : pgame} (h : x ≤ 0) (i : x.left_moves) : (x.move_left i).move_right (right_response h i) ≤ 0 := classical.some_spec $ (le_zero.1 h) i /-- Given a left-player-wins game, provide a response to any move by right. -/ noncomputable def left_response {x : pgame} (h : 0 ≤ x) (j : x.right_moves) : (x.move_right j).left_moves := classical.some $ (zero_le.1 h) j /-- Show that the response for left provided by `left_response` preserves the left-player-wins condition. -/ lemma left_response_spec {x : pgame} (h : 0 ≤ x) (j : x.right_moves) : 0 ≤ (x.move_right j).move_left (left_response h j) := classical.some_spec $ (zero_le.1 h) j theorem lt_of_le_mk {xl xr xL xR y i} : (⟨xl, xr, xL, xR⟩ : pgame) ≤ y → xL i < y := by { cases y, rw mk_le_mk, tauto } theorem lt_of_mk_le {x : pgame} {yl yr yL yR i} : x ≤ ⟨yl, yr, yL, yR⟩ → x < yR i := by { cases x, rw mk_le_mk, tauto } theorem mk_lt_of_le {xl xr xL xR y i} : (by exact xR i ≤ y) → (⟨xl, xr, xL, xR⟩ : pgame) < y := by { cases y, rw mk_lt_mk, tauto } theorem lt_mk_of_le {x : pgame} {yl yr yL yR i} : (by exact x ≤ yL i) → x < ⟨yl, yr, yL, yR⟩ := by { cases x, rw mk_lt_mk, exact λ h, or.inl ⟨_, h⟩ } theorem not_le_lt {x y : pgame} : (¬ x ≤ y ↔ y < x) ∧ (¬ x < y ↔ y ≤ x) := begin induction x with xl xr xL xR IHxl IHxr generalizing y, induction y with yl yr yL yR IHyl IHyr, classical, simp only [mk_le_mk, mk_lt_mk, not_and_distrib, not_or_distrib, not_forall, not_exists, and_comm, or_comm, IHxl, IHxr, IHyl, IHyr, iff_self, and_self] end theorem not_le {x y : pgame} : ¬ x ≤ y ↔ y < x := not_le_lt.1 theorem not_lt {x y : pgame} : ¬ x < y ↔ y ≤ x := not_le_lt.2 @[refl] protected theorem le_refl : ∀ x : pgame, x ≤ x | ⟨l, r, L, R⟩ := by rw mk_le_mk; exact ⟨λ i, lt_mk_of_le (le_refl _), λ i, mk_lt_of_le (le_refl _)⟩ protected theorem lt_irrefl (x : pgame) : ¬ x < x := not_lt.2 (pgame.le_refl _) protected theorem ne_of_lt : ∀ {x y : pgame}, x < y → x ≠ y | x _ h rfl := pgame.lt_irrefl x h theorem le_trans_aux {xl xr} {xL : xl → pgame} {xR : xr → pgame} {yl yr} {yL : yl → pgame} {yR : yr → pgame} {zl zr} {zL : zl → pgame} {zR : zr → pgame} (h₁ : ∀ i, mk yl yr yL yR ≤ mk zl zr zL zR → mk zl zr zL zR ≤ xL i → mk yl yr yL yR ≤ xL i) (h₂ : ∀ i, zR i ≤ mk xl xr xL xR → mk xl xr xL xR ≤ mk yl yr yL yR → zR i ≤ mk yl yr yL yR) : mk xl xr xL xR ≤ mk yl yr yL yR → mk yl yr yL yR ≤ mk zl zr zL zR → mk xl xr xL xR ≤ mk zl zr zL zR := by simp only [mk_le_mk] at *; exact λ ⟨xLy, xyR⟩ ⟨yLz, yzR⟩, ⟨ λ i, not_le.1 (λ h, not_lt.2 (h₁ _ ⟨yLz, yzR⟩ h) (xLy _)), λ i, not_le.1 (λ h, not_lt.2 (h₂ _ h ⟨xLy, xyR⟩) (yzR _))⟩ @[trans] theorem le_trans {x y z : pgame} : x ≤ y → y ≤ z → x ≤ z := suffices ∀ {x y z : pgame}, (x ≤ y → y ≤ z → x ≤ z) ∧ (y ≤ z → z ≤ x → y ≤ x) ∧ (z ≤ x → x ≤ y → z ≤ y), from this.1, begin clear x y z, intros, induction x with xl xr xL xR IHxl IHxr generalizing y z, induction y with yl yr yL yR IHyl IHyr generalizing z, induction z with zl zr zL zR IHzl IHzr, exact ⟨ le_trans_aux (λ i, (IHxl _).2.1) (λ i, (IHzr _).2.2), le_trans_aux (λ i, (IHyl _).2.2) (λ i, (IHxr _).1), le_trans_aux (λ i, (IHzl _).1) (λ i, (IHyr _).2.1)⟩, end @[trans] theorem lt_of_le_of_lt {x y z : pgame} (hxy : x ≤ y) (hyz : y < z) : x < z := begin rw ←not_le at ⊢ hyz, exact mt (λ H, le_trans H hxy) hyz end @[trans] theorem lt_of_lt_of_le {x y z : pgame} (hxy : x < y) (hyz : y ≤ z) : x < z := begin rw ←not_le at ⊢ hxy, exact mt (λ H, le_trans hyz H) hxy end /-- Define the equivalence relation on pre-games. Two pre-games `x`, `y` are equivalent if `x ≤ y` and `y ≤ x`. -/ def equiv (x y : pgame) : Prop := x ≤ y ∧ y ≤ x local infix ` ≈ ` := pgame.equiv @[refl, simp] theorem equiv_refl (x) : x ≈ x := ⟨pgame.le_refl _, pgame.le_refl _⟩ @[symm] theorem equiv_symm {x y} : x ≈ y → y ≈ x | ⟨xy, yx⟩ := ⟨yx, xy⟩ @[trans] theorem equiv_trans {x y z} : x ≈ y → y ≈ z → x ≈ z | ⟨xy, yx⟩ ⟨yz, zy⟩ := ⟨le_trans xy yz, le_trans zy yx⟩ theorem lt_of_lt_of_equiv {x y z} (h₁ : x < y) (h₂ : y ≈ z) : x < z := lt_of_lt_of_le h₁ h₂.1 theorem le_of_le_of_equiv {x y z} (h₁ : x ≤ y) (h₂ : y ≈ z) : x ≤ z := le_trans h₁ h₂.1 theorem lt_of_equiv_of_lt {x y z} (h₁ : x ≈ y) (h₂ : y < z) : x < z := lt_of_le_of_lt h₁.1 h₂ theorem le_of_equiv_of_le {x y z} (h₁ : x ≈ y) (h₂ : y ≤ z) : x ≤ z := le_trans h₁.1 h₂ theorem le_congr {x₁ y₁ x₂ y₂} : x₁ ≈ x₂ → y₁ ≈ y₂ → (x₁ ≤ y₁ ↔ x₂ ≤ y₂) | ⟨x12, x21⟩ ⟨y12, y21⟩ := ⟨λ h, le_trans x21 (le_trans h y12), λ h, le_trans x12 (le_trans h y21)⟩ theorem lt_congr {x₁ y₁ x₂ y₂} (hx : x₁ ≈ x₂) (hy : y₁ ≈ y₂) : x₁ < y₁ ↔ x₂ < y₂ := not_le.symm.trans $ (not_congr (le_congr hy hx)).trans not_le theorem equiv_congr_left {y₁ y₂} : y₁ ≈ y₂ ↔ ∀ x₁, x₁ ≈ y₁ ↔ x₁ ≈ y₂ := ⟨λ h x₁, ⟨λ h', equiv_trans h' h, λ h', equiv_trans h' (equiv_symm h)⟩, λ h, (h y₁).1 $ equiv_refl _⟩ theorem equiv_congr_right {x₁ x₂} : x₁ ≈ x₂ ↔ ∀ y₁, x₁ ≈ y₁ ↔ x₂ ≈ y₁ := ⟨λ h y₁, ⟨λ h', equiv_trans (equiv_symm h) h', λ h', equiv_trans h h'⟩, λ h, (h x₂).2 $ equiv_refl _⟩ theorem equiv_of_mk_equiv {x y : pgame} (L : x.left_moves ≃ y.left_moves) (R : x.right_moves ≃ y.right_moves) (hl : ∀ (i : x.left_moves), x.move_left i ≈ y.move_left (L i)) (hr : ∀ (j : y.right_moves), x.move_right (R.symm j) ≈ y.move_right j) : x ≈ y := begin fsplit; rw le_def, { exact ⟨λ i, or.inl ⟨L i, (hl i).1⟩, λ j, or.inr ⟨R.symm j, (hr j).1⟩⟩ }, { fsplit, { intro i, left, specialize hl (L.symm i), simp only [move_left_mk, equiv.apply_symm_apply] at hl, use ⟨L.symm i, hl.2⟩ }, { intro j, right, specialize hr (R j), simp only [move_right_mk, equiv.symm_apply_apply] at hr, use ⟨R j, hr.2⟩ } } end /-- `restricted x y` says that Left always has no more moves in `x` than in `y`, and Right always has no more moves in `y` than in `x` -/ inductive restricted : pgame.{u} → pgame.{u} → Type (u+1) | mk : Π {x y : pgame} (L : x.left_moves → y.left_moves) (R : y.right_moves → x.right_moves), (∀ (i : x.left_moves), restricted (x.move_left i) (y.move_left (L i))) → (∀ (j : y.right_moves), restricted (x.move_right (R j)) (y.move_right j)) → restricted x y /-- The identity restriction. -/ @[refl] def restricted.refl : Π (x : pgame), restricted x x | (mk xl xr xL xR) := restricted.mk id id (λ i, restricted.refl _) (λ j, restricted.refl _) using_well_founded { dec_tac := pgame_wf_tac } -- TODO trans for restricted theorem restricted.le : Π {x y : pgame} (r : restricted x y), x ≤ y | (mk xl xr xL xR) (mk yl yr yL yR) (restricted.mk L_embedding R_embedding L_restriction R_restriction) := begin rw le_def, exact ⟨λ i, or.inl ⟨L_embedding i, (L_restriction i).le⟩, λ i, or.inr ⟨R_embedding i, (R_restriction i).le⟩⟩ end /-- `relabelling x y` says that `x` and `y` are really the same game, just dressed up differently. Specifically, there is a bijection between the moves for Left in `x` and in `y`, and similarly for Right, and under these bijections we inductively have `relabelling`s for the consequent games. -/ inductive relabelling : pgame.{u} → pgame.{u} → Type (u+1) | mk : Π {x y : pgame} (L : x.left_moves ≃ y.left_moves) (R : x.right_moves ≃ y.right_moves), (∀ (i : x.left_moves), relabelling (x.move_left i) (y.move_left (L i))) → (∀ (j : y.right_moves), relabelling (x.move_right (R.symm j)) (y.move_right j)) → relabelling x y /-- If `x` is a relabelling of `y`, then Left and Right have the same moves in either game, so `x` is a restriction of `y`. -/ def relabelling.restricted: Π {x y : pgame} (r : relabelling x y), restricted x y | (mk xl xr xL xR) (mk yl yr yL yR) (relabelling.mk L_equiv R_equiv L_relabelling R_relabelling) := restricted.mk L_equiv.to_embedding R_equiv.symm.to_embedding (λ i, (L_relabelling i).restricted) (λ j, (R_relabelling j).restricted) -- It's not the case that `restricted x y → restricted y x → relabelling x y`, -- but if we insisted that the maps in a restriction were injective, then one -- could use Schröder-Bernstein for do this. /-- The identity relabelling. -/ @[refl] def relabelling.refl : Π (x : pgame), relabelling x x | (mk xl xr xL xR) := relabelling.mk (equiv.refl _) (equiv.refl _) (λ i, relabelling.refl _) (λ j, relabelling.refl _) using_well_founded { dec_tac := pgame_wf_tac } /-- Reverse a relabelling. -/ @[symm] def relabelling.symm : Π {x y : pgame}, relabelling x y → relabelling y x | (mk xl xr xL xR) (mk yl yr yL yR) (relabelling.mk L_equiv R_equiv L_relabelling R_relabelling) := begin refine relabelling.mk L_equiv.symm R_equiv.symm _ _, { intro i, simpa using (L_relabelling (L_equiv.symm i)).symm }, { intro j, simpa using (R_relabelling (R_equiv j)).symm } end /-- Transitivity of relabelling -/ @[trans] def relabelling.trans : Π {x y z : pgame}, relabelling x y → relabelling y z → relabelling x z | (mk xl xr xL xR) (mk yl yr yL yR) (mk zl zr zL zR) (relabelling.mk L_equiv₁ R_equiv₁ L_relabelling₁ R_relabelling₁) (relabelling.mk L_equiv₂ R_equiv₂ L_relabelling₂ R_relabelling₂) := begin refine relabelling.mk (L_equiv₁.trans L_equiv₂) (R_equiv₁.trans R_equiv₂) _ _, { intro i, simpa using (L_relabelling₁ _).trans (L_relabelling₂ _) }, { intro j, simpa using (R_relabelling₁ _).trans (R_relabelling₂ _) }, end theorem relabelling.le {x y : pgame} (r : relabelling x y) : x ≤ y := r.restricted.le /-- A relabelling lets us prove equivalence of games. -/ theorem relabelling.equiv {x y : pgame} (r : relabelling x y) : x ≈ y := ⟨r.le, r.symm.le⟩ instance {x y : pgame} : has_coe (relabelling x y) (x ≈ y) := ⟨relabelling.equiv⟩ /-- Replace the types indexing the next moves for Left and Right by equivalent types. -/ def relabel {x : pgame} {xl' xr'} (el : x.left_moves ≃ xl') (er : x.right_moves ≃ xr') := pgame.mk xl' xr' (λ i, x.move_left (el.symm i)) (λ j, x.move_right (er.symm j)) @[simp] lemma relabel_move_left' {x : pgame} {xl' xr'} (el : x.left_moves ≃ xl') (er : x.right_moves ≃ xr') (i : xl') : move_left (relabel el er) i = x.move_left (el.symm i) := rfl @[simp] lemma relabel_move_left {x : pgame} {xl' xr'} (el : x.left_moves ≃ xl') (er : x.right_moves ≃ xr') (i : x.left_moves) : move_left (relabel el er) (el i) = x.move_left i := by simp @[simp] lemma relabel_move_right' {x : pgame} {xl' xr'} (el : x.left_moves ≃ xl') (er : x.right_moves ≃ xr') (j : xr') : move_right (relabel el er) j = x.move_right (er.symm j) := rfl @[simp] lemma relabel_move_right {x : pgame} {xl' xr'} (el : x.left_moves ≃ xl') (er : x.right_moves ≃ xr') (j : x.right_moves) : move_right (relabel el er) (er j) = x.move_right j := by simp /-- The game obtained by relabelling the next moves is a relabelling of the original game. -/ def relabel_relabelling {x : pgame} {xl' xr'} (el : x.left_moves ≃ xl') (er : x.right_moves ≃ xr') : relabelling x (relabel el er) := relabelling.mk el er (λ i, by simp) (λ j, by simp) /-- The negation of `{L | R}` is `{-R | -L}`. -/ def neg : pgame → pgame | ⟨l, r, L, R⟩ := ⟨r, l, λ i, neg (R i), λ i, neg (L i)⟩ instance : has_neg pgame := ⟨neg⟩ @[simp] lemma neg_def {xl xr xL xR} : -(mk xl xr xL xR) = mk xr xl (λ j, -(xR j)) (λ i, -(xL i)) := rfl @[simp] theorem neg_neg : Π {x : pgame}, -(-x) = x | (mk xl xr xL xR) := begin dsimp [has_neg.neg, neg], congr; funext i; apply neg_neg end @[simp] theorem neg_zero : -(0 : pgame) = 0 := begin dsimp [has_zero.zero, has_neg.neg, neg], congr; funext i; cases i end /-- An explicit equivalence between the moves for Left in `-x` and the moves for Right in `x`. -/ -- This equivalence is useful to avoid having to use `cases` unnecessarily. def left_moves_neg (x : pgame) : (-x).left_moves ≃ x.right_moves := by { cases x, refl } /-- An explicit equivalence between the moves for Right in `-x` and the moves for Left in `x`. -/ def right_moves_neg (x : pgame) : (-x).right_moves ≃ x.left_moves := by { cases x, refl } @[simp] lemma move_right_left_moves_neg {x : pgame} (i : left_moves (-x)) : move_right x ((left_moves_neg x) i) = -(move_left (-x) i) := begin induction x, exact neg_neg.symm end @[simp] lemma move_left_left_moves_neg_symm {x : pgame} (i : right_moves x) : move_left (-x) ((left_moves_neg x).symm i) = -(move_right x i) := by { cases x, refl } @[simp] lemma move_left_right_moves_neg {x : pgame} (i : right_moves (-x)) : move_left x ((right_moves_neg x) i) = -(move_right (-x) i) := begin induction x, exact neg_neg.symm end @[simp] lemma move_right_right_moves_neg_symm {x : pgame} (i : left_moves x) : move_right (-x) ((right_moves_neg x).symm i) = -(move_left x i) := by { cases x, refl } /-- If `x` has the same moves as `y`, then `-x` has the sames moves as `-y`. -/ def relabelling.neg_congr : ∀ {x y : pgame}, x.relabelling y → (-x).relabelling (-y) | (mk xl xr xL xR) (mk yl yr yL yR) ⟨L_equiv, R_equiv, L_relabelling, R_relabelling⟩ := ⟨R_equiv, L_equiv, λ i, relabelling.neg_congr (by simpa using R_relabelling (R_equiv i)), λ i, relabelling.neg_congr (by simpa using L_relabelling (L_equiv.symm i))⟩ theorem le_iff_neg_ge : Π {x y : pgame}, x ≤ y ↔ -y ≤ -x | (mk xl xr xL xR) (mk yl yr yL yR) := begin rw [le_def], rw [le_def], dsimp [neg], split, { intro h, split, { intro i, have t := h.right i, cases t, { right, cases t, use (@right_moves_neg (yR i)).symm t_w, convert le_iff_neg_ge.1 t_h, simp }, { left, cases t, use t_w, exact le_iff_neg_ge.1 t_h, } }, { intro j, have t := h.left j, cases t, { right, cases t, use t_w, exact le_iff_neg_ge.1 t_h, }, { left, cases t, use (@left_moves_neg (xL j)).symm t_w, convert le_iff_neg_ge.1 t_h, simp, } } }, { intro h, split, { intro i, have t := h.right i, cases t, { right, cases t, use (@left_moves_neg (xL i)) t_w, convert le_iff_neg_ge.2 _, convert t_h, simp, }, { left, cases t, use t_w, exact le_iff_neg_ge.2 t_h, } }, { intro j, have t := h.left j, cases t, { right, cases t, use t_w, exact le_iff_neg_ge.2 t_h, }, { left, cases t, use (@right_moves_neg (yR j)) t_w, convert le_iff_neg_ge.2 _, convert t_h, simp } } }, end using_well_founded { dec_tac := pgame_wf_tac } theorem neg_congr {x y : pgame} (h : x ≈ y) : -x ≈ -y := ⟨le_iff_neg_ge.1 h.2, le_iff_neg_ge.1 h.1⟩ theorem lt_iff_neg_gt : Π {x y : pgame}, x < y ↔ -y < -x := begin classical, intros, rw [←not_le, ←not_le, not_iff_not], apply le_iff_neg_ge end theorem zero_le_iff_neg_le_zero {x : pgame} : 0 ≤ x ↔ -x ≤ 0 := begin convert le_iff_neg_ge, rw neg_zero end theorem le_zero_iff_zero_le_neg {x : pgame} : x ≤ 0 ↔ 0 ≤ -x := begin convert le_iff_neg_ge, rw neg_zero end /-- The sum of `x = {xL | xR}` and `y = {yL | yR}` is `{xL + y, x + yL | xR + y, x + yR}`. -/ def add (x y : pgame) : pgame := begin induction x with xl xr xL xR IHxl IHxr generalizing y, induction y with yl yr yL yR IHyl IHyr, have y := mk yl yr yL yR, refine ⟨xl ⊕ yl, xr ⊕ yr, sum.rec _ _, sum.rec _ _⟩, { exact λ i, IHxl i y }, { exact λ i, IHyl i }, { exact λ i, IHxr i y }, { exact λ i, IHyr i } end instance : has_add pgame := ⟨add⟩ /-- `x + 0` has exactly the same moves as `x`. -/ def add_zero_relabelling : Π (x : pgame.{u}), relabelling (x + 0) x | (mk xl xr xL xR) := begin refine ⟨equiv.sum_empty xl pempty, equiv.sum_empty xr pempty, _, _⟩, { rintro (⟨i⟩|⟨⟨⟩⟩), apply add_zero_relabelling, }, { rintro j, apply add_zero_relabelling, } end /-- `x + 0` is equivalent to `x`. -/ lemma add_zero_equiv (x : pgame.{u}) : x + 0 ≈ x := (add_zero_relabelling x).equiv /-- `0 + x` has exactly the same moves as `x`. -/ def zero_add_relabelling : Π (x : pgame.{u}), relabelling (0 + x) x | (mk xl xr xL xR) := begin refine ⟨equiv.empty_sum pempty xl, equiv.empty_sum pempty xr, _, _⟩, { rintro (⟨⟨⟩⟩|⟨i⟩), apply zero_add_relabelling, }, { rintro j, apply zero_add_relabelling, } end /-- `0 + x` is equivalent to `x`. -/ lemma zero_add_equiv (x : pgame.{u}) : 0 + x ≈ x := (zero_add_relabelling x).equiv /-- An explicit equivalence between the moves for Left in `x + y` and the type-theory sum of the moves for Left in `x` and in `y`. -/ def left_moves_add (x y : pgame) : (x + y).left_moves ≃ x.left_moves ⊕ y.left_moves := by { cases x, cases y, refl, } /-- An explicit equivalence between the moves for Right in `x + y` and the type-theory sum of the moves for Right in `x` and in `y`. -/ def right_moves_add (x y : pgame) : (x + y).right_moves ≃ x.right_moves ⊕ y.right_moves := by { cases x, cases y, refl, } @[simp] lemma mk_add_move_left_inl {xl xr yl yr} {xL xR yL yR} {i} : (mk xl xr xL xR + mk yl yr yL yR).move_left (sum.inl i) = (mk xl xr xL xR).move_left i + (mk yl yr yL yR) := rfl @[simp] lemma add_move_left_inl {x y : pgame} {i} : (x + y).move_left ((@left_moves_add x y).symm (sum.inl i)) = x.move_left i + y := by { cases x, cases y, refl, } @[simp] lemma mk_add_move_right_inl {xl xr yl yr} {xL xR yL yR} {i} : (mk xl xr xL xR + mk yl yr yL yR).move_right (sum.inl i) = (mk xl xr xL xR).move_right i + (mk yl yr yL yR) := rfl @[simp] lemma add_move_right_inl {x y : pgame} {i} : (x + y).move_right ((@right_moves_add x y).symm (sum.inl i)) = x.move_right i + y := by { cases x, cases y, refl, } @[simp] lemma mk_add_move_left_inr {xl xr yl yr} {xL xR yL yR} {i} : (mk xl xr xL xR + mk yl yr yL yR).move_left (sum.inr i) = (mk xl xr xL xR) + (mk yl yr yL yR).move_left i := rfl @[simp] lemma add_move_left_inr {x y : pgame} {i : y.left_moves} : (x + y).move_left ((@left_moves_add x y).symm (sum.inr i)) = x + y.move_left i := by { cases x, cases y, refl, } @[simp] lemma mk_add_move_right_inr {xl xr yl yr} {xL xR yL yR} {i} : (mk xl xr xL xR + mk yl yr yL yR).move_right (sum.inr i) = (mk xl xr xL xR) + (mk yl yr yL yR).move_right i := rfl @[simp] lemma add_move_right_inr {x y : pgame} {i} : (x + y).move_right ((@right_moves_add x y).symm (sum.inr i)) = x + y.move_right i := by { cases x, cases y, refl, } /-- If `w` has the same moves as `x` and `y` has the same moves as `z`, then `w + y` has the same moves as `x + z`. -/ def relabelling.add_congr : ∀ {w x y z : pgame.{u}}, w.relabelling x → y.relabelling z → (w + y).relabelling (x + z) | (mk wl wr wL wR) (mk xl xr xL xR) (mk yl yr yL yR) (mk zl zr zL zR) ⟨L_equiv₁, R_equiv₁, L_relabelling₁, R_relabelling₁⟩ ⟨L_equiv₂, R_equiv₂, L_relabelling₂, R_relabelling₂⟩ := begin refine ⟨equiv.sum_congr L_equiv₁ L_equiv₂, equiv.sum_congr R_equiv₁ R_equiv₂, _, _⟩, { rintro (i|j), { exact relabelling.add_congr (L_relabelling₁ i) (⟨L_equiv₂, R_equiv₂, L_relabelling₂, R_relabelling₂⟩) }, { exact relabelling.add_congr (⟨L_equiv₁, R_equiv₁, L_relabelling₁, R_relabelling₁⟩) (L_relabelling₂ j) }}, { rintro (i|j), { exact relabelling.add_congr (R_relabelling₁ i) (⟨L_equiv₂, R_equiv₂, L_relabelling₂, R_relabelling₂⟩) }, { exact relabelling.add_congr (⟨L_equiv₁, R_equiv₁, L_relabelling₁, R_relabelling₁⟩) (R_relabelling₂ j) }} end using_well_founded { dec_tac := pgame_wf_tac } instance : has_sub pgame := ⟨λ x y, x + -y⟩ /-- If `w` has the same moves as `x` and `y` has the same moves as `z`, then `w - y` has the same moves as `x - z`. -/ def relabelling.sub_congr {w x y z : pgame} (h₁ : w.relabelling x) (h₂ : y.relabelling z) : (w - y).relabelling (x - z) := h₁.add_congr h₂.neg_congr /-- `-(x+y)` has exactly the same moves as `-x + -y`. -/ def neg_add_relabelling : Π (x y : pgame), relabelling (-(x + y)) (-x + -y) | (mk xl xr xL xR) (mk yl yr yL yR) := ⟨equiv.refl _, equiv.refl _, λ j, sum.cases_on j (λ j, neg_add_relabelling (xR j) (mk yl yr yL yR)) (λ j, neg_add_relabelling (mk xl xr xL xR) (yR j)), λ i, sum.cases_on i (λ i, neg_add_relabelling (xL i) (mk yl yr yL yR)) (λ i, neg_add_relabelling (mk xl xr xL xR) (yL i))⟩ using_well_founded { dec_tac := pgame_wf_tac } theorem neg_add_le {x y : pgame} : -(x + y) ≤ -x + -y := (neg_add_relabelling x y).le /-- `x+y` has exactly the same moves as `y+x`. -/ def add_comm_relabelling : Π (x y : pgame.{u}), relabelling (x + y) (y + x) | (mk xl xr xL xR) (mk yl yr yL yR) := begin refine ⟨equiv.sum_comm _ _, equiv.sum_comm _ _, _, _⟩; rintros (_|_); { simp [left_moves_add, right_moves_add], apply add_comm_relabelling } end using_well_founded { dec_tac := pgame_wf_tac } theorem add_comm_le {x y : pgame} : x + y ≤ y + x := (add_comm_relabelling x y).le theorem add_comm_equiv {x y : pgame} : x + y ≈ y + x := (add_comm_relabelling x y).equiv /-- `(x + y) + z` has exactly the same moves as `x + (y + z)`. -/ def add_assoc_relabelling : Π (x y z : pgame.{u}), relabelling ((x + y) + z) (x + (y + z)) | (mk xl xr xL xR) (mk yl yr yL yR) (mk zl zr zL zR) := begin refine ⟨equiv.sum_assoc _ _ _, equiv.sum_assoc _ _ _, _, _⟩, { rintro (⟨i|i⟩|i), { apply add_assoc_relabelling, }, { change relabelling (mk xl xr xL xR + yL i + mk zl zr zL zR) (mk xl xr xL xR + (yL i + mk zl zr zL zR)), apply add_assoc_relabelling, }, { change relabelling (mk xl xr xL xR + mk yl yr yL yR + zL i) (mk xl xr xL xR + (mk yl yr yL yR + zL i)), apply add_assoc_relabelling, } }, { rintro (j|⟨j|j⟩), { apply add_assoc_relabelling, }, { change relabelling (mk xl xr xL xR + yR j + mk zl zr zL zR) (mk xl xr xL xR + (yR j + mk zl zr zL zR)), apply add_assoc_relabelling, }, { change relabelling (mk xl xr xL xR + mk yl yr yL yR + zR j) (mk xl xr xL xR + (mk yl yr yL yR + zR j)), apply add_assoc_relabelling, } }, end using_well_founded { dec_tac := pgame_wf_tac } theorem add_assoc_equiv {x y z : pgame} : (x + y) + z ≈ x + (y + z) := (add_assoc_relabelling x y z).equiv theorem add_le_add_right : Π {x y z : pgame} (h : x ≤ y), x + z ≤ y + z | (mk xl xr xL xR) (mk yl yr yL yR) (mk zl zr zL zR) := begin intros h, rw le_def, split, { -- if Left plays first intros i, change xl ⊕ zl at i, cases i, { -- either they play in x rw le_def at h, cases h, have t := h_left i, rcases t with ⟨i', ih⟩ | ⟨j, jh⟩, { left, refine ⟨(left_moves_add _ _).inv_fun (sum.inl i'), _⟩, exact add_le_add_right ih, }, { right, refine ⟨(right_moves_add _ _).inv_fun (sum.inl j), _⟩, convert add_le_add_right jh, apply add_move_right_inl } }, { -- or play in z left, refine ⟨(left_moves_add _ _).inv_fun (sum.inr i), _⟩, exact add_le_add_right h, }, }, { -- if Right plays first intros j, change yr ⊕ zr at j, cases j, { -- either they play in y rw le_def at h, cases h, have t := h_right j, rcases t with ⟨i, ih⟩ | ⟨j', jh⟩, { left, refine ⟨(left_moves_add _ _).inv_fun (sum.inl i), _⟩, convert add_le_add_right ih, apply add_move_left_inl }, { right, refine ⟨(right_moves_add _ _).inv_fun (sum.inl j'), _⟩, exact add_le_add_right jh } }, { -- or play in z right, refine ⟨(right_moves_add _ _).inv_fun (sum.inr j), _⟩, exact add_le_add_right h } } end using_well_founded { dec_tac := pgame_wf_tac } theorem add_le_add_left {x y z : pgame} (h : y ≤ z) : x + y ≤ x + z := calc x + y ≤ y + x : add_comm_le ... ≤ z + x : add_le_add_right h ... ≤ x + z : add_comm_le theorem add_congr {w x y z : pgame} (h₁ : w ≈ x) (h₂ : y ≈ z) : w + y ≈ x + z := ⟨calc w + y ≤ w + z : add_le_add_left h₂.1 ... ≤ x + z : add_le_add_right h₁.1, calc x + z ≤ x + y : add_le_add_left h₂.2 ... ≤ w + y : add_le_add_right h₁.2⟩ theorem sub_congr {w x y z : pgame} (h₁ : w ≈ x) (h₂ : y ≈ z) : w - y ≈ x - z := add_congr h₁ (neg_congr h₂) theorem add_left_neg_le_zero : Π {x : pgame}, (-x) + x ≤ 0 | ⟨xl, xr, xL, xR⟩ := begin rw [le_def], split, { intro i, change xr ⊕ xl at i, cases i, { -- If Left played in -x, Right responds with the same move in x. right, refine ⟨(right_moves_add _ _).inv_fun (sum.inr i), _⟩, convert @add_left_neg_le_zero (xR i), exact add_move_right_inr }, { -- If Left in x, Right responds with the same move in -x. right, dsimp, refine ⟨(right_moves_add _ _).inv_fun (sum.inl i), _⟩, convert @add_left_neg_le_zero (xL i), exact add_move_right_inl }, }, { rintro ⟨⟩, } end using_well_founded { dec_tac := pgame_wf_tac } theorem zero_le_add_left_neg : Π {x : pgame}, 0 ≤ (-x) + x := begin intro x, rw [le_iff_neg_ge, neg_zero], exact le_trans neg_add_le add_left_neg_le_zero end theorem add_left_neg_equiv {x : pgame} : (-x) + x ≈ 0 := ⟨add_left_neg_le_zero, zero_le_add_left_neg⟩ theorem add_right_neg_le_zero {x : pgame} : x + (-x) ≤ 0 := calc x + (-x) ≤ (-x) + x : add_comm_le ... ≤ 0 : add_left_neg_le_zero theorem zero_le_add_right_neg {x : pgame} : 0 ≤ x + (-x) := calc 0 ≤ (-x) + x : zero_le_add_left_neg ... ≤ x + (-x) : add_comm_le theorem add_right_neg_equiv {x : pgame} : x + (-x) ≈ 0 := ⟨add_right_neg_le_zero, zero_le_add_right_neg⟩ theorem add_lt_add_right {x y z : pgame} (h : x < y) : x + z < y + z := suffices y + z ≤ x + z → y ≤ x, by { rw ←not_le at ⊢ h, exact mt this h }, assume w, calc y ≤ y + 0 : (add_zero_relabelling _).symm.le ... ≤ y + (z + -z) : add_le_add_left zero_le_add_right_neg ... ≤ (y + z) + (-z) : (add_assoc_relabelling _ _ _).symm.le ... ≤ (x + z) + (-z) : add_le_add_right w ... ≤ x + (z + -z) : (add_assoc_relabelling _ _ _).le ... ≤ x + 0 : add_le_add_left add_right_neg_le_zero ... ≤ x : (add_zero_relabelling _).le theorem add_lt_add_left {x y z : pgame} (h : y < z) : x + y < x + z := calc x + y ≤ y + x : add_comm_le ... < z + x : add_lt_add_right h ... ≤ x + z : add_comm_le theorem le_iff_sub_nonneg {x y : pgame} : x ≤ y ↔ 0 ≤ y - x := ⟨λ h, le_trans zero_le_add_right_neg (add_le_add_right h), λ h, calc x ≤ 0 + x : (zero_add_relabelling x).symm.le ... ≤ (y - x) + x : add_le_add_right h ... ≤ y + (-x + x) : (add_assoc_relabelling _ _ _).le ... ≤ y + 0 : add_le_add_left (add_left_neg_le_zero) ... ≤ y : (add_zero_relabelling y).le⟩ theorem lt_iff_sub_pos {x y : pgame} : x < y ↔ 0 < y - x := ⟨λ h, lt_of_le_of_lt zero_le_add_right_neg (add_lt_add_right h), λ h, calc x ≤ 0 + x : (zero_add_relabelling x).symm.le ... < (y - x) + x : add_lt_add_right h ... ≤ y + (-x + x) : (add_assoc_relabelling _ _ _).le ... ≤ y + 0 : add_le_add_left (add_left_neg_le_zero) ... ≤ y : (add_zero_relabelling y).le⟩ /-- The pre-game `star`, which is fuzzy/confused with zero. -/ def star : pgame := pgame.of_lists [0] [0] theorem star_lt_zero : star < 0 := by rw lt_def; exact or.inr ⟨⟨0, zero_lt_one⟩, (by split; rintros ⟨⟩)⟩ theorem zero_lt_star : 0 < star := by rw lt_def; exact or.inl ⟨⟨0, zero_lt_one⟩, (by split; rintros ⟨⟩)⟩ /-- The pre-game `ω`. (In fact all ordinals have game and surreal representatives.) -/ def omega : pgame := ⟨ulift ℕ, pempty, λ n, ↑n.1, pempty.elim⟩ end pgame
39a82809f5619762b440697723c101ffbf0fae99
4727251e0cd73359b15b664c3170e5d754078599
/archive/arithcc.lean
9de0770bbd8f2c3c7806ae82c9aaec09e3c2703a
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
12,217
lean
/- Copyright (c) 2020 Xi Wang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Xi Wang -/ import order.basic import tactic.basic /-! # A compiler for arithmetic expressions A formalization of the correctness of a compiler from arithmetic expressions to machine language described by McCarthy and Painter, which is considered the first proof of compiler correctness. ## Main definitions * `expr` : the syntax of the source language. * `value` : the semantics of the source language. * `instruction`: the syntax of the target language. * `step` : the semantics of the target language. * `compile` : the compiler. ## Main results * `compiler_correctness`: the compiler correctness theorem. ## Notation * `≃[t]/ac`: partial equality of two machine states excluding registers x ≥ t and the accumulator. * `≃[t]` : partial equality of two machine states excluding registers x ≥ t. ## References * John McCarthy and James Painter. Correctness of a compiler for arithmetic expressions. In Mathematical Aspects of Computer Science, volume 19 of Proceedings of Symposia in Applied Mathematics. American Mathematical Society, 1967. <http://jmc.stanford.edu/articles/mcpain/mcpain.pdf> ## Tags compiler -/ namespace arithcc section types /-! ### Types -/ /-- Value type shared by both source and target languages. -/ @[reducible] def word := ℕ /-- Variable identifier type in the source language. -/ @[reducible] def identifier := string /-- Register name type in the target language. -/ @[reducible] def register := ℕ lemma register.lt_succ_self : ∀ (r : register), r < r + 1 := nat.lt_succ_self lemma register.le_of_lt_succ {r₁ r₂ : register} : r₁ < r₂ + 1 → r₁ ≤ r₂ := nat.le_of_succ_le_succ end types section source /-! ### Source language -/ /-- An expression in the source language is formed by constants, variables, and sums. -/ @[derive inhabited] inductive expr | const (v : word) : expr | var (x : identifier) : expr | sum (s₁ s₂ : expr) : expr /-- The semantics of the source language (2.1). -/ @[simp] def value : expr → (identifier → word) → word | (expr.const v) _ := v | (expr.var x) ξ := ξ x | (expr.sum s₁ s₂) ξ := (value s₁ ξ) + (value s₂ ξ) end source section target /-! ### Target language -/ /-- Instructions of the target machine language (3.1--3.7). -/ @[derive inhabited] inductive instruction | li : word → instruction | load : register → instruction | sto : register → instruction | add : register → instruction /-- Machine state consists of the accumulator and a vector of registers. The paper uses two functions `c` and `a` for accessing both the accumulator and registers. For clarity, we make accessing the accumulator explicit and use `read`/`write` for registers. -/ structure state := mk :: (ac : word) (rs : register → word) instance : inhabited state := ⟨{ac := 0, rs := λ x, 0}⟩ /-- This is similar to the `c` function (3.8), but for registers only. -/ @[simp] def read (r : register) (η : state) : word := η.rs r /-- This is similar to the `a` function (3.9), but for registers only. -/ @[simp] def write (r : register) (v : word) (η : state) : state := {rs := λ x, if x = r then v else η.rs x, ..η} /-- The semantics of the target language (3.11). -/ def step : instruction → state → state | (instruction.li v) η := {ac := v, ..η} | (instruction.load r) η := {ac := read r η, ..η} | (instruction.sto r) η := write r η.ac η | (instruction.add r) η := {ac := read r η + η.ac, ..η} /-- The resulting machine state of running a target program from a given machine state (3.12). -/ @[simp] def outcome : list instruction → state → state | [] η := η | (i :: is) η := outcome is (step i η) /-- A lemma on the concatenation of two programs (3.13). -/ @[simp] lemma outcome_append (p₁ p₂ : list instruction) (η : state) : outcome (p₁ ++ p₂) η = outcome p₂ (outcome p₁ η) := begin revert η, induction p₁; intros; simp, apply p₁_ih end end target section compiler open instruction /-! ### Compiler -/ /-- Map a variable in the source expression to a machine register. -/ @[simp] def loc (ν : identifier) (map : identifier → register) : register := map ν /-- The implementation of the compiler (4.2). This definition explicitly takes a map from variables to registers. -/ @[simp] def compile (map : identifier → register) : expr → register → (list instruction) | (expr.const v) _ := [li v] | (expr.var x) _ := [load (loc x map)] | (expr.sum s₁ s₂) t := compile s₁ t ++ [sto t] ++ compile s₂ (t + 1) ++ [add t] end compiler section correctness /-! ### Correctness -/ /-- Machine states ζ₁ and ζ₂ are equal except for the accumulator and registers {x | x ≥ t}. -/ def state_eq_rs (t : register) (ζ₁ ζ₂ : state) : Prop := ∀ (r : register), r < t → ζ₁.rs r = ζ₂.rs r notation ζ₁ ` ≃[`:50 t `]/ac ` ζ₂:50 := state_eq_rs t ζ₁ ζ₂ @[refl] protected lemma state_eq_rs.refl (t : register) (ζ : state) : ζ ≃[t]/ac ζ := by simp [state_eq_rs] @[symm] protected lemma state_eq_rs.symm {t : register} (ζ₁ ζ₂ : state) : ζ₁ ≃[t]/ac ζ₂ → ζ₂ ≃[t]/ac ζ₁ := by finish [state_eq_rs] @[trans] protected lemma state_eq_rs.trans {t : register} (ζ₁ ζ₂ ζ₃ : state) : ζ₁ ≃[t]/ac ζ₂ → ζ₂ ≃[t]/ac ζ₃ → ζ₁ ≃[t]/ac ζ₃ := by finish [state_eq_rs] /-- Machine states ζ₁ and ζ₂ are equal except for registers {x | x ≥ t}. -/ def state_eq (t : register) (ζ₁ ζ₂ : state) : Prop := ζ₁.ac = ζ₂.ac ∧ state_eq_rs t ζ₁ ζ₂ notation ζ₁ ` ≃[`:50 t `] ` ζ₂:50 := state_eq t ζ₁ ζ₂ @[refl] protected lemma state_eq.refl (t : register) (ζ : state) : ζ ≃[t] ζ := by simp [state_eq] @[symm] protected lemma state_eq.symm {t : register} (ζ₁ ζ₂ : state) : ζ₁ ≃[t] ζ₂ → ζ₂ ≃[t] ζ₁ := begin simp [state_eq], intros, split; try { cc }, symmetry, assumption end @[trans] protected lemma state_eq.trans {t : register} (ζ₁ ζ₂ ζ₃ : state) : ζ₁ ≃[t] ζ₂ → ζ₂ ≃[t] ζ₃ → ζ₁ ≃[t] ζ₃ := begin simp [state_eq], intros, split; try { cc }, transitivity ζ₂; assumption end /-- Transitivity of chaining `≃[t]` and `≃[t]/ac`. -/ @[trans] protected theorem state_eq_state_eq_rs.trans (t : register) (ζ₁ ζ₂ ζ₃ : state) : ζ₁ ≃[t] ζ₂ → ζ₂ ≃[t]/ac ζ₃ → ζ₁ ≃[t]/ac ζ₃ := begin simp [state_eq], intros, transitivity ζ₂; assumption end /-- Writing the same value to register `t` gives `≃[t + 1]` from `≃[t]`. -/ lemma state_eq_implies_write_eq {t : register} {ζ₁ ζ₂ : state} (h : ζ₁ ≃[t] ζ₂) (v : word) : write t v ζ₁ ≃[t + 1] write t v ζ₂ := begin simp [state_eq, state_eq_rs] at *, split ; try { cc }, intros _ hr, have hr : r ≤ t := register.le_of_lt_succ hr, cases lt_or_eq_of_le hr with hr hr, { cases h with _ h, specialize h r hr, cc }, { cc } end /-- Writing the same value to any register preserves `≃[t]/ac`. -/ lemma state_eq_rs_implies_write_eq_rs {t : register} {ζ₁ ζ₂ : state} (h : ζ₁ ≃[t]/ac ζ₂) (r : register) (v : word) : write r v ζ₁ ≃[t]/ac write r v ζ₂ := begin simp [state_eq_rs] at *, intros r' hr', specialize h r' hr', cc end /-- `≃[t + 1]` with writing to register `t` implies `≃[t]`. -/ lemma write_eq_implies_state_eq {t : register} {v : word} {ζ₁ ζ₂ : state} (h : ζ₁ ≃[t + 1] write t v ζ₂) : ζ₁ ≃[t] ζ₂ := begin simp [state_eq, state_eq_rs] at *, split; try { cc }, intros r hr, cases h with _ h, specialize h r (lt_trans hr (register.lt_succ_self _)), rwa if_neg (ne_of_lt hr) at h end /-- The main **compiler correctness theorem**. Unlike Theorem 1 in the paper, both `map` and the assumption on `t` are explicit. -/ theorem compiler_correctness : ∀ (map : identifier → register) (e : expr) (ξ : identifier → word) (η : state) (t : register), (∀ x, read (loc x map) η = ξ x) → (∀ x, loc x map < t) → outcome (compile map e t) η ≃[t] {ac := value e ξ, ..η} := begin intros _ _ _ _ _ hmap ht, revert η t, induction e; intros, -- 5.I case expr.const { simp [state_eq, step] }, -- 5.II case expr.var { finish [hmap, state_eq, step] }, -- 5.III case expr.sum { simp, generalize_hyp dν₁ : value e_s₁ ξ = ν₁ at e_ih_s₁ ⊢, generalize_hyp dν₂ : value e_s₂ ξ = ν₂ at e_ih_s₂ ⊢, generalize dν : ν₁ + ν₂ = ν, generalize dζ₁ : outcome (compile _ e_s₁ t) η = ζ₁, generalize dζ₂ : step (instruction.sto t) ζ₁ = ζ₂, generalize dζ₃ : outcome (compile _ e_s₂ (t + 1)) ζ₂ = ζ₃, generalize dζ₄ : step (instruction.add t) ζ₃ = ζ₄, have hζ₁ : ζ₁ ≃[t] {ac := ν₁, ..η}, calc ζ₁ = outcome (compile map e_s₁ t) η : by cc ... ≃[t] {ac := ν₁, ..η} : by apply e_ih_s₁; assumption, have hζ₁_ν₁ : ζ₁.ac = ν₁, { finish [state_eq] }, have hζ₂ : ζ₂ ≃[t + 1]/ac write t ν₁ η, calc ζ₂ = step (instruction.sto t) ζ₁ : by cc ... = write t ζ₁.ac ζ₁ : by simp [step] ... = write t ν₁ ζ₁ : by cc ... ≃[t + 1] write t ν₁ {ac := ν₁, ..η} : by apply state_eq_implies_write_eq hζ₁ ... ≃[t + 1]/ac write t ν₁ η : by { apply state_eq_rs_implies_write_eq_rs, simp [state_eq_rs] }, have hζ₂_ν₂ : read t ζ₂ = ν₁, { simp [state_eq_rs] at hζ₂ ⊢, specialize hζ₂ t (register.lt_succ_self _), cc }, have ht' : ∀ x, loc x map < t + 1, { intros, apply lt_trans (ht _) (register.lt_succ_self _) }, have hmap' : ∀ x, read (loc x map) ζ₂ = ξ x, { intros, calc read (loc x map) ζ₂ = read (loc x map) (write t ν₁ η) : hζ₂ _ (ht' _) ... = read (loc x map) η : by { simp only [loc] at ht, simp [(ht _).ne] } ... = ξ x : hmap x }, have hζ₃ : ζ₃ ≃[t + 1] {ac := ν₂, ..(write t ν₁ η)}, calc ζ₃ = outcome (compile map e_s₂ (t + 1)) ζ₂ : by cc ... ≃[t + 1] {ac := ν₂, ..ζ₂} : by apply e_ih_s₂; assumption ... ≃[t + 1] {ac := ν₂, ..(write t ν₁ η)} : by { simp [state_eq], apply hζ₂ }, have hζ₃_ν₂ : ζ₃.ac = ν₂, { finish [state_eq] }, have hζ₃_ν₁ : read t ζ₃ = ν₁, { simp [state_eq, state_eq_rs] at hζ₃ ⊢, cases hζ₃ with _ hζ₃, specialize hζ₃ t (register.lt_succ_self _), cc }, have hζ₄ : ζ₄ ≃[t + 1] {ac := ν, ..write t ν₁ η}, calc ζ₄ = step (instruction.add t) ζ₃ : by cc ... = {ac := read t ζ₃ + ζ₃.ac, ..ζ₃} : by simp [step] ... = {ac := ν, ..ζ₃} : by cc ... ≃[t + 1] {ac := ν, ..{ac := ν₂, ..write t ν₁ η}} : by { simp [state_eq] at hζ₃ ⊢, cases hζ₃, assumption } ... ≃[t + 1] {ac := ν, ..write t ν₁ η} : by simp, apply write_eq_implies_state_eq; assumption } end end correctness section test open instruction /-- The example in the paper for compiling (x + 3) + (x + (y + 2)). -/ example (x y t : register) : let map := λ v, if v = "x" then x else if v = "y" then y else 0, p := expr.sum (expr.sum (expr.var "x") (expr.const 3)) (expr.sum (expr.var "x") (expr.sum (expr.var "y") (expr.const 2))) in compile map p t = [ load x, sto t, li 3, add t, sto t, load x, sto (t + 1), load y, sto (t + 2), li 2, add (t + 2), add (t + 1), add t ] := rfl end test end arithcc
a3ae1ff23b9485afb8396082611518083b6f2fb9
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/07_Induction_and_Recursion.org.12.lean
dad71f4e6fac3dff33a48bdc68184507fa51e9f6
[]
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
714
lean
/- page 104 -/ import standard import data.examples.vector open nat vector prod -- BEGIN definition head {A : Type} : Π {n}, vector A (succ n) → A | head (h :: t) := h definition tail {A : Type} : Π {n}, vector A (succ n) → vector A n | tail (h :: t) := t theorem eta {A : Type} : ∀ {n} (v : vector A (succ n)), head v :: tail v = v | eta (h::t) := rfl definition map {A B C : Type} (f : A → B → C) : Π {n : nat}, vector A n → vector B n → vector C n | map nil nil := nil | map (a::va) (b::vb) := f a b :: map va vb definition zip {A B : Type} : Π {n}, vector A n → vector B n → vector (A × B) n | zip nil nil := nil | zip (a::va) (b::vb) := (a, b) :: zip va vb -- END
98bbeb844ed7ddfae15e4496ad8a3daf1ee0e446
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/number_theory/sum_four_squares.lean
21856c92e431620b8af5d951a0700c55993e1f4b
[ "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
11,816
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import algebra.group_power.identities import data.zmod.basic import field_theory.finite.basic import data.int.parity import data.fintype.card /-! # Lagrange's four square theorem The main result in this file is `sum_four_squares`, a proof that every natural number is the sum of four square numbers. ## Implementation Notes The proof used is close to Lagrange's original proof. -/ open finset polynomial finite_field equiv open_locale big_operators namespace int lemma sq_add_sq_of_two_mul_sq_add_sq {m x y : ℤ} (h : 2 * m = x^2 + y^2) : m = ((x - y) / 2) ^ 2 + ((x + y) / 2) ^ 2 := have even (x^2 + y^2), by simp [h.symm, even_mul], have hxaddy : even (x + y), by simpa [sq] with parity_simps, have hxsuby : even (x - y), by simpa [sq] with parity_simps, (mul_right_inj' (show (2*2 : ℤ) ≠ 0, from dec_trivial)).1 $ calc 2 * 2 * m = (x - y)^2 + (x + y)^2 : by rw [mul_assoc, h]; ring ... = (2 * ((x - y) / 2))^2 + (2 * ((x + y) / 2))^2 : by rw [int.mul_div_cancel' hxsuby, int.mul_div_cancel' hxaddy] ... = 2 * 2 * (((x - y) / 2) ^ 2 + ((x + y) / 2) ^ 2) : by simp [mul_add, pow_succ, mul_comm, mul_assoc, mul_left_comm] lemma exists_sq_add_sq_add_one_eq_k (p : ℕ) [hp : fact p.prime] : ∃ (a b : ℤ) (k : ℕ), a^2 + b^2 + 1 = k * p ∧ k < p := hp.1.eq_two_or_odd.elim (λ hp2, hp2.symm ▸ ⟨1, 0, 1, rfl, dec_trivial⟩) $ λ hp1, let ⟨a, b, hab⟩ := zmod.sq_add_sq p (-1) in have hab' : (p : ℤ) ∣ a.val_min_abs ^ 2 + b.val_min_abs ^ 2 + 1, from (char_p.int_cast_eq_zero_iff (zmod p) p _).1 $ by simpa [eq_neg_iff_add_eq_zero] using hab, let ⟨k, hk⟩ := hab' in have hk0 : 0 ≤ k, from nonneg_of_mul_nonneg_left (by rw ← hk; exact (add_nonneg (add_nonneg (sq_nonneg _) (sq_nonneg _)) zero_le_one)) (int.coe_nat_pos.2 hp.1.pos), ⟨a.val_min_abs, b.val_min_abs, k.nat_abs, by rw [hk, int.nat_abs_of_nonneg hk0, mul_comm], lt_of_mul_lt_mul_left (calc p * k.nat_abs = a.val_min_abs.nat_abs ^ 2 + b.val_min_abs.nat_abs ^ 2 + 1 : by rw [← int.coe_nat_inj', int.coe_nat_add, int.coe_nat_add, int.coe_nat_pow, int.coe_nat_pow, int.nat_abs_sq, int.nat_abs_sq, int.coe_nat_one, hk, int.coe_nat_mul, int.nat_abs_of_nonneg hk0] ... ≤ (p / 2) ^ 2 + (p / 2)^2 + 1 : add_le_add (add_le_add (nat.pow_le_pow_of_le_left (zmod.nat_abs_val_min_abs_le _) _) (nat.pow_le_pow_of_le_left (zmod.nat_abs_val_min_abs_le _) _)) le_rfl ... < (p / 2) ^ 2 + (p / 2)^ 2 + (p % 2)^2 + ((2 * (p / 2)^2 + (4 * (p / 2) * (p % 2)))) : by rw [hp1, one_pow, mul_one]; exact (lt_add_iff_pos_right _).2 (add_pos_of_nonneg_of_pos (nat.zero_le _) (mul_pos dec_trivial (nat.div_pos hp.1.two_le dec_trivial))) ... = p * p : by { conv_rhs { rw [← nat.mod_add_div p 2] }, ring }) (show 0 ≤ p, from nat.zero_le _)⟩ end int namespace nat open int open_locale classical private lemma sum_four_squares_of_two_mul_sum_four_squares {m a b c d : ℤ} (h : a^2 + b^2 + c^2 + d^2 = 2 * m) : ∃ w x y z : ℤ, w^2 + x^2 + y^2 + z^2 = m := have ∀ f : fin 4 → zmod 2, (f 0)^2 + (f 1)^2 + (f 2)^2 + (f 3)^2 = 0 → ∃ i : (fin 4), (f i)^2 + f (swap i 0 1)^2 = 0 ∧ f (swap i 0 2)^2 + f (swap i 0 3)^2 = 0, from dec_trivial, let f : fin 4 → ℤ := vector.nth (a ::ᵥ b ::ᵥ c ::ᵥ d ::ᵥ vector.nil) in let ⟨i, hσ⟩ := this (coe ∘ f) (by rw [← @zero_mul (zmod 2) _ m, ← show ((2 : ℤ) : zmod 2) = 0, from rfl, ← int.cast_mul, ← h]; simp only [int.cast_add, int.cast_pow]; refl) in let σ := swap i 0 in have h01 : 2 ∣ f (σ 0) ^ 2 + f (σ 1) ^ 2, from (char_p.int_cast_eq_zero_iff (zmod 2) 2 _).1 $ by simpa [σ] using hσ.1, have h23 : 2 ∣ f (σ 2) ^ 2 + f (σ 3) ^ 2, from (char_p.int_cast_eq_zero_iff (zmod 2) 2 _).1 $ by simpa using hσ.2, let ⟨x, hx⟩ := h01 in let ⟨y, hy⟩ := h23 in ⟨(f (σ 0) - f (σ 1)) / 2, (f (σ 0) + f (σ 1)) / 2, (f (σ 2) - f (σ 3)) / 2, (f (σ 2) + f (σ 3)) / 2, begin rw [← int.sq_add_sq_of_two_mul_sq_add_sq hx.symm, add_assoc, ← int.sq_add_sq_of_two_mul_sq_add_sq hy.symm, ← mul_right_inj' (show (2 : ℤ) ≠ 0, from dec_trivial), ← h, mul_add, ← hx, ← hy], have : ∑ x, f (σ x)^2 = ∑ x, f x^2, { conv_rhs { rw ←equiv.sum_comp σ } }, have fin4univ : (univ : finset (fin 4)).1 = 0 ::ₘ 1 ::ₘ 2 ::ₘ 3 ::ₘ 0, from dec_trivial, simpa [finset.sum_eq_multiset_sum, fin4univ, multiset.sum_cons, f, add_assoc] end⟩ private lemma prime_sum_four_squares (p : ℕ) [hp : _root_.fact p.prime] : ∃ a b c d : ℤ, a^2 + b^2 + c^2 + d^2 = p := have hm : ∃ m < p, 0 < m ∧ ∃ a b c d : ℤ, a^2 + b^2 + c^2 + d^2 = m * p, from let ⟨a, b, k, hk⟩ := exists_sq_add_sq_add_one_eq_k p in ⟨k, hk.2, nat.pos_of_ne_zero $ (λ hk0, by { rw [hk0, int.coe_nat_zero, zero_mul] at hk, exact ne_of_gt (show a^2 + b^2 + 1 > 0, from add_pos_of_nonneg_of_pos (add_nonneg (sq_nonneg _) (sq_nonneg _)) zero_lt_one) hk.1 }), a, b, 1, 0, by simpa [sq] using hk.1⟩, let m := nat.find hm in let ⟨a, b, c, d, (habcd : a^2 + b^2 + c^2 + d^2 = m * p)⟩ := (nat.find_spec hm).snd.2 in by haveI hm0 : _root_.fact (0 < m) := ⟨(nat.find_spec hm).snd.1⟩; exact have hmp : m < p, from (nat.find_spec hm).fst, m.mod_two_eq_zero_or_one.elim (λ hm2 : m % 2 = 0, let ⟨k, hk⟩ := (nat.dvd_iff_mod_eq_zero _ _).2 hm2 in have hk0 : 0 < k, from nat.pos_of_ne_zero $ λ _, by { simp [*, lt_irrefl] at * }, have hkm : k < m, { rw [hk, two_mul], exact (lt_add_iff_pos_left _).2 hk0 }, false.elim $ nat.find_min hm hkm ⟨lt_trans hkm hmp, hk0, sum_four_squares_of_two_mul_sum_four_squares (show a^2 + b^2 + c^2 + d^2 = 2 * (k * p), by { rw [habcd, hk, int.coe_nat_mul, mul_assoc], simp })⟩) (λ hm2 : m % 2 = 1, if hm1 : m = 1 then ⟨a, b, c, d, by simp only [hm1, habcd, int.coe_nat_one, one_mul]⟩ else let w := (a : zmod m).val_min_abs, x := (b : zmod m).val_min_abs, y := (c : zmod m).val_min_abs, z := (d : zmod m).val_min_abs in have hnat_abs : w^2 + x^2 + y^2 + z^2 = (w.nat_abs^2 + x.nat_abs^2 + y.nat_abs ^2 + z.nat_abs ^ 2 : ℕ), by simp [sq], have hwxyzlt : w^2 + x^2 + y^2 + z^2 < m^2, from calc w^2 + x^2 + y^2 + z^2 = (w.nat_abs^2 + x.nat_abs^2 + y.nat_abs ^2 + z.nat_abs ^ 2 : ℕ) : hnat_abs ... ≤ ((m / 2) ^ 2 + (m / 2) ^ 2 + (m / 2) ^ 2 + (m / 2) ^ 2 : ℕ) : int.coe_nat_le.2 $ add_le_add (add_le_add (add_le_add (nat.pow_le_pow_of_le_left (zmod.nat_abs_val_min_abs_le _) _) (nat.pow_le_pow_of_le_left (zmod.nat_abs_val_min_abs_le _) _)) (nat.pow_le_pow_of_le_left (zmod.nat_abs_val_min_abs_le _) _)) (nat.pow_le_pow_of_le_left (zmod.nat_abs_val_min_abs_le _) _) ... = 4 * (m / 2 : ℕ) ^ 2 : by simp [sq, bit0, bit1, mul_add, add_mul, add_assoc] ... < 4 * (m / 2 : ℕ) ^ 2 + ((4 * (m / 2) : ℕ) * (m % 2 : ℕ) + (m % 2 : ℕ)^2) : (lt_add_iff_pos_right _).2 (by { rw [hm2, int.coe_nat_one, one_pow, mul_one], exact add_pos_of_nonneg_of_pos (int.coe_nat_nonneg _) zero_lt_one }) ... = m ^ 2 : by { conv_rhs {rw [← nat.mod_add_div m 2]}, simp [-nat.mod_add_div, mul_add, add_mul, bit0, bit1, mul_comm, mul_assoc, mul_left_comm, pow_add, add_comm, add_left_comm] }, have hwxyzabcd : ((w^2 + x^2 + y^2 + z^2 : ℤ) : zmod m) = ((a^2 + b^2 + c^2 + d^2 : ℤ) : zmod m), by simp [w, x, y, z, sq], have hwxyz0 : ((w^2 + x^2 + y^2 + z^2 : ℤ) : zmod m) = 0, by rw [hwxyzabcd, habcd, int.cast_mul, cast_coe_nat, zmod.nat_cast_self, zero_mul], let ⟨n, hn⟩ := ((char_p.int_cast_eq_zero_iff _ m _).1 hwxyz0) in have hn0 : 0 < n.nat_abs, from int.nat_abs_pos_of_ne_zero (λ hn0, have hwxyz0 : (w.nat_abs^2 + x.nat_abs^2 + y.nat_abs^2 + z.nat_abs^2 : ℕ) = 0, by { rw [← int.coe_nat_eq_zero, ← hnat_abs], rwa [hn0, mul_zero] at hn }, have habcd0 : (m : ℤ) ∣ a ∧ (m : ℤ) ∣ b ∧ (m : ℤ) ∣ c ∧ (m : ℤ) ∣ d, by simpa [add_eq_zero_iff' (sq_nonneg (_ : ℤ)) (sq_nonneg _), pow_two, w, x, y, z, (char_p.int_cast_eq_zero_iff _ m _), and.assoc] using hwxyz0, let ⟨ma, hma⟩ := habcd0.1, ⟨mb, hmb⟩ := habcd0.2.1, ⟨mc, hmc⟩ := habcd0.2.2.1, ⟨md, hmd⟩ := habcd0.2.2.2 in have hmdvdp : m ∣ p, from int.coe_nat_dvd.1 ⟨ma^2 + mb^2 + mc^2 + md^2, (mul_right_inj' (show (m : ℤ) ≠ 0, from int.coe_nat_ne_zero_iff_pos.2 hm0.1)).1 $ by { rw [← habcd, hma, hmb, hmc, hmd], ring }⟩, (hp.1.eq_one_or_self_of_dvd _ hmdvdp).elim hm1 (λ hmeqp, by simpa [lt_irrefl, hmeqp] using hmp)), have hawbxcydz : ((m : ℕ) : ℤ) ∣ a * w + b * x + c * y + d * z, from (char_p.int_cast_eq_zero_iff (zmod m) m _).1 $ by { rw [← hwxyz0], simp, ring }, have haxbwczdy : ((m : ℕ) : ℤ) ∣ a * x - b * w - c * z + d * y, from (char_p.int_cast_eq_zero_iff (zmod m) m _).1 $ by { simp [sub_eq_add_neg], ring }, have haybzcwdx : ((m : ℕ) : ℤ) ∣ a * y + b * z - c * w - d * x, from (char_p.int_cast_eq_zero_iff (zmod m) m _).1 $ by { simp [sub_eq_add_neg], ring }, have hazbycxdw : ((m : ℕ) : ℤ) ∣ a * z - b * y + c * x - d * w, from (char_p.int_cast_eq_zero_iff (zmod m) m _).1 $ by { simp [sub_eq_add_neg], ring }, let ⟨s, hs⟩ := hawbxcydz, ⟨t, ht⟩ := haxbwczdy, ⟨u, hu⟩ := haybzcwdx, ⟨v, hv⟩ := hazbycxdw in have hn_nonneg : 0 ≤ n, from nonneg_of_mul_nonneg_left (by { erw [← hn], repeat {try {refine add_nonneg _ _}, try {exact sq_nonneg _}} }) (int.coe_nat_pos.2 hm0.1), have hnm : n.nat_abs < m, from int.coe_nat_lt.1 (lt_of_mul_lt_mul_left (by { rw [int.nat_abs_of_nonneg hn_nonneg, ← hn, ← sq], exact hwxyzlt }) (int.coe_nat_nonneg m)), have hstuv : s^2 + t^2 + u^2 + v^2 = n.nat_abs * p, from (mul_right_inj' (show (m^2 : ℤ) ≠ 0, from pow_ne_zero 2 (int.coe_nat_ne_zero_iff_pos.2 hm0.1))).1 $ calc (m : ℤ)^2 * (s^2 + t^2 + u^2 + v^2) = ((m : ℕ) * s)^2 + ((m : ℕ) * t)^2 + ((m : ℕ) * u)^2 + ((m : ℕ) * v)^2 : by { simp [mul_pow], ring } ... = (w^2 + x^2 + y^2 + z^2) * (a^2 + b^2 + c^2 + d^2) : by { simp only [hs.symm, ht.symm, hu.symm, hv.symm], ring } ... = _ : by { rw [hn, habcd, int.nat_abs_of_nonneg hn_nonneg], dsimp [m], ring }, false.elim $ nat.find_min hm hnm ⟨lt_trans hnm hmp, hn0, s, t, u, v, hstuv⟩) /-- **Four squares theorem** -/ lemma sum_four_squares : ∀ n : ℕ, ∃ a b c d : ℕ, a^2 + b^2 + c^2 + d^2 = n | 0 := ⟨0, 0, 0, 0, rfl⟩ | 1 := ⟨1, 0, 0, 0, rfl⟩ | n@(k+2) := have hm : _root_.fact (min_fac (k+2)).prime := ⟨min_fac_prime dec_trivial⟩, have n / min_fac n < n := factors_lemma, let ⟨a, b, c, d, h₁⟩ := show ∃ a b c d : ℤ, a^2 + b^2 + c^2 + d^2 = min_fac n, by exactI prime_sum_four_squares (min_fac (k+2)) in let ⟨w, x, y, z, h₂⟩ := sum_four_squares (n / min_fac n) in ⟨(a * w - b * x - c * y - d * z).nat_abs, (a * x + b * w + c * z - d * y).nat_abs, (a * y - b * z + c * w + d * x).nat_abs, (a * z + b * y - c * x + d * w).nat_abs, begin rw [← int.coe_nat_inj', ← nat.mul_div_cancel' (min_fac_dvd (k+2)), int.coe_nat_mul, ← h₁, ← h₂], simp [sum_four_sq_mul_sum_four_sq], end⟩ end nat
bd071f72891981f1de8ef31262692bf8e241bc56
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/run/def10.lean
48f2d926548aea118da633e6a27310c457631eb3
[ "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
693
lean
def f : Bool → Bool → Nat | true, true => 0 | _, _ => 3 example : f true true = 0 := rfl def g : Bool → Bool → Bool → Nat | true, _, true => 1 | _, false, false => 2 | a, _, b => f a b theorem ex1 : g true true true = 1 := rfl theorem ex2 : g true false true = 1 := rfl theorem ex3 : g true false false = 2 := rfl theorem ex4 : g false false false = 2 := rfl theorem ex5 : g false true true = 3 := rfl theorem f_eq (h : a = true → b = true → False) : f a b = 3 := by simp [f] split . contradiction . rfl theorem ex6 : g x y z > 0 := by simp [g] split next => decide next => decide next a b c h₁ h₂ => simp [f_eq h₁]
8016b5b672d7e328afe0cd1fc9cb2d87c94a2890
19cc34575500ee2e3d4586c15544632aa07a8e66
/src/data/polynomial/degree/basic.lean
9c7c92a7871379823dbacae6f23a9536fe4a63cd
[ "Apache-2.0" ]
permissive
LibertasSpZ/mathlib
b9fcd46625eb940611adb5e719a4b554138dade6
33f7870a49d7cc06d2f3036e22543e6ec5046e68
refs/heads/master
1,672,066,539,347
1,602,429,158,000
1,602,429,158,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
34,492
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import data.polynomial.coeff import data.nat.with_bot /-! # Theory of univariate polynomials The definitions include `degree`, `monic`, `leading_coeff` Results include - `degree_mul` : The degree of the product is the sum of degrees - `leading_coeff_add_of_degree_eq` and `leading_coeff_add_of_degree_lt` : The leading_coefficient of a sum is determined by the leading coefficients and degrees -/ noncomputable theory local attribute [instance, priority 100] classical.prop_decidable open finsupp finset open_locale big_operators namespace polynomial universes u v variables {R : Type u} {S : Type v} {a b : R} {n m : ℕ} section semiring variables [semiring R] {p q r : polynomial R} /-- `degree p` is the degree of the polynomial `p`, i.e. the largest `X`-exponent in `p`. `degree p = some n` when `p ≠ 0` and `n` is the highest power of `X` that appears in `p`, otherwise `degree 0 = ⊥`. -/ def degree (p : polynomial R) : with_bot ℕ := p.support.sup some lemma degree_lt_wf : well_founded (λp q : polynomial R, degree p < degree q) := inv_image.wf degree (with_bot.well_founded_lt nat.lt_wf) instance : has_well_founded (polynomial R) := ⟨_, degree_lt_wf⟩ /-- `nat_degree p` forces `degree p` to ℕ, by defining nat_degree 0 = 0. -/ def nat_degree (p : polynomial R) : ℕ := (degree p).get_or_else 0 /-- `leading_coeff p` gives the coefficient of the highest power of `X` in `p`-/ def leading_coeff (p : polynomial R) : R := coeff p (nat_degree p) /-- a polynomial is `monic` if its leading coefficient is 1 -/ def monic (p : polynomial R) := leading_coeff p = (1 : R) lemma monic.def : monic p ↔ leading_coeff p = 1 := iff.rfl instance monic.decidable [decidable_eq R] : decidable (monic p) := by unfold monic; apply_instance @[simp] lemma monic.leading_coeff {p : polynomial R} (hp : p.monic) : leading_coeff p = 1 := hp @[simp] lemma degree_zero : degree (0 : polynomial R) = ⊥ := rfl @[simp] lemma nat_degree_zero : nat_degree (0 : polynomial R) = 0 := rfl lemma degree_eq_bot : degree p = ⊥ ↔ p = 0 := ⟨λ h, by rw [degree, ← max_eq_sup_with_bot] at h; exact support_eq_empty.1 (max_eq_none.1 h), λ h, h.symm ▸ rfl⟩ lemma degree_eq_nat_degree (hp : p ≠ 0) : degree p = (nat_degree p : with_bot ℕ) := let ⟨n, hn⟩ := not_forall.1 (mt option.eq_none_iff_forall_not_mem.2 (mt degree_eq_bot.1 hp)) in have hn : degree p = some n := not_not.1 hn, by rw [nat_degree, hn]; refl lemma degree_eq_iff_nat_degree_eq {p : polynomial R} {n : ℕ} (hp : p ≠ 0) : p.degree = n ↔ p.nat_degree = n := by rw [degree_eq_nat_degree hp, with_bot.coe_eq_coe] lemma degree_eq_iff_nat_degree_eq_of_pos {p : polynomial R} {n : ℕ} (hn : 0 < n) : p.degree = n ↔ p.nat_degree = n := begin split, { intro H, rwa ← degree_eq_iff_nat_degree_eq, rintro rfl, rw degree_zero at H, exact option.no_confusion H }, { intro H, rwa degree_eq_iff_nat_degree_eq, rintro rfl, rw nat_degree_zero at H, rw H at hn, exact lt_irrefl _ hn } end lemma nat_degree_eq_of_degree_eq_some {p : polynomial R} {n : ℕ} (h : degree p = n) : nat_degree p = n := have hp0 : p ≠ 0, from λ hp0, by rw hp0 at h; exact option.no_confusion h, option.some_inj.1 $ show (nat_degree p : with_bot ℕ) = n, by rwa [← degree_eq_nat_degree hp0] @[simp] lemma degree_le_nat_degree : degree p ≤ nat_degree p := begin by_cases hp : p = 0, { rw hp, exact bot_le }, rw [degree_eq_nat_degree hp], exact le_refl _ end lemma nat_degree_eq_of_degree_eq [semiring S] {q : polynomial S} (h : degree p = degree q) : nat_degree p = nat_degree q := by unfold nat_degree; rw h lemma le_degree_of_ne_zero (h : coeff p n ≠ 0) : (n : with_bot ℕ) ≤ degree p := show @has_le.le (with_bot ℕ) _ (some n : with_bot ℕ) (p.support.sup some : with_bot ℕ), from finset.le_sup (finsupp.mem_support_iff.2 h) lemma le_nat_degree_of_ne_zero (h : coeff p n ≠ 0) : n ≤ nat_degree p := begin rw [← with_bot.coe_le_coe, ← degree_eq_nat_degree], exact le_degree_of_ne_zero h, { assume h, subst h, exact h rfl } end lemma degree_le_degree (h : coeff q (nat_degree p) ≠ 0) : degree p ≤ degree q := begin by_cases hp : p = 0, { rw hp, exact bot_le }, { rw degree_eq_nat_degree hp, exact le_degree_of_ne_zero h } end lemma degree_ne_of_nat_degree_ne {n : ℕ} : p.nat_degree ≠ n → degree p ≠ n := @option.cases_on _ (λ d, d.get_or_else 0 ≠ n → d ≠ n) p.degree (λ _ h, option.no_confusion h) (λ n' h, mt option.some_inj.mp h) theorem nat_degree_le_of_degree_le {n : ℕ} (H : degree p ≤ n) : nat_degree p ≤ n := show option.get_or_else (degree p) 0 ≤ n, from match degree p, H with | none, H := zero_le _ | (some d), H := with_bot.coe_le_coe.1 H end lemma nat_degree_le_nat_degree (hpq : p.degree ≤ q.degree) : p.nat_degree ≤ q.nat_degree := begin by_cases hp : p = 0, { rw [hp, nat_degree_zero], exact zero_le _ }, by_cases hq : q = 0, { rw [hq, degree_zero, le_bot_iff, degree_eq_bot] at hpq, cc }, rwa [degree_eq_nat_degree hp, degree_eq_nat_degree hq, with_bot.coe_le_coe] at hpq end @[simp] lemma degree_C (ha : a ≠ 0) : degree (C a) = (0 : with_bot ℕ) := show sup (ite (a = 0) ∅ {0}) some = 0, by rw if_neg ha; refl lemma degree_C_le : degree (C a) ≤ (0 : with_bot ℕ) := by by_cases h : a = 0; [rw [h, C_0], rw [degree_C h]]; [exact bot_le, exact le_refl _] lemma degree_one_le : degree (1 : polynomial R) ≤ (0 : with_bot ℕ) := by rw [← C_1]; exact degree_C_le @[simp] lemma nat_degree_C (a : R) : nat_degree (C a) = 0 := begin by_cases ha : a = 0, { have : C a = 0, { rw [ha, C_0] }, rw [nat_degree, degree_eq_bot.2 this], refl }, { rw [nat_degree, degree_C ha], refl } end @[simp] lemma nat_degree_one : nat_degree (1 : polynomial R) = 0 := nat_degree_C 1 @[simp] lemma nat_degree_nat_cast (n : ℕ) : nat_degree (n : polynomial R) = 0 := by simp only [←C_eq_nat_cast, nat_degree_C] @[simp] lemma degree_monomial (n : ℕ) (ha : a ≠ 0) : degree (C a * X ^ n) = n := by rw [← single_eq_C_mul_X, degree, monomial, support_single_ne_zero ha]; refl lemma degree_monomial_le (n : ℕ) (a : R) : degree (C a * X ^ n) ≤ n := if h : a = 0 then by rw [h, C_0, zero_mul]; exact bot_le else le_of_eq (degree_monomial n h) @[simp] lemma nat_degree_C_mul_X_pow (n : ℕ) (a : R) (ha : a ≠ 0) : nat_degree (C a * X ^ n) = n := nat_degree_eq_of_degree_eq_some (degree_monomial n ha) lemma coeff_eq_zero_of_degree_lt (h : degree p < n) : coeff p n = 0 := not_not.1 (mt le_degree_of_ne_zero (not_le_of_gt h)) lemma coeff_eq_zero_of_nat_degree_lt {p : polynomial R} {n : ℕ} (h : p.nat_degree < n) : p.coeff n = 0 := begin apply coeff_eq_zero_of_degree_lt, by_cases hp : p = 0, { subst hp, exact with_bot.bot_lt_coe n }, { rwa [degree_eq_nat_degree hp, with_bot.coe_lt_coe] } end @[simp] lemma coeff_nat_degree_succ_eq_zero {p : polynomial R} : p.coeff (p.nat_degree + 1) = 0 := coeff_eq_zero_of_nat_degree_lt (lt_add_one _) -- We need the explicit `decidable` argument here because an exotic one shows up in a moment! lemma ite_le_nat_degree_coeff (p : polynomial R) (n : ℕ) (I : decidable (n < 1 + nat_degree p)) : @ite (n < 1 + nat_degree p) I _ (coeff p n) 0 = coeff p n := begin split_ifs, { refl }, { exact (coeff_eq_zero_of_nat_degree_lt (not_le.1 (λ w, h (nat.lt_one_add_iff.2 w)))).symm, } end lemma as_sum_range (p : polynomial R) : p = ∑ i in range (p.nat_degree + 1), C (p.coeff i) * X^i := begin ext n, simp only [add_comm, coeff_X_pow, coeff_C_mul, finset.mem_range, finset.sum_mul_boole, finset_sum_coeff, ite_le_nat_degree_coeff], end lemma as_sum_support (p : polynomial R) : p = ∑ i in p.support, C (p.coeff i) * X^i := begin ext n, simp only [finset_sum_coeff, coeff_C_mul, coeff_X_pow, finset.sum_mul_boole], split_ifs, { refl }, { contrapose h, rw not_not, exact mem_support_iff_coeff_ne_zero.mpr h } end /-- We can reexpress a sum over `p.support` as a sum over `range n`, for any `n` satisfying `p.nat_degree < n`. -/ lemma sum_over_range' [add_comm_monoid S] (p : polynomial R) {f : ℕ → R → S} (h : ∀ n, f n 0 = 0) (n : ℕ) (w : p.nat_degree < n) : p.sum f = ∑ (a : ℕ) in range n, f a (coeff p a) := begin rw finsupp.sum, apply finset.sum_bij_ne_zero (λ n _ _, n), { intros k h₁ h₂, simp only [mem_range], calc k ≤ p.nat_degree : _ ... < n : w, rw finsupp.mem_support_iff at h₁, exact le_nat_degree_of_ne_zero h₁, }, { intros, assumption }, { intros b hb hb', refine ⟨b, _, hb', rfl⟩, rw finsupp.mem_support_iff, contrapose! hb', convert h b, }, { intros, refl } end /-- We can reexpress a sum over `p.support` as a sum over `range (p.nat_degree + 1)`. -/ -- See also `as_sum`. lemma sum_over_range [add_comm_monoid S] (p : polynomial R) {f : ℕ → R → S} (h : ∀ n, f n 0 = 0) : p.sum f = ∑ (a : ℕ) in range (p.nat_degree + 1), f a (coeff p a) := sum_over_range' p h (p.nat_degree + 1) (lt_add_one _) lemma coeff_ne_zero_of_eq_degree (hn : degree p = n) : coeff p n ≠ 0 := λ h, mem_support_iff.mp (mem_of_max hn) h lemma eq_X_add_C_of_degree_le_one (h : degree p ≤ 1) : p = C (p.coeff 1) * X + C (p.coeff 0) := ext (λ n, nat.cases_on n (by simp) (λ n, nat.cases_on n (by simp [coeff_C]) (λ m, have degree p < m.succ.succ, from lt_of_le_of_lt h dec_trivial, by simp [coeff_eq_zero_of_degree_lt this, coeff_C, nat.succ_ne_zero, coeff_X, nat.succ_inj', @eq_comm ℕ 0]))) lemma eq_X_add_C_of_degree_eq_one (h : degree p = 1) : p = C (p.leading_coeff) * X + C (p.coeff 0) := (eq_X_add_C_of_degree_le_one (show degree p ≤ 1, from h ▸ le_refl _)).trans (by simp [leading_coeff, nat_degree_eq_of_degree_eq_some h]) theorem degree_C_mul_X_pow_le (r : R) (n : ℕ) : degree (C r * X^n) ≤ n := begin rw [← single_eq_C_mul_X], refine finset.sup_le (λ b hb, _), rw list.eq_of_mem_singleton (finsupp.support_single_subset hb), exact le_refl _ end theorem degree_X_pow_le (n : ℕ) : degree (X^n : polynomial R) ≤ n := by simpa only [C_1, one_mul] using degree_C_mul_X_pow_le (1:R) n theorem degree_X_le : degree (X : polynomial R) ≤ 1 := by simpa only [C_1, one_mul, pow_one] using degree_C_mul_X_pow_le (1:R) 1 lemma nat_degree_X_le : (X : polynomial R).nat_degree ≤ 1 := nat_degree_le_of_degree_le degree_X_le lemma mem_support_C_mul_X_pow {n a : ℕ} {c : R} : a ∈ (C c * X ^ n).support → a = n := begin rw [mem_support_iff_coeff_ne_zero, coeff_C_mul_X c n a], split_ifs with an, { intro, assumption, }, { intro h, exfalso, apply h, refl, }, end lemma support_C_mul_X_pow (c : R) (n : ℕ) : (C c * X ^ n).support ⊆ singleton n := begin intro a, rw mem_singleton, exact mem_support_C_mul_X_pow, end lemma card_support_C_mul_X_pow_le_one {c : R} {n : ℕ} : (C c * X ^ n).support.card ≤ 1 := begin rw ← card_singleton n, apply card_le_of_subset (support_C_mul_X_pow c n), end lemma le_nat_degree_of_mem_supp (a : ℕ) : a ∈ p.support → a ≤ nat_degree p:= le_nat_degree_of_ne_zero ∘ mem_support_iff_coeff_ne_zero.mp lemma le_degree_of_mem_supp (a : ℕ) : a ∈ p.support → ↑a ≤ degree p := le_degree_of_ne_zero ∘ mem_support_iff_coeff_ne_zero.mp lemma nonempty_support_iff : p.support.nonempty ↔ p ≠ 0 := by rw [ne.def, nonempty_iff_ne_empty, ne.def, ← support_eq_empty] lemma support_C_mul_X_pow_nonzero {c : R} {n : ℕ} (h : c ≠ 0): (C c * X ^ n).support = singleton n := begin ext1, rw [mem_singleton], split, { exact mem_support_C_mul_X_pow, }, { intro, rwa [mem_support_iff_coeff_ne_zero, ne.def, a_1, coeff_C_mul, coeff_X_pow_self n, mul_one], }, end end semiring section nonzero_semiring variables [semiring R] [nontrivial R] {p q : polynomial R} @[simp] lemma degree_one : degree (1 : polynomial R) = (0 : with_bot ℕ) := degree_C (show (1 : R) ≠ 0, from zero_ne_one.symm) @[simp] lemma degree_X : degree (X : polynomial R) = 1 := begin unfold X degree monomial single finsupp.support, rw if_neg (one_ne_zero : (1 : R) ≠ 0), refl end @[simp] lemma nat_degree_X : (X : polynomial R).nat_degree = 1 := nat_degree_eq_of_degree_eq_some degree_X end nonzero_semiring section ring variables [ring R] lemma coeff_mul_X_sub_C {p : polynomial R} {r : R} {a : ℕ} : coeff (p * (X - C r)) (a + 1) = coeff p a - coeff p (a + 1) * r := by simp [mul_sub] @[simp] lemma C_eq_int_cast (n : ℤ) : C ↑n = (n : polynomial R) := (C : R →+* _).map_int_cast n @[simp] lemma degree_neg (p : polynomial R) : degree (-p) = degree p := by unfold degree; rw support_neg @[simp] lemma nat_degree_neg (p : polynomial R) : nat_degree (-p) = nat_degree p := by simp [nat_degree] @[simp] lemma nat_degree_int_cast (n : ℤ) : nat_degree (n : polynomial R) = 0 := by simp only [←C_eq_int_cast, nat_degree_C] end ring section semiring variables [semiring R] /-- The second-highest coefficient, or 0 for constants -/ def next_coeff (p : polynomial R) : R := if p.nat_degree = 0 then 0 else p.coeff (p.nat_degree - 1) @[simp] lemma next_coeff_C_eq_zero (c : R) : next_coeff (C c) = 0 := by { rw next_coeff, simp } lemma next_coeff_of_pos_nat_degree (p : polynomial R) (hp : 0 < p.nat_degree) : next_coeff p = p.coeff (p.nat_degree - 1) := by { rw [next_coeff, if_neg], contrapose! hp, simpa } end semiring section semiring variables [semiring R] {p q : polynomial R} {ι : Type*} lemma coeff_nat_degree_eq_zero_of_degree_lt (h : degree p < degree q) : coeff p (nat_degree q) = 0 := coeff_eq_zero_of_degree_lt (lt_of_lt_of_le h degree_le_nat_degree) lemma ne_zero_of_degree_gt {n : with_bot ℕ} (h : n < degree p) : p ≠ 0 := mt degree_eq_bot.2 (ne.symm (ne_of_lt (lt_of_le_of_lt bot_le h))) lemma eq_C_of_degree_le_zero (h : degree p ≤ 0) : p = C (coeff p 0) := begin refine ext (λ n, _), cases n, { simp }, { have : degree p < ↑(nat.succ n) := lt_of_le_of_lt h (with_bot.some_lt_some.2 (nat.succ_pos _)), rw [coeff_C, if_neg (nat.succ_ne_zero _), coeff_eq_zero_of_degree_lt this] } end lemma eq_C_of_degree_eq_zero (h : degree p = 0) : p = C (coeff p 0) := eq_C_of_degree_le_zero (h ▸ le_refl _) lemma degree_le_zero_iff : degree p ≤ 0 ↔ p = C (coeff p 0) := ⟨eq_C_of_degree_le_zero, λ h, h.symm ▸ degree_C_le⟩ lemma degree_add_le (p q : polynomial R) : degree (p + q) ≤ max (degree p) (degree q) := calc degree (p + q) = ((p + q).support).sup some : rfl ... ≤ (p.support ∪ q.support).sup some : by convert sup_mono support_add ... = p.support.sup some ⊔ q.support.sup some : by convert sup_union ... = _ : with_bot.sup_eq_max _ _ @[simp] lemma leading_coeff_zero : leading_coeff (0 : polynomial R) = 0 := rfl @[simp] lemma leading_coeff_eq_zero : leading_coeff p = 0 ↔ p = 0 := ⟨λ h, by_contradiction $ λ hp, mt mem_support_iff.1 (not_not.2 h) (mem_of_max (degree_eq_nat_degree hp)), λ h, h.symm ▸ leading_coeff_zero⟩ lemma leading_coeff_eq_zero_iff_deg_eq_bot : leading_coeff p = 0 ↔ degree p = ⊥ := by rw [leading_coeff_eq_zero, degree_eq_bot] lemma nat_degree_mem_support_of_nonzero (H : p ≠ 0) : p.nat_degree ∈ p.support := (p.mem_support_to_fun p.nat_degree).mpr ((not_congr leading_coeff_eq_zero).mpr H) lemma nat_degree_eq_support_max' (h : p ≠ 0) : p.nat_degree = p.support.max' (nonempty_support_iff.mpr h) := begin apply le_antisymm, { apply finset.le_max', rw mem_support_iff_coeff_ne_zero, exact (not_congr leading_coeff_eq_zero).mpr h, }, { apply max'_le, refine le_nat_degree_of_mem_supp, }, end lemma nat_degree_C_mul_X_pow_le (a : R) (n : ℕ) : nat_degree (C a * X ^ n) ≤ n := begin by_cases a0 : a = 0, { rw [a0, C_0, zero_mul, nat_degree_zero], exact nat.zero_le n, }, { rw nat_degree_eq_support_max', { simp_rw [support_C_mul_X_pow_nonzero a0, max'_singleton n], }, { intro, apply a0, rw [← C_inj, C_0], apply mul_X_pow_eq_zero a_1, }, }, end lemma nat_degree_C_mul_X_pow_of_nonzero {a : R} (n : ℕ) (ha : a ≠ 0) : nat_degree (C a * X ^ n) = n := begin rw nat_degree_eq_support_max', { simp_rw [support_C_mul_X_pow_nonzero ha, max'_singleton n], }, { intro, apply ha, rw [← C_inj, C_0], exact mul_X_pow_eq_zero a_1, }, end lemma degree_add_eq_of_degree_lt (h : degree p < degree q) : degree (p + q) = degree q := le_antisymm (max_eq_right_of_lt h ▸ degree_add_le _ _) $ degree_le_degree $ begin rw [coeff_add, coeff_nat_degree_eq_zero_of_degree_lt h, zero_add], exact mt leading_coeff_eq_zero.1 (ne_zero_of_degree_gt h) end lemma degree_add_C (hp : 0 < degree p) : degree (p + C a) = degree p := add_comm (C a) p ▸ degree_add_eq_of_degree_lt $ lt_of_le_of_lt degree_C_le hp lemma degree_add_eq_of_leading_coeff_add_ne_zero (h : leading_coeff p + leading_coeff q ≠ 0) : degree (p + q) = max p.degree q.degree := le_antisymm (degree_add_le _ _) $ match lt_trichotomy (degree p) (degree q) with | or.inl hlt := by rw [degree_add_eq_of_degree_lt hlt, max_eq_right_of_lt hlt]; exact le_refl _ | or.inr (or.inl heq) := le_of_not_gt $ assume hlt : max (degree p) (degree q) > degree (p + q), h $ show leading_coeff p + leading_coeff q = 0, begin rw [heq, max_self] at hlt, rw [leading_coeff, leading_coeff, nat_degree_eq_of_degree_eq heq, ← coeff_add], exact coeff_nat_degree_eq_zero_of_degree_lt hlt end | or.inr (or.inr hlt) := by rw [add_comm, degree_add_eq_of_degree_lt hlt, max_eq_left_of_lt hlt]; exact le_refl _ end lemma degree_erase_le (p : polynomial R) (n : ℕ) : degree (p.erase n) ≤ degree p := by convert sup_mono (erase_subset _ _) lemma degree_erase_lt (hp : p ≠ 0) : degree (p.erase (nat_degree p)) < degree p := lt_of_le_of_ne (degree_erase_le _ _) $ (degree_eq_nat_degree hp).symm ▸ (by convert λ h, not_mem_erase _ _ (mem_of_max h)) lemma degree_sum_le (s : finset ι) (f : ι → polynomial R) : degree (∑ i in s, f i) ≤ s.sup (λ b, degree (f b)) := finset.induction_on s (by simp only [sum_empty, sup_empty, degree_zero, le_refl]) $ assume a s has ih, calc degree (∑ i in insert a s, f i) ≤ max (degree (f a)) (degree (∑ i in s, f i)) : by rw sum_insert has; exact degree_add_le _ _ ... ≤ _ : by rw [sup_insert, with_bot.sup_eq_max]; exact max_le_max (le_refl _) ih lemma degree_mul_le (p q : polynomial R) : degree (p * q) ≤ degree p + degree q := calc degree (p * q) ≤ (p.support).sup (λi, degree (sum q (λj a, C (coeff p i * a) * X ^ (i + j)))) : by simp only [single_eq_C_mul_X.symm]; exact degree_sum_le _ _ ... ≤ p.support.sup (λi, q.support.sup (λj, degree (C (coeff p i * coeff q j) * X ^ (i + j)))) : finset.sup_mono_fun (assume i hi, degree_sum_le _ _) ... ≤ degree p + degree q : begin refine finset.sup_le (λ a ha, finset.sup_le (λ b hb, le_trans (degree_monomial_le _ _) _)), rw [with_bot.coe_add], rw mem_support_iff at ha hb, exact add_le_add (le_degree_of_ne_zero ha) (le_degree_of_ne_zero hb) end lemma degree_pow_le (p : polynomial R) : ∀ n, degree (p ^ n) ≤ n •ℕ (degree p) | 0 := by rw [pow_zero, zero_nsmul]; exact degree_one_le | (n+1) := calc degree (p ^ (n + 1)) ≤ degree p + degree (p ^ n) : by rw pow_succ; exact degree_mul_le _ _ ... ≤ _ : by rw succ_nsmul; exact add_le_add (le_refl _) (degree_pow_le _) @[simp] lemma leading_coeff_monomial (a : R) (n : ℕ) : leading_coeff (C a * X ^ n) = a := begin by_cases ha : a = 0, { simp only [ha, C_0, zero_mul, leading_coeff_zero] }, { rw [leading_coeff, nat_degree, degree_monomial _ ha, ← single_eq_C_mul_X], exact @finsupp.single_eq_same _ _ _ n a } end @[simp] lemma leading_coeff_C (a : R) : leading_coeff (C a) = a := suffices leading_coeff (C a * X^0) = a, by rwa [pow_zero, mul_one] at this, leading_coeff_monomial a 0 @[simp] lemma leading_coeff_X : leading_coeff (X : polynomial R) = 1 := suffices leading_coeff (C (1:R) * X^1) = 1, by rwa [C_1, pow_one, one_mul] at this, leading_coeff_monomial 1 1 @[simp] lemma monic_X : monic (X : polynomial R) := leading_coeff_X @[simp] lemma leading_coeff_one : leading_coeff (1 : polynomial R) = 1 := suffices leading_coeff (C (1:R) * X^0) = 1, by rwa [C_1, pow_zero, mul_one] at this, leading_coeff_monomial 1 0 @[simp] lemma monic_one : monic (1 : polynomial R) := leading_coeff_C _ lemma monic.ne_zero_of_zero_ne_one (h : (0:R) ≠ 1) {p : polynomial R} (hp : p.monic) : p ≠ 0 := by { contrapose! h, rwa [h] at hp } lemma monic.ne_zero {R : Type*} [semiring R] [nontrivial R] {p : polynomial R} (hp : p.monic) : p ≠ 0 := hp.ne_zero_of_zero_ne_one zero_ne_one lemma leading_coeff_add_of_degree_lt (h : degree p < degree q) : leading_coeff (p + q) = leading_coeff q := have coeff p (nat_degree q) = 0, from coeff_nat_degree_eq_zero_of_degree_lt h, by simp only [leading_coeff, nat_degree_eq_of_degree_eq (degree_add_eq_of_degree_lt h), this, coeff_add, zero_add] lemma leading_coeff_add_of_degree_eq (h : degree p = degree q) (hlc : leading_coeff p + leading_coeff q ≠ 0) : leading_coeff (p + q) = leading_coeff p + leading_coeff q := have nat_degree (p + q) = nat_degree p, by apply nat_degree_eq_of_degree_eq; rw [degree_add_eq_of_leading_coeff_add_ne_zero hlc, h, max_self], by simp only [leading_coeff, this, nat_degree_eq_of_degree_eq h, coeff_add] @[simp] lemma coeff_mul_degree_add_degree (p q : polynomial R) : coeff (p * q) (nat_degree p + nat_degree q) = leading_coeff p * leading_coeff q := calc coeff (p * q) (nat_degree p + nat_degree q) = ∑ x in nat.antidiagonal (nat_degree p + nat_degree q), coeff p x.1 * coeff q x.2 : coeff_mul _ _ _ ... = coeff p (nat_degree p) * coeff q (nat_degree q) : begin refine finset.sum_eq_single (nat_degree p, nat_degree q) _ _, { rintro ⟨i,j⟩ h₁ h₂, rw nat.mem_antidiagonal at h₁, by_cases H : nat_degree p < i, { rw [coeff_eq_zero_of_degree_lt (lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 H)), zero_mul] }, { rw not_lt_iff_eq_or_lt at H, cases H, { subst H, rw add_left_cancel_iff at h₁, dsimp at h₁, subst h₁, exfalso, exact h₂ rfl }, { suffices : nat_degree q < j, { rw [coeff_eq_zero_of_degree_lt (lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 this)), mul_zero] }, { by_contra H', rw not_lt at H', exact ne_of_lt (nat.lt_of_lt_of_le (nat.add_lt_add_right H j) (nat.add_le_add_left H' _)) h₁ } } } }, { intro H, exfalso, apply H, rw nat.mem_antidiagonal } end lemma degree_mul' (h : leading_coeff p * leading_coeff q ≠ 0) : degree (p * q) = degree p + degree q := have hp : p ≠ 0 := by refine mt _ h; exact λ hp, by rw [hp, leading_coeff_zero, zero_mul], have hq : q ≠ 0 := by refine mt _ h; exact λ hq, by rw [hq, leading_coeff_zero, mul_zero], le_antisymm (degree_mul_le _ _) begin rw [degree_eq_nat_degree hp, degree_eq_nat_degree hq], refine le_degree_of_ne_zero _, rwa coeff_mul_degree_add_degree end lemma nat_degree_mul' (h : leading_coeff p * leading_coeff q ≠ 0) : nat_degree (p * q) = nat_degree p + nat_degree q := have hp : p ≠ 0 := mt leading_coeff_eq_zero.2 (λ h₁, h $ by rw [h₁, zero_mul]), have hq : q ≠ 0 := mt leading_coeff_eq_zero.2 (λ h₁, h $ by rw [h₁, mul_zero]), have hpq : p * q ≠ 0 := λ hpq, by rw [← coeff_mul_degree_add_degree, hpq, coeff_zero] at h; exact h rfl, option.some_inj.1 (show (nat_degree (p * q) : with_bot ℕ) = nat_degree p + nat_degree q, by rw [← degree_eq_nat_degree hpq, degree_mul' h, degree_eq_nat_degree hp, degree_eq_nat_degree hq]) lemma leading_coeff_mul' (h : leading_coeff p * leading_coeff q ≠ 0) : leading_coeff (p * q) = leading_coeff p * leading_coeff q := begin unfold leading_coeff, rw [nat_degree_mul' h, coeff_mul_degree_add_degree], refl end lemma leading_coeff_pow' : leading_coeff p ^ n ≠ 0 → leading_coeff (p ^ n) = leading_coeff p ^ n := nat.rec_on n (by simp) $ λ n ih h, have h₁ : leading_coeff p ^ n ≠ 0 := λ h₁, h $ by rw [pow_succ, h₁, mul_zero], have h₂ : leading_coeff p * leading_coeff (p ^ n) ≠ 0 := by rwa [pow_succ, ← ih h₁] at h, by rw [pow_succ, pow_succ, leading_coeff_mul' h₂, ih h₁] lemma degree_pow' : ∀ {n}, leading_coeff p ^ n ≠ 0 → degree (p ^ n) = n •ℕ (degree p) | 0 := λ h, by rw [pow_zero, ← C_1] at *; rw [degree_C h, zero_nsmul] | (n+1) := λ h, have h₁ : leading_coeff p ^ n ≠ 0 := λ h₁, h $ by rw [pow_succ, h₁, mul_zero], have h₂ : leading_coeff p * leading_coeff (p ^ n) ≠ 0 := by rwa [pow_succ, ← leading_coeff_pow' h₁] at h, by rw [pow_succ, degree_mul' h₂, succ_nsmul, degree_pow' h₁] lemma nat_degree_pow' {n : ℕ} (h : leading_coeff p ^ n ≠ 0) : nat_degree (p ^ n) = n * nat_degree p := if hp0 : p = 0 then if hn0 : n = 0 then by simp * else by rw [hp0, zero_pow (nat.pos_of_ne_zero hn0)]; simp else have hpn : p ^ n ≠ 0, from λ hpn0, have h1 : _ := h, by rw [← leading_coeff_pow' h1, hpn0, leading_coeff_zero] at h; exact h rfl, option.some_inj.1 $ show (nat_degree (p ^ n) : with_bot ℕ) = (n * nat_degree p : ℕ), by rw [← degree_eq_nat_degree hpn, degree_pow' h, degree_eq_nat_degree hp0, ← with_bot.coe_nsmul]; simp @[simp] lemma leading_coeff_X_pow : ∀ n : ℕ, leading_coeff ((X : polynomial R) ^ n) = 1 | 0 := by simp | (n+1) := if h10 : (1 : R) = 0 then by rw [pow_succ, ← one_mul X, ← C_1, h10]; simp else have h : leading_coeff (X : polynomial R) * leading_coeff (X ^ n) ≠ 0, by rw [leading_coeff_X, leading_coeff_X_pow n, one_mul]; exact h10, by rw [pow_succ, leading_coeff_mul' h, leading_coeff_X, leading_coeff_X_pow, one_mul] theorem leading_coeff_mul_X_pow {p : polynomial R} {n : ℕ} : leading_coeff (p * X ^ n) = leading_coeff p := decidable.by_cases (λ H : leading_coeff p = 0, by rw [H, leading_coeff_eq_zero.1 H, zero_mul, leading_coeff_zero]) (λ H : leading_coeff p ≠ 0, by rw [leading_coeff_mul', leading_coeff_X_pow, mul_one]; rwa [leading_coeff_X_pow, mul_one]) lemma nat_degree_mul_le {p q : polynomial R} : nat_degree (p * q) ≤ nat_degree p + nat_degree q := begin apply nat_degree_le_of_degree_le, apply le_trans (degree_mul_le p q), rw with_bot.coe_add, refine add_le_add _ _; apply degree_le_nat_degree, end lemma subsingleton_of_monic_zero (h : monic (0 : polynomial R)) : (∀ p q : polynomial R, p = q) ∧ (∀ a b : R, a = b) := by rw [monic.def, leading_coeff_zero] at h; exact ⟨λ p q, by rw [← mul_one p, ← mul_one q, ← C_1, ← h, C_0, mul_zero, mul_zero], λ a b, by rw [← mul_one a, ← mul_one b, ← h, mul_zero, mul_zero]⟩ lemma zero_le_degree_iff {p : polynomial R} : 0 ≤ degree p ↔ p ≠ 0 := by rw [ne.def, ← degree_eq_bot]; cases degree p; exact dec_trivial lemma degree_nonneg_iff_ne_zero : 0 ≤ degree p ↔ p ≠ 0 := ⟨λ h0p hp0, absurd h0p (by rw [hp0, degree_zero]; exact dec_trivial), λ hp0, le_of_not_gt (λ h, by simp [gt, degree_eq_bot, *] at *)⟩ lemma nat_degree_eq_zero_iff_degree_le_zero : p.nat_degree = 0 ↔ p.degree ≤ 0 := if hp0 : p = 0 then by simp [hp0] else by rw [degree_eq_nat_degree hp0, ← with_bot.coe_zero, with_bot.coe_le_coe, nat.le_zero_iff] theorem degree_le_iff_coeff_zero (f : polynomial R) (n : with_bot ℕ) : degree f ≤ n ↔ ∀ m : ℕ, n < m → coeff f m = 0 := ⟨λ (H : finset.sup (f.support) some ≤ n) m (Hm : n < (m : with_bot ℕ)), decidable.of_not_not $ λ H4, have H1 : m ∉ f.support, from λ H2, not_lt_of_ge ((finset.sup_le_iff.1 H) m H2 : ((m : with_bot ℕ) ≤ n)) Hm, H1 $ (finsupp.mem_support_to_fun f m).2 H4, λ H, finset.sup_le $ λ b Hb, decidable.of_not_not $ λ Hn, (finsupp.mem_support_to_fun f b).1 Hb $ H b $ lt_of_not_ge Hn⟩ lemma degree_lt_degree_mul_X (hp : p ≠ 0) : p.degree < (p * X).degree := by haveI := nonzero.of_polynomial_ne hp; exact have leading_coeff p * leading_coeff X ≠ 0, by simpa, by erw [degree_mul' this, degree_eq_nat_degree hp, degree_X, ← with_bot.coe_one, ← with_bot.coe_add, with_bot.coe_lt_coe]; exact nat.lt_succ_self _ lemma eq_C_of_nat_degree_le_zero {p : polynomial R} (h : nat_degree p ≤ 0) : p = C (coeff p 0) := begin refine polynomial.ext (λ n, _), cases n, { simp }, { have : nat_degree p < nat.succ n := lt_of_le_of_lt h (nat.succ_pos _), rw [coeff_C, if_neg (nat.succ_ne_zero _), coeff_eq_zero_of_nat_degree_lt this] } end lemma nat_degree_pos_iff_degree_pos {p : polynomial R} : 0 < nat_degree p ↔ 0 < degree p := ⟨ λ h, ((degree_eq_iff_nat_degree_eq_of_pos h).mpr rfl).symm ▸ (with_bot.some_lt_some.mpr h), by { unfold nat_degree, cases degree p, { rintros ⟨_, ⟨⟩, _⟩ }, { exact with_bot.some_lt_some.mp } } ⟩ end semiring section nonzero_semiring variables [semiring R] [nontrivial R] {p q : polynomial R} @[simp] lemma degree_X_pow : ∀ (n : ℕ), degree ((X : polynomial R) ^ n) = n | 0 := by simp only [pow_zero, degree_one]; refl | (n+1) := have h : leading_coeff (X : polynomial R) * leading_coeff (X ^ n) ≠ 0, by rw [leading_coeff_X, leading_coeff_X_pow n, one_mul]; exact zero_ne_one.symm, by rw [pow_succ, degree_mul' h, degree_X, degree_X_pow, add_comm]; refl theorem not_is_unit_X : ¬ is_unit (X : polynomial R) := λ ⟨⟨_, g, hfg, hgf⟩, rfl⟩, @zero_ne_one R _ _ $ by { rw [← coeff_one_zero, ← hgf], simp } end nonzero_semiring section ring variables [ring R] {p q : polynomial R} lemma degree_sub_le (p q : polynomial R) : degree (p - q) ≤ max (degree p) (degree q) := degree_neg q ▸ degree_add_le p (-q) lemma degree_sub_lt (hd : degree p = degree q) (hp0 : p ≠ 0) (hlc : leading_coeff p = leading_coeff q) : degree (p - q) < degree p := have hp : single (nat_degree p) (leading_coeff p) + p.erase (nat_degree p) = p := finsupp.single_add_erase, have hq : single (nat_degree q) (leading_coeff q) + q.erase (nat_degree q) = q := finsupp.single_add_erase, have hd' : nat_degree p = nat_degree q := by unfold nat_degree; rw hd, have hq0 : q ≠ 0 := mt degree_eq_bot.2 (hd ▸ mt degree_eq_bot.1 hp0), calc degree (p - q) = degree (erase (nat_degree q) p + -erase (nat_degree q) q) : by conv {to_lhs, rw [← hp, ← hq, hlc, hd', add_sub_add_left_eq_sub, sub_eq_add_neg]} ... ≤ max (degree (erase (nat_degree q) p)) (degree (erase (nat_degree q) q)) : degree_neg (erase (nat_degree q) q) ▸ degree_add_le _ _ ... < degree p : max_lt_iff.2 ⟨hd' ▸ degree_erase_lt hp0, hd.symm ▸ degree_erase_lt hq0⟩ lemma nat_degree_X_sub_C_le {r : R} : (X - C r).nat_degree ≤ 1 := nat_degree_le_of_degree_le $ le_trans (degree_sub_le _ _) $ max_le degree_X_le $ le_trans degree_C_le $ with_bot.coe_le_coe.2 zero_le_one end ring section nonzero_ring variables [nontrivial R] [ring R] @[simp] lemma degree_X_sub_C (a : R) : degree (X - C a) = 1 := begin rw [sub_eq_add_neg, add_comm, ← @degree_X R], by_cases ha : a = 0, { simp only [ha, C_0, neg_zero, zero_add] }, exact degree_add_eq_of_degree_lt (by rw [degree_X, degree_neg, degree_C ha]; exact dec_trivial) end @[simp] lemma nat_degree_X_sub_C (x : R) : (X - C x).nat_degree = 1 := nat_degree_eq_of_degree_eq_some $ degree_X_sub_C x @[simp] lemma next_coeff_X_sub_C (c : R) : next_coeff (X - C c) = - c := by simp [next_coeff_of_pos_nat_degree] lemma degree_X_pow_sub_C {n : ℕ} (hn : 0 < n) (a : R) : degree ((X : polynomial R) ^ n - C a) = n := have degree (-C a) < degree ((X : polynomial R) ^ n), from calc degree (-C a) ≤ 0 : by rw degree_neg; exact degree_C_le ... < degree ((X : polynomial R) ^ n) : by rwa [degree_X_pow]; exact with_bot.coe_lt_coe.2 hn, by rw [sub_eq_add_neg, add_comm, degree_add_eq_of_degree_lt this, degree_X_pow] lemma X_pow_sub_C_ne_zero {n : ℕ} (hn : 0 < n) (a : R) : (X : polynomial R) ^ n - C a ≠ 0 := mt degree_eq_bot.2 (show degree ((X : polynomial R) ^ n - C a) ≠ ⊥, by rw degree_X_pow_sub_C hn a; exact dec_trivial) theorem X_sub_C_ne_zero (r : R) : X - C r ≠ 0 := pow_one (X : polynomial R) ▸ X_pow_sub_C_ne_zero zero_lt_one r lemma nat_degree_X_pow_sub_C {n : ℕ} (hn : 0 < n) {r : R} : (X ^ n - C r).nat_degree = n := by { apply nat_degree_eq_of_degree_eq_some, simp [degree_X_pow_sub_C hn], } end nonzero_ring section integral_domain variables [integral_domain R] {p q : polynomial R} @[simp] lemma degree_mul : degree (p * q) = degree p + degree q := if hp0 : p = 0 then by simp only [hp0, degree_zero, zero_mul, with_bot.bot_add] else if hq0 : q = 0 then by simp only [hq0, degree_zero, mul_zero, with_bot.add_bot] else degree_mul' $ mul_ne_zero (mt leading_coeff_eq_zero.1 hp0) (mt leading_coeff_eq_zero.1 hq0) @[simp] lemma degree_pow (p : polynomial R) (n : ℕ) : degree (p ^ n) = n •ℕ (degree p) := by induction n; [simp only [pow_zero, degree_one, zero_nsmul], simp only [*, pow_succ, succ_nsmul, degree_mul]] @[simp] lemma leading_coeff_mul (p q : polynomial R) : leading_coeff (p * q) = leading_coeff p * leading_coeff q := begin by_cases hp : p = 0, { simp only [hp, zero_mul, leading_coeff_zero] }, { by_cases hq : q = 0, { simp only [hq, mul_zero, leading_coeff_zero] }, { rw [leading_coeff_mul'], exact mul_ne_zero (mt leading_coeff_eq_zero.1 hp) (mt leading_coeff_eq_zero.1 hq) } } end @[simp] lemma leading_coeff_X_add_C (a b : R) (ha : a ≠ 0): leading_coeff (C a * X + C b) = a := begin rw [add_comm, leading_coeff_add_of_degree_lt], { simp }, { simpa [degree_C ha] using lt_of_le_of_lt degree_C_le (with_bot.coe_lt_coe.2 zero_lt_one)} end /-- `polynomial.leading_coeff` bundled as a `monoid_hom` when `R` is an `integral_domain`, and thus `leading_coeff` is multiplicative -/ def leading_coeff_hom : polynomial R →* R := { to_fun := leading_coeff, map_one' := by simp, map_mul' := leading_coeff_mul } @[simp] lemma leading_coeff_hom_apply (p : polynomial R) : leading_coeff_hom p = leading_coeff p := rfl @[simp] lemma leading_coeff_pow (p : polynomial R) (n : ℕ) : leading_coeff (p ^ n) = leading_coeff p ^ n := leading_coeff_hom.map_pow p n end integral_domain end polynomial
99abb7dd0a341a2c16a9c12a69a6bfc99bc4f47c
9b9a16fa2cb737daee6b2785474678b6fa91d6d4
/src/data/complex/exponential.lean
9e3e8744c63fea9b75b3df84355681a0978062ed
[ "Apache-2.0" ]
permissive
johoelzl/mathlib
253f46daa30b644d011e8e119025b01ad69735c4
592e3c7a2dfbd5826919b4605559d35d4d75938f
refs/heads/master
1,625,657,216,488
1,551,374,946,000
1,551,374,946,000
98,915,829
0
0
Apache-2.0
1,522,917,267,000
1,501,524,499,000
Lean
UTF-8
Lean
false
false
46,845
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir -/ import algebra.archimedean import data.nat.choose data.complex.basic import tactic.linarith local attribute [instance, priority 0] classical.prop_decidable local notation `abs'` := _root_.abs open is_absolute_value section open real is_absolute_value finset lemma forall_ge_le_of_forall_le_succ {α : Type*} [preorder α] (f : ℕ → α) {m : ℕ} (h : ∀ n ≥ m, f n.succ ≤ f n) : ∀ {l}, ∀ k ≥ m, k ≤ l → f l ≤ f k := begin assume l k hkm hkl, generalize hp : l - k = p, have : l = k + p := add_comm p k ▸ (nat.sub_eq_iff_eq_add hkl).1 hp, subst this, clear hkl hp, induction p with p ih, { simp }, { exact le_trans (h _ (le_trans hkm (nat.le_add_right _ _))) ih } end variables {α : Type*} {β : Type*} [ring β] [discrete_linear_ordered_field α] [archimedean α] {abv : β → α} [is_absolute_value abv] lemma is_cau_of_decreasing_bounded (f : ℕ → α) {a : α} {m : ℕ} (ham : ∀ n ≥ m, abs (f n) ≤ a) (hnm : ∀ n ≥ m, f n.succ ≤ f n) : is_cau_seq abs f := λ ε ε0, let ⟨k, hk⟩ := archimedean.arch a ε0 in have h : ∃ l, ∀ n ≥ m, a - add_monoid.smul l ε < f n := ⟨k + k + 1, λ n hnm, lt_of_lt_of_le (show a - add_monoid.smul (k + (k + 1)) ε < -abs (f n), from lt_neg.1 $ lt_of_le_of_lt (ham n hnm) (begin rw [neg_sub, lt_sub_iff_add_lt, add_monoid.add_smul], exact add_lt_add_of_le_of_lt hk (lt_of_le_of_lt hk (lt_add_of_pos_left _ ε0)), end)) (neg_le.2 $ (abs_neg (f n)) ▸ le_abs_self _)⟩, let l := nat.find h in have hl : ∀ (n : ℕ), n ≥ m → f n > a - add_monoid.smul l ε := nat.find_spec h, have hl0 : l ≠ 0 := λ hl0, not_lt_of_ge (ham m (le_refl _)) (lt_of_lt_of_le (by have := hl m (le_refl m); simpa [hl0] using this) (le_abs_self (f m))), begin cases classical.not_forall.1 (nat.find_min h (nat.pred_lt hl0)) with i hi, rw [not_imp, not_lt] at hi, existsi i, assume j hj, have hfij : f j ≤ f i := forall_ge_le_of_forall_le_succ f hnm _ hi.1 hj, rw [abs_of_nonpos (sub_nonpos.2 hfij), neg_sub, sub_lt_iff_lt_add'], exact calc f i ≤ a - add_monoid.smul (nat.pred l) ε : hi.2 ... = a - add_monoid.smul l ε + ε : by conv {to_rhs, rw [← nat.succ_pred_eq_of_pos (nat.pos_of_ne_zero hl0), succ_smul', sub_add, add_sub_cancel] } ... < f j + ε : add_lt_add_right (hl j (le_trans hi.1 hj)) _ end lemma is_cau_of_mono_bounded (f : ℕ → α) {a : α} {m : ℕ} (ham : ∀ n ≥ m, abs (f n) ≤ a) (hnm : ∀ n ≥ m, f n ≤ f n.succ) : is_cau_seq abs f := begin refine @eq.rec_on (ℕ → α) _ (is_cau_seq abs) _ _ (-⟨_, @is_cau_of_decreasing_bounded _ _ _ (λ n, -f n) a m (by simpa) (by simpa)⟩ : cau_seq α abs).2, ext, exact neg_neg _ end lemma is_cau_series_of_abv_le_cau {f : ℕ → β} {g : ℕ → α} (n : ℕ) : (∀ m, n ≤ m → abv (f m) ≤ g m) → is_cau_seq abs (λ n, (range n).sum g) → is_cau_seq abv (λ n, (range n).sum f) := begin assume hm hg ε ε0, cases hg (ε / 2) (div_pos ε0 (by norm_num)) with i hi, existsi max n i, assume j ji, have hi₁ := hi j (le_trans (le_max_right n i) ji), have hi₂ := hi (max n i) (le_max_right n i), have sub_le := abs_sub_le ((range j).sum g) ((range i).sum g) ((range (max n i)).sum g), have := add_lt_add hi₁ hi₂, rw [abs_sub ((range (max n i)).sum g), add_halves ε] at this, refine lt_of_le_of_lt (le_trans (le_trans _ (le_abs_self _)) sub_le) this, generalize hk : j - max n i = k, clear this hi₂ hi₁ hi ε0 ε hg sub_le, rw nat.sub_eq_iff_eq_add ji at hk, rw hk, clear hk ji j, induction k with k' hi, { simp [abv_zero abv] }, { dsimp at *, rw [nat.succ_add, sum_range_succ, sum_range_succ, add_assoc, add_assoc], refine le_trans (abv_add _ _ _) _, exact add_le_add (hm _ (le_add_of_nonneg_of_le (nat.zero_le _) (le_max_left _ _))) hi }, end lemma is_cau_series_of_abv_cau {f : ℕ → β} : is_cau_seq abs (λ m, (range m).sum (λ n, abv (f n))) → is_cau_seq abv (λ m, (range m).sum f) := is_cau_series_of_abv_le_cau 0 (λ n h, le_refl _) lemma is_cau_geo_series {β : Type*} [field β] {abv : β → α} [is_absolute_value abv] (x : β) (hx1 : abv x < 1) : is_cau_seq abv (λ n, (range n).sum (λ m, x ^ m)) := have hx1' : abv x ≠ 1 := λ h, by simpa [h, lt_irrefl] using hx1, is_cau_series_of_abv_cau begin simp only [abv_pow abv, geom_sum hx1'] {eta := ff}, conv in (_ / _) { rw [← neg_div_neg_eq, neg_sub, neg_sub] }, refine @is_cau_of_mono_bounded _ _ _ _ ((1 : α) / (1 - abv x)) 0 _ _, { assume n hn, rw abs_of_nonneg, refine div_le_div_of_le_of_pos (sub_le_self _ (abv_pow abv x n ▸ abv_nonneg _ _)) (sub_pos.2 hx1), refine div_nonneg (sub_nonneg.2 _) (sub_pos.2 hx1), clear hn, induction n with n ih, { simp }, { rw [_root_.pow_succ, ← one_mul (1 : α)], refine mul_le_mul (le_of_lt hx1) ih (abv_pow abv x n ▸ abv_nonneg _ _) (by norm_num) } }, { assume n hn, refine div_le_div_of_le_of_pos (sub_le_sub_left _ _) (sub_pos.2 hx1), rw [← one_mul (_ ^ n), _root_.pow_succ], exact mul_le_mul_of_nonneg_right (le_of_lt hx1) (pow_nonneg (abv_nonneg _ _) _) } end lemma is_cau_geo_series_const (a : α) {x : α} (hx1 : abs x < 1) : is_cau_seq abs (λ m, (range m).sum (λ n, a * x ^ n)) := have is_cau_seq abs (λ m, a * (range m).sum (λ n, x ^ n)) := (cau_seq.const abs a * ⟨_, is_cau_geo_series x hx1⟩).2, by simpa only [mul_sum] lemma series_ratio_test {f : ℕ → β} (n : ℕ) (r : α) (hr0 : 0 ≤ r) (hr1 : r < 1) (h : ∀ m, n ≤ m → abv (f m.succ) ≤ r * abv (f m)) : is_cau_seq abv (λ m, (range m).sum f) := have har1 : abs r < 1, by rwa abs_of_nonneg hr0, begin refine is_cau_series_of_abv_le_cau n.succ _ (is_cau_geo_series_const (abv (f n.succ) * r⁻¹ ^ n.succ) har1), assume m hmn, cases classical.em (r = 0) with r_zero r_ne_zero, { have m_pos := lt_of_lt_of_le (nat.succ_pos n) hmn, have := h m.pred (nat.le_of_succ_le_succ (by rwa [nat.succ_pred_eq_of_pos m_pos])), simpa [r_zero, nat.succ_pred_eq_of_pos m_pos, pow_succ] }, generalize hk : m - n.succ = k, have r_pos : 0 < r := lt_of_le_of_ne hr0 (ne.symm r_ne_zero), replace hk : m = k + n.succ := (nat.sub_eq_iff_eq_add hmn).1 hk, induction k with k ih generalizing m n, { rw [hk, zero_add, mul_right_comm, ← pow_inv _ _ r_ne_zero, ← div_eq_mul_inv, mul_div_cancel], exact (ne_of_lt (pow_pos r_pos _)).symm }, { have kn : k + n.succ ≥ n.succ, by rw ← zero_add n.succ; exact add_le_add (zero_le _) (by simp), rw [hk, nat.succ_add, pow_succ' r, ← mul_assoc], exact le_trans (by rw mul_comm; exact h _ (nat.le_of_succ_le kn)) (mul_le_mul_of_nonneg_right (ih (k + n.succ) n h kn rfl) hr0) } end lemma sum_range_diag_flip {α : Type*} [add_comm_monoid α] (n : ℕ) (f : ℕ → ℕ → α) : (range n).sum (λ m, (range (m + 1)).sum (λ k, f k (m - k))) = (range n).sum (λ m, (range (n - m)).sum (f m)) := have h₁ : ((range n).sigma (range ∘ nat.succ)).sum (λ (a : Σ m, ℕ), f (a.2) (a.1 - a.2)) = (range n).sum (λ m, (range (m + 1)).sum (λ k, f k (m - k))) := sum_sigma, have h₂ : ((range n).sigma (λ m, range (n - m))).sum (λ a : Σ (m : ℕ), ℕ, f (a.1) (a.2)) = (range n).sum (λ m, sum (range (n - m)) (f m)) := sum_sigma, h₁ ▸ h₂ ▸ sum_bij (λ a _, ⟨a.2, a.1 - a.2⟩) (λ a ha, have h₁ : a.1 < n := mem_range.1 (mem_sigma.1 ha).1, have h₂ : a.2 < nat.succ a.1 := mem_range.1 (mem_sigma.1 ha).2, mem_sigma.2 ⟨mem_range.2 (lt_of_lt_of_le h₂ h₁), mem_range.2 ((nat.sub_lt_sub_right_iff (nat.le_of_lt_succ h₂)).2 h₁)⟩) (λ _ _, rfl) (λ ⟨a₁, a₂⟩ ⟨b₁, b₂⟩ ha hb h, have ha : a₁ < n ∧ a₂ ≤ a₁ := ⟨mem_range.1 (mem_sigma.1 ha).1, nat.le_of_lt_succ (mem_range.1 (mem_sigma.1 ha).2)⟩, have hb : b₁ < n ∧ b₂ ≤ b₁ := ⟨mem_range.1 (mem_sigma.1 hb).1, nat.le_of_lt_succ (mem_range.1 (mem_sigma.1 hb).2)⟩, have h : a₂ = b₂ ∧ _ := sigma.mk.inj h, have h' : a₁ = b₁ - b₂ + a₂ := (nat.sub_eq_iff_eq_add ha.2).1 (eq_of_heq h.2), sigma.mk.inj_iff.2 ⟨nat.sub_add_cancel hb.2 ▸ h'.symm ▸ h.1 ▸ rfl, (heq_of_eq h.1)⟩) (λ ⟨a₁, a₂⟩ ha, have ha : a₁ < n ∧ a₂ < n - a₁ := ⟨mem_range.1 (mem_sigma.1 ha).1, (mem_range.1 (mem_sigma.1 ha).2)⟩, ⟨⟨a₂ + a₁, a₁⟩, ⟨mem_sigma.2 ⟨mem_range.2 (nat.lt_sub_right_iff_add_lt.1 ha.2), mem_range.2 (nat.lt_succ_of_le (nat.le_add_left _ _))⟩, sigma.mk.inj_iff.2 ⟨rfl, heq_of_eq (nat.add_sub_cancel _ _).symm⟩⟩⟩) lemma abv_sum_le_sum_abv {γ : Type*} (f : γ → β) (s : finset γ) : abv (s.sum f) ≤ s.sum (abv ∘ f) := by haveI := classical.dec_eq γ; exact finset.induction_on s (by simp [abv_zero abv]) (λ a s has ih, by rw [sum_insert has, sum_insert has]; exact le_trans (abv_add abv _ _) (add_le_add_left ih _)) lemma sum_range_sub_sum_range {α : Type*} [add_comm_group α] {f : ℕ → α} {n m : ℕ} (hnm : n ≤ m) : (range m).sum f - (range n).sum f = ((range m).filter (λ k, n ≤ k)).sum f := begin rw [← sum_sdiff (@filter_subset _ (λ k, n ≤ k) _ (range m)), sub_eq_iff_eq_add, ← eq_sub_iff_add_eq, add_sub_cancel'], refine finset.sum_congr (finset.ext.2 $ λ a, ⟨λ h, by simp at *; finish, λ h, have ham : a < m := lt_of_lt_of_le (mem_range.1 h) hnm, by simp * at *⟩) (λ _ _, rfl), end lemma cauchy_product {a b : ℕ → β} (ha : is_cau_seq abs (λ m, (range m).sum (λ n, abv (a n)))) (hb : is_cau_seq abv (λ m, (range m).sum b)) (ε : α) (ε0 : 0 < ε) : ∃ i : ℕ, ∀ j ≥ i, abv ((range j).sum a * (range j).sum b - (range j).sum (λ n, (range (n + 1)).sum (λ m, a m * b (n - m)))) < ε := let ⟨Q, hQ⟩ := cau_seq.bounded ⟨_, hb⟩ in let ⟨P, hP⟩ := cau_seq.bounded ⟨_, ha⟩ in have hP0 : 0 < P, from lt_of_le_of_lt (abs_nonneg _) (hP 0), have hPε0 : 0 < ε / (2 * P), from div_pos ε0 (mul_pos (show (2 : α) > 0, from by norm_num) hP0), let ⟨N, hN⟩ := cau_seq.cauchy₂ ⟨_, hb⟩ hPε0 in have hQε0 : 0 < ε / (4 * Q), from div_pos ε0 (mul_pos (show (0 : α) < 4, by norm_num) (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))), let ⟨M, hM⟩ := cau_seq.cauchy₂ ⟨_, ha⟩ hQε0 in ⟨2 * (max N M + 1), λ K hK, have h₁ : sum (range K) (λ m, (range (m + 1)).sum (λ k, a k * b (m - k))) = sum (range K) (λ m, sum (range (K - m)) (λ n, a m * b n)), by simpa using sum_range_diag_flip K (λ m n, a m * b n), have h₂ : (λ i, (range (K - i)).sum (λ k, a i * b k)) = (λ i, a i * (range (K - i)).sum b), by simp [finset.mul_sum], have h₃ : (range K).sum (λ i, a i * (range (K - i)).sum b) = (range K).sum (λ i, a i * ((range (K - i)).sum b - (range K).sum b)) + (range K).sum (λ i, a i * (range K).sum b), by rw ← sum_add_distrib; simp [(mul_add _ _ _).symm], have two_mul_two : (4 : α) = 2 * 2, by norm_num, have hQ0 : Q ≠ 0, from λ h, by simpa [h, lt_irrefl] using hQε0, have h2Q0 : 2 * Q ≠ 0, from mul_ne_zero two_ne_zero hQ0, have hε : ε / (2 * P) * P + ε / (4 * Q) * (2 * Q) = ε, by rw [← div_div_eq_div_mul, div_mul_cancel _ (ne.symm (ne_of_lt hP0)), two_mul_two, mul_assoc, ← div_div_eq_div_mul, div_mul_cancel _ h2Q0, add_halves], have hNMK : max N M + 1 < K, from lt_of_lt_of_le (by rw two_mul; exact lt_add_of_pos_left _ (nat.succ_pos _)) hK, have hKN : N < K, from calc N ≤ max N M : le_max_left _ _ ... < max N M + 1 : nat.lt_succ_self _ ... < K : hNMK, have hsumlesum : (range (max N M + 1)).sum (λ i, abv (a i) * abv ((range (K - i)).sum b - (range K).sum b)) ≤ (range (max N M + 1)).sum (λ i, abv (a i) * (ε / (2 * P))), from sum_le_sum (λ m hmJ, mul_le_mul_of_nonneg_left (le_of_lt (hN (K - m) K (nat.le_sub_left_of_add_le (le_trans (by rw two_mul; exact add_le_add (le_of_lt (mem_range.1 hmJ)) (le_trans (le_max_left _ _) (le_of_lt (lt_add_one _)))) hK)) (le_of_lt hKN))) (abv_nonneg abv _)), have hsumltP : sum (range (max N M + 1)) (λ n, abv (a n)) < P := calc sum (range (max N M + 1)) (λ n, abv (a n)) = abs (sum (range (max N M + 1)) (λ n, abv (a n))) : eq.symm (abs_of_nonneg (zero_le_sum (λ x h, abv_nonneg abv (a x)))) ... < P : hP (max N M + 1), begin rw [h₁, h₂, h₃, sum_mul, ← sub_sub, sub_right_comm, sub_self, zero_sub, abv_neg abv], refine lt_of_le_of_lt (abv_sum_le_sum_abv _ _) _, suffices : (range (max N M + 1)).sum (λ (i : ℕ), abv (a i) * abv ((range (K - i)).sum b - (range K).sum b)) + ((range K).sum (λ (i : ℕ), abv (a i) * abv ((range (K - i)).sum b - (range K).sum b)) -(range (max N M + 1)).sum (λ (i : ℕ), abv (a i) * abv ((range (K - i)).sum b - (range K).sum b))) < ε / (2 * P) * P + ε / (4 * Q) * (2 * Q), { rw hε at this, simpa [abv_mul abv] }, refine add_lt_add (lt_of_le_of_lt hsumlesum (by rw [← sum_mul, mul_comm]; exact (mul_lt_mul_left hPε0).mpr hsumltP)) _, rw sum_range_sub_sum_range (le_of_lt hNMK), exact calc sum ((range K).filter (λ k, max N M + 1 ≤ k)) (λ i, abv (a i) * abv (sum (range (K - i)) b - sum (range K) b)) ≤ sum ((range K).filter (λ k, max N M + 1 ≤ k)) (λ i, abv (a i) * (2 * Q)) : sum_le_sum (λ n hn, begin refine mul_le_mul_of_nonneg_left _ (abv_nonneg _ _), rw sub_eq_add_neg, refine le_trans (abv_add _ _ _) _, rw [two_mul, abv_neg abv], exact add_le_add (le_of_lt (hQ _)) (le_of_lt (hQ _)), end) ... < ε / (4 * Q) * (2 * Q) : by rw [← sum_mul, ← sum_range_sub_sum_range (le_of_lt hNMK)]; refine (mul_lt_mul_right $ by rw two_mul; exact add_pos (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0)) (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))).2 (lt_of_le_of_lt (le_abs_self _) (hM _ _ (le_trans (nat.le_succ_of_le (le_max_right _ _)) (le_of_lt hNMK)) (nat.le_succ_of_le (le_max_right _ _)))) end⟩ end open finset open cau_seq namespace complex lemma is_cau_abs_exp (z : ℂ) : is_cau_seq _root_.abs (λ n, (range n).sum (λ m, abs (z ^ m / nat.fact m))) := let ⟨n, hn⟩ := exists_nat_gt (abs z) in have hn0 : (0 : ℝ) < n, from lt_of_le_of_lt (abs_nonneg _) hn, series_ratio_test n (complex.abs z / n) (div_nonneg_of_nonneg_of_pos (complex.abs_nonneg _) hn0) (by rwa [div_lt_iff hn0, one_mul]) (λ m hm, by rw [abs_abs, abs_abs, nat.fact_succ, pow_succ, mul_comm m.succ, nat.cast_mul, ← div_div_eq_div_mul, mul_div_assoc, mul_div_right_comm, abs_mul, abs_div, abs_cast_nat]; exact mul_le_mul_of_nonneg_right (div_le_div_of_le_left (abs_nonneg _) (nat.cast_pos.2 (nat.succ_pos _)) hn0 (nat.cast_le.2 (le_trans hm (nat.le_succ _)))) (abs_nonneg _)) noncomputable theory lemma is_cau_exp (z : ℂ) : is_cau_seq abs (λ n, (range n).sum (λ m, z ^ m / nat.fact m)) := is_cau_series_of_abv_cau (is_cau_abs_exp z) def exp' (z : ℂ) : cau_seq ℂ complex.abs := ⟨λ n, (range n).sum (λ m, z ^ m / nat.fact m), is_cau_exp z⟩ def exp (z : ℂ) : ℂ := lim (exp' z) def sin (z : ℂ) : ℂ := ((exp (-z * I) - exp (z * I)) * I) / 2 def cos (z : ℂ) : ℂ := (exp (z * I) + exp (-z * I)) / 2 def tan (z : ℂ) : ℂ := sin z / cos z def sinh (z : ℂ) : ℂ := (exp z - exp (-z)) / 2 def cosh (z : ℂ) : ℂ := (exp z + exp (-z)) / 2 def tanh (z : ℂ) : ℂ := sinh z / cosh z end complex namespace real open complex def exp (x : ℝ) : ℝ := (exp x).re def sin (x : ℝ) : ℝ := (sin x).re def cos (x : ℝ) : ℝ := (cos x).re def tan (x : ℝ) : ℝ := (tan x).re def sinh (x : ℝ) : ℝ := (sinh x).re def cosh (x : ℝ) : ℝ := (cosh x).re def tanh (x : ℝ) : ℝ := (tanh x).re end real namespace complex variables (x y : ℂ) @[simp] lemma exp_zero : exp 0 = 1 := lim_eq_of_equiv_const $ λ ε ε0, ⟨1, λ j hj, begin convert ε0, cases j, { exact absurd hj (not_le_of_gt zero_lt_one) }, { dsimp [exp'], induction j with j ih, { dsimp [exp']; simp }, { rw ← ih dec_trivial, simp only [sum_range_succ, pow_succ], simp } } end⟩ lemma exp_add : exp (x + y) = exp x * exp y := show lim (⟨_, is_cau_exp (x + y)⟩ : cau_seq ℂ abs) = lim (show cau_seq ℂ abs, from ⟨_, is_cau_exp x⟩) * lim (show cau_seq ℂ abs, from ⟨_, is_cau_exp y⟩), from have hj : ∀ j : ℕ, (range j).sum (λ m, (x + y) ^ m / m.fact) = (range j).sum (λ i, (range (i + 1)).sum (λ k, x ^ k / k.fact * (y ^ (i - k) / (i - k).fact))), from assume j, finset.sum_congr rfl (λ m hm, begin rw [add_pow, div_eq_mul_inv, sum_mul], refine finset.sum_congr rfl (λ i hi, _), have h₁ : (choose m i : ℂ) ≠ 0 := nat.cast_ne_zero.2 (nat.pos_iff_ne_zero.1 (choose_pos (nat.le_of_lt_succ (mem_range.1 hi)))), have h₂ := choose_mul_fact_mul_fact (nat.le_of_lt_succ $ finset.mem_range.1 hi), rw [← h₂, nat.cast_mul, nat.cast_mul, mul_inv', mul_inv'], simp only [mul_left_comm (choose m i : ℂ), mul_assoc, mul_left_comm (choose m i : ℂ)⁻¹, mul_comm (choose m i : ℂ)], rw inv_mul_cancel h₁, simp [div_eq_mul_inv, mul_comm, mul_assoc, mul_left_comm] end), by rw lim_mul_lim; exact eq.symm (lim_eq_lim_of_equiv (by dsimp; simp only [hj]; exact cauchy_product (is_cau_abs_exp x) (is_cau_exp y))) lemma exp_nat_mul (x : ℂ) : ∀ n : ℕ, exp(n*x) = (exp x)^n | 0 := by rw [nat.cast_zero, zero_mul, exp_zero, pow_zero] | (nat.succ n) := by rw [pow_succ', nat.cast_add_one, add_mul, exp_add, ←exp_nat_mul, one_mul] lemma exp_ne_zero : exp x ≠ 0 := λ h, @zero_ne_one ℂ _ $ by rw [← exp_zero, ← add_neg_self x, exp_add, h]; simp lemma exp_neg : exp (-x) = (exp x)⁻¹ := by rw [← domain.mul_left_inj (exp_ne_zero x), ← exp_add]; simp [mul_inv_cancel (exp_ne_zero x)] lemma exp_sub : exp (x - y) = exp x / exp y := by simp [exp_add, exp_neg, div_eq_mul_inv] @[simp] lemma exp_conj : exp (conj x) = conj (exp x) := begin dsimp [exp], rw [← lim_conj], refine congr_arg lim (cau_seq.ext (λ _, _)), dsimp [exp', function.comp, cau_seq_conj], rw ← sum_hom conj, refine sum_congr rfl (λ n hn, _), rw [conj_div, conj_pow, ← of_real_nat_cast, conj_of_real] end @[simp] lemma exp_of_real_im (x : ℝ) : (exp x).im = 0 := let ⟨r, hr⟩ := (eq_conj_iff_real (exp x)).1 (by rw [← exp_conj, conj_of_real]) in by rw [hr, of_real_im] lemma exp_of_real_re (x : ℝ) : (exp x).re = real.exp x := rfl @[simp] lemma of_real_exp_of_real_re (x : ℝ) : ((exp x).re : ℂ) = exp x := complex.ext (by simp) (by simp) @[simp] lemma of_real_exp (x : ℝ) : (real.exp x : ℂ) = exp x := complex.ext (by simp [real.exp]) (by simp [real.exp]) @[simp] lemma sin_zero : sin 0 = 0 := by simp [sin] @[simp] lemma sin_neg : sin (-x) = -sin x := by simp [sin, exp_neg, (neg_div _ _).symm, add_mul] lemma sin_add : sin (x + y) = sin x * cos y + cos x * sin y := begin rw [← domain.mul_left_inj (@two_ne_zero' ℂ _ _ _), ← domain.mul_left_inj (@two_ne_zero' ℂ _ _ _)], simp only [mul_add, add_mul, exp_add, div_mul_div, div_add_div_same, mul_assoc, (div_div_eq_div_mul _ _ _).symm, mul_div_cancel' _ (@two_ne_zero' ℂ _ _ _), sin, cos], simp [mul_add, add_mul, exp_add], ring end @[simp] lemma cos_zero : cos 0 = 1 := by simp [cos] @[simp] lemma cos_neg : cos (-x) = cos x := by simp [cos, exp_neg] lemma cos_add : cos (x + y) = cos x * cos y - sin x * sin y := begin rw [← domain.mul_left_inj (@two_ne_zero' ℂ _ _ _), ← domain.mul_left_inj (@two_ne_zero' ℂ _ _ _)], simp only [mul_add, add_mul, mul_sub, sub_mul, exp_add, div_mul_div, div_add_div_same, mul_assoc, (div_div_eq_div_mul _ _ _).symm, mul_div_cancel' _ (@two_ne_zero' ℂ _ _ _), sin, cos], apply complex.ext; simp [mul_add, add_mul, exp_add]; ring end lemma sin_sub : sin (x - y) = sin x * cos y - cos x * sin y := by simp [sin_add, sin_neg, cos_neg] lemma cos_sub : cos (x - y) = cos x * cos y + sin x * sin y := by simp [cos_add, sin_neg, cos_neg] lemma sin_conj : sin (conj x) = conj (sin x) := begin rw [sin, ← conj_neg_I, ← conj_mul, ← conj_neg, ← conj_mul, exp_conj, exp_conj, ← conj_sub, sin, conj_div, conj_two, ← domain.mul_left_inj (@two_ne_zero' ℂ _ _ _), mul_div_cancel' _ (@two_ne_zero' ℂ _ _ _), mul_div_cancel' _ (@two_ne_zero' ℂ _ _ _)], apply complex.ext; simp [sin, neg_add], end @[simp] lemma sin_of_real_im (x : ℝ) : (sin x).im = 0 := let ⟨r, hr⟩ := (eq_conj_iff_real (sin x)).1 (by rw [← sin_conj, conj_of_real]) in by rw [hr, of_real_im] lemma sin_of_real_re (x : ℝ) : (sin x).re = real.sin x := rfl @[simp] lemma of_real_sin_of_real_re (x : ℝ) : ((sin x).re : ℂ) = sin x := by apply complex.ext; simp @[simp] lemma of_real_sin (x : ℝ) : (real.sin x : ℂ) = sin x := by simp [real.sin] lemma cos_conj : cos (conj x) = conj (cos x) := begin rw [cos, ← conj_neg_I, ← conj_mul, ← conj_neg, ← conj_mul, exp_conj, exp_conj, cos, conj_div, conj_two, ← domain.mul_left_inj (@two_ne_zero' ℂ _ _ _), mul_div_cancel' _ (@two_ne_zero' ℂ _ _ _), mul_div_cancel' _ (@two_ne_zero' ℂ _ _ _)], apply complex.ext; simp end @[simp] lemma cos_of_real_im (x : ℝ) : (cos x).im = 0 := let ⟨r, hr⟩ := (eq_conj_iff_real (cos x)).1 (by rw [← cos_conj, conj_of_real]) in by rw [hr, of_real_im] lemma cos_of_real_re (x : ℝ) : (cos x).re = real.cos x := rfl @[simp] lemma of_real_cos_of_real_re (x : ℝ) : ((cos x).re : ℂ) = cos x := by apply complex.ext; simp @[simp] lemma of_real_cos (x : ℝ) : (real.cos x : ℂ) = cos x := by simp [real.cos, -cos_of_real_re] @[simp] lemma tan_zero : tan 0 = 0 := by simp [tan] lemma tan_eq_sin_div_cos : tan x = sin x / cos x := rfl @[simp] lemma tan_neg : tan (-x) = -tan x := by simp [tan, neg_div] lemma tan_conj : tan (conj x) = conj (tan x) := by rw [tan, sin_conj, cos_conj, ← conj_div, tan] @[simp] lemma tan_of_real_im (x : ℝ) : (tan x).im = 0 := let ⟨r, hr⟩ := (eq_conj_iff_real (tan x)).1 (by rw [← tan_conj, conj_of_real]) in by rw [hr, of_real_im] lemma tan_of_real_re (x : ℝ) : (tan x).re = real.tan x := rfl @[simp] lemma of_real_tan_of_real_re (x : ℝ) : ((tan x).re : ℂ) = tan x := by apply complex.ext; simp @[simp] lemma of_real_tan (x : ℝ) : (real.tan x : ℂ) = tan x := by simp [real.tan, -tan_of_real_re] lemma sin_pow_two_add_cos_pow_two : sin x ^ 2 + cos x ^ 2 = 1 := begin simp only [pow_two, mul_sub, sub_mul, mul_add, add_mul, div_eq_mul_inv, neg_mul_eq_neg_mul_symm, exp_neg, mul_comm (exp _), mul_left_comm (exp _), mul_assoc, mul_left_comm (exp _)⁻¹, inv_mul_cancel (exp_ne_zero _), mul_inv', mul_one, one_mul, sin, cos], apply complex.ext; simp [norm_sq]; ring end lemma cos_two_mul : cos (2 * x) = 2 * cos x ^ 2 - 1 := by rw [two_mul, cos_add, ← pow_two, ← pow_two, eq_sub_iff_add_eq.2 (sin_pow_two_add_cos_pow_two x)]; simp [two_mul] lemma sin_two_mul : sin (2 * x) = 2 * sin x * cos x := by rw [two_mul, sin_add, two_mul, add_mul, mul_comm] lemma exp_mul_I : exp (x * I) = cos x + sin x * I := by rw [cos, sin, mul_comm (_ / 2) I, ← mul_div_assoc, mul_left_comm I, I_mul_I, ← add_div]; simp lemma exp_add_mul_I : exp (x + y * I) = exp x * (cos y + sin y * I) := by rw [exp_add, exp_mul_I] lemma exp_eq_exp_re_mul_sin_add_cos : exp x = exp x.re * (cos x.im + sin x.im * I) := by rw [← exp_add_mul_I, re_add_im] theorem cos_add_sin_mul_I_pow (n : ℕ) (z : ℂ) : (cos z + sin z * I) ^ n = cos (↑n * z) + sin (↑n * z) * I := begin rw [← exp_mul_I, ← exp_mul_I], induction n with n ih, { rw [pow_zero, nat.cast_zero, zero_mul, zero_mul, exp_zero] }, { rw [pow_succ', ih, nat.cast_succ, add_mul, add_mul, one_mul, exp_add] } end @[simp] lemma sinh_zero : sinh 0 = 0 := by simp [sinh] @[simp] lemma sinh_neg : sinh (-x) = -sinh x := by simp [sinh, exp_neg, (neg_div _ _).symm, add_mul] lemma sinh_add : sinh (x + y) = sinh x * cosh y + cosh x * sinh y := begin rw [← domain.mul_left_inj (@two_ne_zero' ℂ _ _ _), ← domain.mul_left_inj (@two_ne_zero' ℂ _ _ _)], simp only [mul_add, add_mul, exp_add, div_mul_div, div_add_div_same, mul_assoc, (div_div_eq_div_mul _ _ _).symm, mul_div_cancel' _ (@two_ne_zero' ℂ _ _ _), sinh, cosh], simp [mul_add, add_mul, exp_add], ring end @[simp] lemma cosh_zero : cosh 0 = 1 := by simp [cosh] @[simp] lemma cosh_neg : cosh (-x) = cosh x := by simp [cosh, exp_neg] lemma cosh_add : cosh (x + y) = cosh x * cosh y + sinh x * sinh y := begin rw [← domain.mul_left_inj (@two_ne_zero' ℂ _ _ _), ← domain.mul_left_inj (@two_ne_zero' ℂ _ _ _)], simp only [mul_add, add_mul, mul_sub, sub_mul, exp_add, div_mul_div, div_add_div_same, mul_assoc, (div_div_eq_div_mul _ _ _).symm, mul_div_cancel' _ (@two_ne_zero' ℂ _ _ _), sinh, cosh], apply complex.ext; simp [mul_add, add_mul, exp_add]; ring end lemma sinh_sub : sinh (x - y) = sinh x * cosh y - cosh x * sinh y := by simp [sinh_add, sinh_neg, cosh_neg] lemma cosh_sub : cosh (x - y) = cosh x * cosh y - sinh x * sinh y := by simp [cosh_add, sinh_neg, cosh_neg] lemma sinh_conj : sinh (conj x) = conj (sinh x) := by rw [sinh, ← conj_neg, exp_conj, exp_conj, ← conj_sub, sinh, conj_div, conj_two] @[simp] lemma sinh_of_real_im (x : ℝ) : (sinh x).im = 0 := let ⟨r, hr⟩ := (eq_conj_iff_real (sinh x)).1 (by rw [← sinh_conj, conj_of_real]) in by rw [hr, of_real_im] lemma sinh_of_real_re (x : ℝ) : (sinh x).re = real.sinh x := rfl @[simp] lemma of_real_sinh_of_real_re (x : ℝ) : ((sinh x).re : ℂ) = sinh x := by apply complex.ext; simp @[simp] lemma of_real_sinh (x : ℝ) : (real.sinh x : ℂ) = sinh x := by simp [real.sinh] lemma cosh_conj : cosh (conj x) = conj (cosh x) := by rw [cosh, ← conj_neg, exp_conj, exp_conj, ← conj_add, cosh, conj_div, conj_two] @[simp] lemma cosh_of_real_im (x : ℝ) : (cosh x).im = 0 := let ⟨r, hr⟩ := (eq_conj_iff_real (cosh x)).1 (by rw [← cosh_conj, conj_of_real]) in by rw [hr, of_real_im] lemma cosh_of_real_re (x : ℝ) : (cosh x).re = real.cosh x := rfl @[simp] lemma of_real_cosh_of_real_re (x : ℝ) : ((cosh x).re : ℂ) = cosh x := by apply complex.ext; simp @[simp] lemma of_real_cosh (x : ℝ) : (real.cosh x : ℂ) = cosh x := by simp [real.cosh] lemma tanh_eq_sinh_div_cosh : tanh x = sinh x / cosh x := rfl @[simp] lemma tanh_zero : tanh 0 = 0 := by simp [tanh] @[simp] lemma tanh_neg : tanh (-x) = -tanh x := by simp [tanh, neg_div] lemma tanh_conj : tanh (conj x) = conj (tanh x) := by rw [tanh, sinh_conj, cosh_conj, ← conj_div, tanh] @[simp] lemma tanh_of_real_im (x : ℝ) : (tanh x).im = 0 := let ⟨r, hr⟩ := (eq_conj_iff_real (tanh x)).1 (by rw [← tanh_conj, conj_of_real]) in by rw [hr, of_real_im] lemma tanh_of_real_re (x : ℝ) : (tanh x).re = real.tanh x := rfl @[simp] lemma of_real_tanh_of_real_re (x : ℝ) : ((tanh x).re : ℂ) = tanh x := by apply complex.ext; simp @[simp] lemma of_real_tanh (x : ℝ) : (real.tanh x : ℂ) = tanh x := by simp [real.tanh] end complex namespace real open complex variables (x y : ℝ) @[simp] lemma exp_zero : exp 0 = 1 := by simp [real.exp] lemma exp_add : exp (x + y) = exp x * exp y := by simp [exp_add, exp] lemma exp_nat_mul (x : ℝ) : ∀ n : ℕ, exp(n*x) = (exp x)^n | 0 := by rw [nat.cast_zero, zero_mul, exp_zero, pow_zero] | (nat.succ n) := by rw [pow_succ', nat.cast_add_one, add_mul, exp_add, ←exp_nat_mul, one_mul] lemma exp_ne_zero : exp x ≠ 0 := λ h, exp_ne_zero x $ by rw [exp, ← of_real_inj] at h; simp * at * lemma exp_neg : exp (-x) = (exp x)⁻¹ := by rw [← of_real_inj, exp, of_real_exp_of_real_re, of_real_neg, exp_neg, of_real_inv, of_real_exp] lemma exp_sub : exp (x - y) = exp x / exp y := by simp [exp_add, exp_neg, div_eq_mul_inv] @[simp] lemma sin_zero : sin 0 = 0 := by simp [sin] @[simp] lemma sin_neg : sin (-x) = -sin x := by simp [sin, exp_neg, (neg_div _ _).symm, add_mul] lemma sin_add : sin (x + y) = sin x * cos y + cos x * sin y := by rw [← of_real_inj]; simp [sin, sin_add] @[simp] lemma cos_zero : cos 0 = 1 := by simp [cos] @[simp] lemma cos_neg : cos (-x) = cos x := by simp [cos, exp_neg] lemma cos_add : cos (x + y) = cos x * cos y - sin x * sin y := by rw ← of_real_inj; simp [cos, cos_add] lemma sin_sub : sin (x - y) = sin x * cos y - cos x * sin y := by simp [sin_add, sin_neg, cos_neg] lemma cos_sub : cos (x - y) = cos x * cos y + sin x * sin y := by simp [cos_add, sin_neg, cos_neg] lemma tan_eq_sin_div_cos : tan x = sin x / cos x := if h : complex.cos x = 0 then by simp [sin, cos, tan, *, complex.tan, div_eq_mul_inv] at * else by rw [sin, cos, tan, complex.tan, ← of_real_inj, div_eq_mul_inv, mul_re]; simp [norm_sq, (div_div_eq_div_mul _ _ _).symm, div_self h]; refl @[simp] lemma tan_zero : tan 0 = 0 := by simp [tan] @[simp] lemma tan_neg : tan (-x) = -tan x := by simp [tan, neg_div] lemma sin_pow_two_add_cos_pow_two : sin x ^ 2 + cos x ^ 2 = 1 := by rw ← of_real_inj; simpa [sin, of_real_pow] using sin_pow_two_add_cos_pow_two x lemma abs_sin_le_one : abs' (sin x) ≤ 1 := not_lt.1 $ λ h, lt_irrefl (1 * 1 : ℝ) (calc 1 * 1 < abs' (sin x) * abs' (sin x) : mul_lt_mul h (le_of_lt h) zero_lt_one (le_trans zero_le_one (le_of_lt h)) ... = sin x ^ 2 : by rw [← _root_.abs_mul, abs_mul_self, pow_two] ... ≤ sin x ^ 2 + cos x ^ 2 : le_add_of_nonneg_right (pow_two_nonneg _) ... = 1 * 1 : by rw [sin_pow_two_add_cos_pow_two, one_mul]) lemma abs_cos_le_one : abs' (cos x) ≤ 1 := not_lt.1 $ λ h, lt_irrefl (1 * 1 : ℝ) (calc 1 * 1 < abs' (cos x) * abs' (cos x) : mul_lt_mul h (le_of_lt h) zero_lt_one (le_trans zero_le_one (le_of_lt h)) ... = cos x ^ 2 : by rw [← _root_.abs_mul, abs_mul_self, pow_two] ... ≤ sin x ^ 2 + cos x ^ 2 : le_add_of_nonneg_left (pow_two_nonneg _) ... = 1 * 1 : by rw [sin_pow_two_add_cos_pow_two, one_mul]) lemma sin_le_one : sin x ≤ 1 := (abs_le.1 (abs_sin_le_one _)).2 lemma cos_le_one : cos x ≤ 1 := (abs_le.1 (abs_cos_le_one _)).2 lemma neg_one_le_sin : -1 ≤ sin x := (abs_le.1 (abs_sin_le_one _)).1 lemma neg_one_le_cos : -1 ≤ cos x := (abs_le.1 (abs_cos_le_one _)).1 lemma sin_pow_two_le_one : sin x ^ 2 ≤ 1 := by rw [pow_two, ← abs_mul_self, _root_.abs_mul]; exact mul_le_one (abs_sin_le_one _) (abs_nonneg _) (abs_sin_le_one _) lemma cos_pow_two_le_one : cos x ^ 2 ≤ 1 := by rw [pow_two, ← abs_mul_self, _root_.abs_mul]; exact mul_le_one (abs_cos_le_one _) (abs_nonneg _) (abs_cos_le_one _) lemma cos_two_mul : cos (2 * x) = 2 * cos x ^ 2 - 1 := by rw ← of_real_inj; simp [cos_two_mul, cos, pow_two] lemma sin_two_mul : sin (2 * x) = 2 * sin x * cos x := by rw ← of_real_inj; simp [sin_two_mul, sin, pow_two] @[simp] lemma sinh_zero : sinh 0 = 0 := by simp [sinh] @[simp] lemma sinh_neg : sinh (-x) = -sinh x := by simp [sinh, exp_neg, (neg_div _ _).symm, add_mul] lemma sinh_add : sinh (x + y) = sinh x * cosh y + cosh x * sinh y := by rw ← of_real_inj; simp [sinh, sinh_add] @[simp] lemma cosh_zero : cosh 0 = 1 := by simp [cosh] @[simp] lemma cosh_neg : cosh (-x) = cosh x := by simp [cosh, exp_neg] lemma cosh_add : cosh (x + y) = cosh x * cosh y + sinh x * sinh y := by rw ← of_real_inj; simp [cosh, cosh_add] lemma sinh_sub : sinh (x - y) = sinh x * cosh y - cosh x * sinh y := by simp [sinh_add, sinh_neg, cosh_neg] lemma cosh_sub : cosh (x - y) = cosh x * cosh y - sinh x * sinh y := by simp [cosh_add, sinh_neg, cosh_neg] lemma tanh_eq_sinh_div_cosh : tanh x = sinh x / cosh x := if h : complex.cosh x = 0 then by simp [sinh, cosh, tanh, *, complex.tanh, div_eq_mul_inv] at * else by rw [sinh, cosh, tanh, complex.tanh, ← of_real_inj, div_eq_mul_inv, mul_re]; simp [norm_sq, (div_div_eq_div_mul _ _ _).symm, div_self h]; refl @[simp] lemma tanh_zero : tanh 0 = 0 := by simp [tanh] @[simp] lemma tanh_neg : tanh (-x) = -tanh x := by simp [tanh, neg_div] open is_absolute_value /- TODO make this private and prove ∀ x -/ lemma add_one_le_exp_of_nonneg {x : ℝ} (hx : 0 ≤ x) : x + 1 ≤ exp x := calc x + 1 ≤ lim (⟨(λ n : ℕ, ((exp' x) n).re), is_cau_seq_re (exp' x)⟩ : cau_seq ℝ abs') : le_lim (cau_seq.le_of_exists ⟨2, λ j hj, show x + (1 : ℝ) ≤ ((range j).sum (λ m, (x ^ m / m.fact : ℂ))).re, from have h₁ : (((λ m : ℕ, (x ^ m / m.fact : ℂ)) ∘ nat.succ) 0).re = x, by simp, have h₂ : ((x : ℂ) ^ 0 / nat.fact 0).re = 1, by simp, begin rw [← nat.sub_add_cancel hj, sum_range_succ', sum_range_succ', add_re, add_re, h₁, h₂, add_assoc, ← @sum_hom _ _ _ _ _ _ _ complex.re (is_add_group_hom.to_is_add_monoid_hom _)], refine le_add_of_nonneg_of_le (zero_le_sum (λ m hm, _)) (le_refl _), dsimp [-nat.fact_succ], rw [← of_real_pow, ← of_real_nat_cast, ← of_real_div, of_real_re], exact div_nonneg (pow_nonneg hx _) (nat.cast_pos.2 (nat.fact_pos _)), end⟩) ... = exp x : by rw [exp, complex.exp, ← cau_seq_re, lim_re] lemma one_le_exp {x : ℝ} (hx : 0 ≤ x) : 1 ≤ exp x := by linarith using [add_one_le_exp_of_nonneg hx] lemma exp_pos (x : ℝ) : 0 < exp x := (le_total 0 x).elim (lt_of_lt_of_le zero_lt_one ∘ one_le_exp) (λ h, by rw [← neg_neg x, real.exp_neg]; exact inv_pos (lt_of_lt_of_le zero_lt_one (one_le_exp (neg_nonneg.2 h)))) @[simp] lemma abs_exp (x : ℝ) : abs' (exp x) = exp x := abs_of_nonneg (le_of_lt (exp_pos _)) lemma exp_le_exp {x y : ℝ} (h : x ≤ y) : exp x ≤ exp y := by rw [← sub_add_cancel y x, real.exp_add]; exact (le_mul_iff_one_le_left (exp_pos _)).2 (one_le_exp (sub_nonneg.2 h)) lemma exp_lt_exp {x y : ℝ} (h : x < y) : exp x < exp y := by rw [← sub_add_cancel y x, real.exp_add]; exact (lt_mul_iff_one_lt_left (exp_pos _)).2 (lt_of_lt_of_le (by linarith) (add_one_le_exp_of_nonneg (by linarith))) lemma exp_injective : function.injective exp := λ x y h, begin rcases lt_trichotomy x y with h₁ | h₁ | h₁, { exact absurd h (ne_of_lt (exp_lt_exp h₁)) }, { exact h₁ }, { exact absurd h (ne.symm (ne_of_lt (exp_lt_exp h₁))) } end @[simp] lemma exp_eq_one_iff : exp x = 1 ↔ x = 0 := ⟨by rw ← exp_zero; exact λ h, exp_injective h, λ h, by rw [h, exp_zero]⟩ end real namespace complex lemma sum_div_fact_le {α : Type*} [discrete_linear_ordered_field α] (n j : ℕ) (hn : 0 < n) : (sum (filter (λ k, n ≤ k) (range j)) (λ m : ℕ, (1 / m.fact : α))) ≤ n.succ * (n.fact * n)⁻¹ := calc (filter (λ k, n ≤ k) (range j)).sum (λ m : ℕ, (1 / m.fact : α)) = (range (j - n)).sum (λ m, 1 / (m + n).fact) : sum_bij (λ m _, m - n) (λ m hm, mem_range.2 $ (nat.sub_lt_sub_right_iff (by simp at hm; tauto)).2 (by simp at hm; tauto)) (λ m hm, by rw nat.sub_add_cancel; simp at *; tauto) (λ a₁ a₂ ha₁ ha₂ h, by rwa [nat.sub_eq_iff_eq_add, ← nat.sub_add_comm, eq_comm, nat.sub_eq_iff_eq_add, add_right_inj, eq_comm] at h; simp at *; tauto) (λ b hb, ⟨b + n, mem_filter.2 ⟨mem_range.2 $ nat.add_lt_of_lt_sub_right (mem_range.1 hb), nat.le_add_left _ _⟩, by rw nat.add_sub_cancel⟩) ... ≤ (range (j - n)).sum (λ m, (nat.fact n * n.succ ^ m)⁻¹) : begin refine sum_le_sum (assume m n, _), rw [one_div_eq_inv, inv_le_inv], { rw [← nat.cast_pow, ← nat.cast_mul, nat.cast_le, add_comm], exact nat.fact_mul_pow_le_fact }, { exact nat.cast_pos.2 (nat.fact_pos _) }, { exact mul_pos (nat.cast_pos.2 (nat.fact_pos _)) (pow_pos (nat.cast_pos.2 (nat.succ_pos _)) _) }, end ... = (nat.fact n)⁻¹ * (range (j - n)).sum (λ m, n.succ⁻¹ ^ m) : by simp [mul_inv', mul_sum.symm, sum_mul.symm, -nat.fact_succ, mul_comm, inv_pow'] ... = (n.succ - n.succ * n.succ⁻¹ ^ (j - n)) / (n.fact * n) : have h₁ : (n.succ : α) ≠ 1, from @nat.cast_one α _ _ ▸ mt nat.cast_inj.1 (mt nat.succ_inj (nat.pos_iff_ne_zero.1 hn)), have h₂ : (n.succ : α) ≠ 0, from nat.cast_ne_zero.2 (nat.succ_ne_zero _), have h₃ : (n.fact * n : α) ≠ 0, from mul_ne_zero (nat.cast_ne_zero.2 (nat.pos_iff_ne_zero.1 (nat.fact_pos _))) (nat.cast_ne_zero.2 (nat.pos_iff_ne_zero.1 hn)), have h₄ : (n.succ - 1 : α) = n, by simp, by rw [geom_sum_inv h₁ h₂, eq_div_iff_mul_eq _ _ h₃, mul_comm _ (n.fact * n : α), ← mul_assoc (n.fact⁻¹ : α), ← mul_inv', h₄, ← mul_assoc (n.fact * n : α), mul_comm (n : α) n.fact, mul_inv_cancel h₃]; simp [mul_add, add_mul, mul_assoc, mul_comm] ... ≤ n.succ / (n.fact * n) : begin refine (div_le_div_right (mul_pos _ _)).2 _, exact nat.cast_pos.2 (nat.fact_pos _), exact nat.cast_pos.2 hn, exact sub_le_self _ (mul_nonneg (nat.cast_nonneg _) (pow_nonneg (inv_nonneg.2 (nat.cast_nonneg _)) _)) end lemma exp_bound {x : ℂ} (hx : abs x ≤ 1) {n : ℕ} (hn : 0 < n) : abs (exp x - (range n).sum (λ m, x ^ m / m.fact)) ≤ abs x ^ n * (n.succ * (n.fact * n)⁻¹) := begin rw [← lim_const ((range n).sum _), exp, sub_eq_add_neg, ← lim_neg, lim_add, ← lim_abs], refine lim_le (cau_seq.le_of_exists ⟨n, λ j hj, _⟩), show abs ((range j).sum (λ m, x ^ m / m.fact) - (range n).sum (λ m, x ^ m / m.fact)) ≤ abs x ^ n * (n.succ * (n.fact * n)⁻¹), rw sum_range_sub_sum_range hj, exact calc abs (((range j).filter (λ k, n ≤ k)).sum (λ m : ℕ, (x ^ m / m.fact : ℂ))) = abs (((range j).filter (λ k, n ≤ k)).sum (λ m : ℕ, (x ^ n * (x ^ (m - n) / m.fact) : ℂ))) : congr_arg abs (sum_congr rfl (λ m hm, by rw [← mul_div_assoc, ← pow_add, nat.add_sub_cancel']; simp at hm; tauto)) ... ≤ sum (filter (λ k, n ≤ k) (range j)) (λ m, abs (x ^ n * (_ / m.fact))) : abv_sum_le_sum_abv _ _ ... ≤ sum (filter (λ k, n ≤ k) (range j)) (λ m, abs x ^ n * (1 / m.fact)) : begin refine sum_le_sum (λ m hm, _), rw [abs_mul, abv_pow abs, abs_div, abs_cast_nat], refine mul_le_mul_of_nonneg_left ((div_le_div_right _).2 _) _, exact nat.cast_pos.2 (nat.fact_pos _), rw abv_pow abs, exact (pow_le_one _ (abs_nonneg _) hx), exact pow_nonneg (abs_nonneg _) _ end ... = abs x ^ n * (((range j).filter (λ k, n ≤ k)).sum (λ m : ℕ, (1 / m.fact : ℝ))) : by simp [abs_mul, abv_pow abs, abs_div, mul_sum.symm] ... ≤ abs x ^ n * (n.succ * (n.fact * n)⁻¹) : mul_le_mul_of_nonneg_left (sum_div_fact_le _ _ hn) (pow_nonneg (abs_nonneg _) _) end lemma abs_exp_sub_one_le {x : ℂ} (hx : abs x ≤ 1) : abs (exp x - 1) ≤ 2 * abs x := calc abs (exp x - 1) = abs (exp x - (range 1).sum (λ m, x ^ m / m.fact)) : by simp [sum_range_succ] ... ≤ abs x ^ 1 * ((nat.succ 1) * (nat.fact 1 * (1 : ℕ))⁻¹) : exp_bound hx dec_trivial ... = 2 * abs x : by simp [two_mul, mul_two, mul_add, mul_comm] end complex namespace real open complex finset lemma cos_bound {x : ℝ} (hx : abs' x ≤ 1) : abs' (cos x - (1 - x ^ 2 / 2)) ≤ abs' x ^ 4 * (5 / 96) := calc abs' (cos x - (1 - x ^ 2 / 2)) = abs (complex.cos x - (1 - x ^ 2 / 2)) : by rw ← abs_of_real; simp [of_real_bit0, of_real_one, of_real_inv] ... = abs ((complex.exp (x * I) + complex.exp (-x * I) - (2 - x ^ 2)) / 2) : by simp [complex.cos, sub_div, add_div, neg_div, div_self (@two_ne_zero' ℂ _ _ _)] ... = abs (((complex.exp (x * I) - (range 4).sum (λ m, (x * I) ^ m / m.fact)) + ((complex.exp (-x * I) - (range 4).sum (λ m, (-x * I) ^ m / m.fact)))) / 2) : congr_arg abs (congr_arg (λ x : ℂ, x / 2) begin simp only [sum_range_succ], simp [pow_succ], apply complex.ext; simp [div_eq_mul_inv, norm_sq]; ring end) ... ≤ abs ((complex.exp (x * I) - (range 4).sum (λ m, (x * I) ^ m / m.fact)) / 2) + abs ((complex.exp (-x * I) - (range 4).sum (λ m, (-x * I) ^ m / m.fact)) / 2) : by rw add_div; exact abs_add _ _ ... = (abs ((complex.exp (x * I) - (range 4).sum (λ m, (x * I) ^ m / m.fact))) / 2 + abs ((complex.exp (-x * I) - (range 4).sum (λ m, (-x * I) ^ m / m.fact))) / 2) : by simp [complex.abs_div] ... ≤ ((complex.abs (x * I) ^ 4 * (nat.succ 4 * (nat.fact 4 * (4 : ℕ))⁻¹)) / 2 + (complex.abs (-x * I) ^ 4 * (nat.succ 4 * (nat.fact 4 * (4 : ℕ))⁻¹)) / 2) : add_le_add ((div_le_div_right (by norm_num)).2 (exp_bound (by simpa) dec_trivial)) ((div_le_div_right (by norm_num)).2 (exp_bound (by simpa) dec_trivial)) ... ≤ abs' x ^ 4 * (5 / 96) : by norm_num; simp [mul_assoc, mul_comm, mul_left_comm, mul_div_assoc] lemma sin_bound {x : ℝ} (hx : abs' x ≤ 1) : abs' (sin x - (x - x ^ 3 / 6)) ≤ abs' x ^ 4 * (5 / 96) := calc abs' (sin x - (x - x ^ 3 / 6)) = abs (complex.sin x - (x - x ^ 3 / 6)) : by rw ← abs_of_real; simp [of_real_bit0, of_real_one, of_real_inv] ... = abs (((complex.exp (-x * I) - complex.exp (x * I)) * I - (2 * x - x ^ 3 / 3)) / 2) : by simp [complex.sin, sub_div, add_div, neg_div, mul_div_cancel_left _ (@two_ne_zero' ℂ _ _ _), div_div_eq_div_mul, show (3 : ℂ) * 2 = 6, by norm_num] ... = abs ((((complex.exp (-x * I) - (range 4).sum (λ m, (-x * I) ^ m / m.fact)) - (complex.exp (x * I) - (range 4).sum (λ m, (x * I) ^ m / m.fact))) * I) / 2) : congr_arg abs (congr_arg (λ x : ℂ, x / 2) begin simp only [sum_range_succ], simp [pow_succ], apply complex.ext; simp [div_eq_mul_inv, norm_sq]; ring end) ... ≤ abs ((complex.exp (-x * I) - (range 4).sum (λ m, (-x * I) ^ m / m.fact)) * I / 2) + abs (-((complex.exp (x * I) - (range 4).sum (λ m, (x * I) ^ m / m.fact)) * I) / 2) : by rw [sub_mul, sub_eq_add_neg, add_div]; exact abs_add _ _ ... = (abs ((complex.exp (x * I) - (range 4).sum (λ m, (x * I) ^ m / m.fact))) / 2 + abs ((complex.exp (-x * I) - (range 4).sum (λ m, (-x * I) ^ m / m.fact))) / 2) : by simp [complex.abs_div, complex.abs_mul] ... ≤ ((complex.abs (x * I) ^ 4 * (nat.succ 4 * (nat.fact 4 * (4 : ℕ))⁻¹)) / 2 + (complex.abs (-x * I) ^ 4 * (nat.succ 4 * (nat.fact 4 * (4 : ℕ))⁻¹)) / 2) : add_le_add ((div_le_div_right (by norm_num)).2 (exp_bound (by simpa) dec_trivial)) ((div_le_div_right (by norm_num)).2 (exp_bound (by simpa) dec_trivial)) ... ≤ abs' x ^ 4 * (5 / 96) : by norm_num; simp [mul_assoc, mul_comm, mul_left_comm, mul_div_assoc] lemma cos_pos_of_le_one {x : ℝ} (hx : abs' x ≤ 1) : 0 < cos x := calc 0 < (1 - x ^ 2 / 2) - abs' x ^ 4 * (5 / 96) : sub_pos.2 $ lt_sub_iff_add_lt.2 (calc abs' x ^ 4 * (5 / 96) + x ^ 2 / 2 ≤ 1 * (5 / 96) + 1 / 2 : add_le_add (mul_le_mul_of_nonneg_right (pow_le_one _ (abs_nonneg _) hx) (by norm_num)) ((div_le_div_right (by norm_num)).2 (by rw [pow_two, ← abs_mul_self, _root_.abs_mul]; exact mul_le_one hx (abs_nonneg _) hx)) ... < 1 : by norm_num) ... ≤ cos x : sub_le.1 (abs_sub_le_iff.1 (cos_bound hx)).2 lemma sin_pos_of_pos_of_le_one {x : ℝ} (hx0 : 0 < x) (hx : x ≤ 1) : 0 < sin x := calc 0 < x - x ^ 3 / 6 - abs' x ^ 4 * (5 / 96) : sub_pos.2 $ lt_sub_iff_add_lt.2 (calc abs' x ^ 4 * (5 / 96) + x ^ 3 / 6 ≤ x * (5 / 96) + x / 6 : add_le_add (mul_le_mul_of_nonneg_right (calc abs' x ^ 4 ≤ abs' x ^ 1 : pow_le_pow_of_le_one (abs_nonneg _) (by rwa _root_.abs_of_nonneg (le_of_lt hx0)) dec_trivial ... = x : by simp [_root_.abs_of_nonneg (le_of_lt (hx0))]) (by norm_num)) ((div_le_div_right (by norm_num)).2 (calc x ^ 3 ≤ x ^ 1 : pow_le_pow_of_le_one (le_of_lt hx0) hx dec_trivial ... = x : pow_one _)) ... < x : by linarith) ... ≤ sin x : sub_le.1 (abs_sub_le_iff.1 (sin_bound (by rwa [_root_.abs_of_nonneg (le_of_lt hx0)]))).2 lemma sin_pos_of_pos_of_le_two {x : ℝ} (hx0 : 0 < x) (hx : x ≤ 2) : 0 < sin x := have x / 2 ≤ 1, from div_le_of_le_mul (by norm_num) (by simpa), calc 0 < 2 * sin (x / 2) * cos (x / 2) : mul_pos (mul_pos (by norm_num) (sin_pos_of_pos_of_le_one (half_pos hx0) this)) (cos_pos_of_le_one (by rwa [_root_.abs_of_nonneg (le_of_lt (half_pos hx0))])) ... = sin x : by rw [← sin_two_mul, two_mul, add_halves] lemma cos_one_le : cos 1 ≤ 2 / 3 := calc cos 1 ≤ abs' (1 : ℝ) ^ 4 * (5 / 96) + (1 - 1 ^ 2 / 2) : sub_le_iff_le_add.1 (abs_sub_le_iff.1 (cos_bound (by simp))).1 ... ≤ 2 / 3 : by norm_num lemma cos_one_pos : 0 < cos 1 := cos_pos_of_le_one (by simp) lemma cos_two_neg : cos 2 < 0 := calc cos 2 = cos (2 * 1) : congr_arg cos (mul_one _).symm ... = _ : real.cos_two_mul 1 ... ≤ 2 * (2 / 3) ^ 2 - 1 : sub_le_sub_right (mul_le_mul_of_nonneg_left (by rw [pow_two, pow_two]; exact mul_self_le_mul_self (le_of_lt cos_one_pos) cos_one_le) (by norm_num)) _ ... < 0 : by norm_num end real namespace complex lemma abs_cos_add_sin_mul_I (x : ℝ) : abs (cos x + sin x * I) = 1 := have _ := real.sin_pow_two_add_cos_pow_two x, by simp [abs, norm_sq, pow_two, *, sin_of_real_re, cos_of_real_re, mul_re] at * lemma abs_exp_eq_iff_re_eq {x y : ℂ} : abs (exp x) = abs (exp y) ↔ x.re = y.re := by rw [exp_eq_exp_re_mul_sin_add_cos, exp_eq_exp_re_mul_sin_add_cos y, abs_mul, abs_mul, abs_cos_add_sin_mul_I, abs_cos_add_sin_mul_I, ← of_real_exp, ← of_real_exp, abs_of_nonneg (le_of_lt (real.exp_pos _)), abs_of_nonneg (le_of_lt (real.exp_pos _)), mul_one, mul_one]; exact ⟨λ h, real.exp_injective h, congr_arg _⟩ @[simp] lemma abs_exp_of_real (x : ℝ) : abs (exp x) = real.exp x := by rw [← of_real_exp]; exact abs_of_nonneg (le_of_lt (real.exp_pos _)) end complex
83cd1b521f9c464e92f675a26e7b4c1ced390398
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/playground/sizeof3.lean
a225f31920b8e09ad3a293d80880ac15de6669e0
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,344
lean
set_option trace.Meta.sizeOf true in mutual inductive AList (α β : Type u) | nil | cons (a : α) (t : BList α β) inductive BList (α β : Type u) | cons (b : β) (t : AList α β) end #print AList.nil.sizeOf_spec #print AList.cons.sizeOf_spec #print BList.cons.sizeOf_spec mutual inductive Foo (α : Type u) | mk (cs : AList (Foo α) (Boo α)) inductive Boo (α : Type u) | mk (a : α) (cs : BList (Foo α) (Boo α)) end namespace Foo theorem aux_1 [SizeOf α] (a : AList (Foo α) (Boo α)) : Foo._sizeOf_3 a = sizeOf a := @AList.rec (Foo α) (Boo α) (fun a => Foo._sizeOf_3 a = sizeOf a) (fun b => Foo._sizeOf_4 b = sizeOf b) rfl (fun a t ih => by show 1 + sizeOf a + Foo._sizeOf_4 t = sizeOf (AList.cons a t) rw ih rfl) (fun b t ih => by show 1 + sizeOf b + Foo._sizeOf_3 t = sizeOf (BList.cons b t) rw ih rfl) a theorem aux_2 [SizeOf α] (a : BList (Foo α) (Boo α)) : Foo._sizeOf_4 a = sizeOf a := @BList.rec (Foo α) (Boo α) (fun a => Foo._sizeOf_3 a = sizeOf a) (fun b => Foo._sizeOf_4 b = sizeOf b) rfl (fun a t ih => by show 1 + sizeOf a + Foo._sizeOf_4 t = sizeOf (AList.cons a t) rw ih rfl) (fun b t ih => by show 1 + sizeOf b + Foo._sizeOf_3 t = sizeOf (BList.cons b t) rw ih rfl) a
8b90e0f7409134bc1e122378f1b84604b17eb918
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/algebra/group/to_additive.lean
2d9e7465f241b7b9c112a996ffe7d4b32d7d7b90
[ "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
17,201
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 Kudryashov, Floris van Doorn -/ import tactic.transform_decl import tactic.algebra /-! # Transport multiplicative to additive This file defines an attribute `to_additive` that can be used to automatically transport theorems and definitions (but not inductive types and structures) from a multiplicative theory to an additive theory. Usage information is contained in the doc string of `to_additive.attr`. ### Missing features * Automatically transport structures and other inductive types. * For structures, automatically generate theorems like `group α ↔ add_group (additive α)`. * Rewrite rules for the last part of the name that work in more cases. E.g., we can replace `monoid` with `add_monoid` etc. -/ namespace to_additive open tactic exceptional section performance_hack -- see Note [user attribute parameters] local attribute [semireducible] reflected /-- Temporarily change the `has_reflect` instance for `name`. -/ local attribute [instance, priority 9000] meta def hacky_name_reflect : has_reflect name := λ n, `(id %%(expr.const n []) : name) /-- An auxiliary attribute used to store the names of the additive versions of declarations that have been processed by `to_additive`. -/ @[user_attribute] meta def aux_attr : user_attribute (name_map name) name := { name := `to_additive_aux, descr := "Auxiliary attribute for `to_additive`. DON'T USE IT", cache_cfg := ⟨λ ns, ns.mfoldl (λ dict n', do let n := match n' with | name.mk_string s pre := if s = "_to_additive" then pre else n' | _ := n' end, param ← aux_attr.get_param_untyped n', pure $ dict.insert n param.app_arg.const_name) mk_name_map, []⟩, parser := lean.parser.ident } end performance_hack section extra_attributes setup_tactic_parser /-- n attribute that tells `@[to_additive]` that certain arguments of this definition are not involved when using `@[to_additive]`. This helps the heuristic of `@[to_additive]` by also transforming definitions if `ℕ` or another fixed type occurs as one of these arguments. -/ @[user_attribute] meta def ignore_args_attr : user_attribute (name_map $ list ℕ) (list ℕ) := { name := `to_additive_ignore_args, descr := "Auxiliary attribute for `to_additive` stating that certain arguments are not additivized.", cache_cfg := ⟨λ ns, ns.mfoldl (λ dict n, do param ← ignore_args_attr.get_param_untyped n, -- see Note [user attribute parameters] return $ dict.insert n (param.to_list expr.to_nat).iget) mk_name_map, []⟩, parser := (lean.parser.small_nat)* } end extra_attributes /-- A command that can be used to have future uses of `to_additive` change the `src` namespace to the `tgt` namespace. For example: ``` run_cmd to_additive.map_namespace `quotient_group `quotient_add_group ``` Later uses of `to_additive` on declarations in the `quotient_group` namespace will be created in the `quotient_add_group` namespaces. -/ meta def map_namespace (src tgt : name) : command := do let n := src.mk_string "_to_additive", let decl := declaration.thm n [] `(unit) (pure (reflect ())), add_decl decl, aux_attr.set n tgt tt /-- `value_type` is the type of the arguments that can be provided to `to_additive`. `to_additive.parser` parses the provided arguments into `name` for the target and an optional doc string. -/ @[derive has_reflect, derive inhabited] structure value_type : Type := (replace_all : bool) (tgt : name) (doc : option string) /-- `add_comm_prefix x s` returns `"comm_" ++ s` if `x = tt` and `s` otherwise. -/ meta def add_comm_prefix : bool → string → string | tt s := ("comm_" ++ s) | ff s := s /-- Dictionary used by `to_additive.guess_name` to autogenerate names. -/ meta def tr : bool → list string → list string | is_comm ("one" :: "le" :: s) := add_comm_prefix is_comm "nonneg" :: tr ff s | is_comm ("one" :: "lt" :: s) := add_comm_prefix is_comm "pos" :: tr ff s | is_comm ("le" :: "one" :: s) := add_comm_prefix is_comm "nonpos" :: tr ff s | is_comm ("lt" :: "one" :: s) := add_comm_prefix is_comm "neg" :: tr ff s | is_comm ("mul" :: "support" :: s) := add_comm_prefix is_comm "support" :: tr ff s | is_comm ("mul" :: "indicator" :: s) := add_comm_prefix is_comm "indicator" :: tr ff s | is_comm ("mul" :: s) := add_comm_prefix is_comm "add" :: tr ff s | is_comm ("smul" :: s) := add_comm_prefix is_comm "vadd" :: tr ff s | is_comm ("inv" :: s) := add_comm_prefix is_comm "neg" :: tr ff s | is_comm ("div" :: s) := add_comm_prefix is_comm "sub" :: tr ff s | is_comm ("one" :: s) := add_comm_prefix is_comm "zero" :: tr ff s | is_comm ("prod" :: s) := add_comm_prefix is_comm "sum" :: tr ff s | is_comm ("finprod" :: s) := add_comm_prefix is_comm "finsum" :: tr ff s | is_comm ("npow" :: s) := add_comm_prefix is_comm "nsmul" :: tr ff s | is_comm ("gpow" :: s) := add_comm_prefix is_comm "gsmul" :: tr ff s | is_comm ("monoid" :: s) := ("add_" ++ add_comm_prefix is_comm "monoid") :: tr ff s | is_comm ("submonoid" :: s) := ("add_" ++ add_comm_prefix is_comm "submonoid") :: tr ff s | is_comm ("group" :: s) := ("add_" ++ add_comm_prefix is_comm "group") :: tr ff s | is_comm ("subgroup" :: s) := ("add_" ++ add_comm_prefix is_comm "subgroup") :: tr ff s | is_comm ("semigroup" :: s) := ("add_" ++ add_comm_prefix is_comm "semigroup") :: tr ff s | is_comm ("magma" :: s) := ("add_" ++ add_comm_prefix is_comm "magma") :: tr ff s | is_comm ("comm" :: s) := tr tt s | is_comm (x :: s) := (add_comm_prefix is_comm x :: tr ff s) | tt [] := ["comm"] | ff [] := [] /-- Autogenerate target name for `to_additive`. -/ meta def guess_name : string → string := string.map_tokens ''' $ λ s, string.intercalate (string.singleton '_') $ tr ff (s.split_on '_') /-- Return the provided target name or autogenerate one if one was not provided. -/ meta def target_name (src tgt : name) (dict : name_map name) : tactic name := (if tgt.get_prefix ≠ name.anonymous -- `tgt` is a full name then pure tgt else match src with | (name.mk_string s pre) := do let tgt_auto := guess_name s, guard (tgt.to_string ≠ tgt_auto ∨ tgt = src) <|> trace ("`to_additive " ++ src.to_string ++ "`: correctly autogenerated target " ++ "name, you may remove the explicit " ++ tgt_auto ++ " argument."), pure $ name.mk_string (if tgt = name.anonymous then tgt_auto else tgt.to_string) (pre.map_prefix dict.find) | _ := fail ("to_additive: can't transport " ++ src.to_string) end) >>= (λ res, if res = src ∧ tgt ≠ src then fail ("to_additive: can't transport " ++ src.to_string ++ " to itself. Give the desired additive name explicitly using `@[to_additive additive_name]`. ") else pure res) setup_tactic_parser /-- the parser for the arguments to `to_additive` -/ meta def parser : lean.parser value_type := do b ← option.is_some <$> (tk "!")?, tgt ← ident?, e ← texpr?, doc ← match e with | some pe := some <$> ((to_expr pe >>= eval_expr string) : tactic string) | none := pure none end, return ⟨b, tgt.get_or_else name.anonymous, doc⟩ private meta def proceed_fields_aux (src tgt : name) (prio : ℕ) (f : name → tactic (list string)) : command := do src_fields ← f src, tgt_fields ← f tgt, guard (src_fields.length = tgt_fields.length) <|> fail ("Failed to map fields of " ++ src.to_string), (src_fields.zip tgt_fields).mmap' $ λ names, guard (names.fst = names.snd) <|> aux_attr.set (src.append names.fst) (tgt.append names.snd) tt prio /-- Add the `aux_attr` attribute to the structure fields of `src` so that future uses of `to_additive` will map them to the corresponding `tgt` fields. -/ meta def proceed_fields (env : environment) (src tgt : name) (prio : ℕ) : command := let aux := proceed_fields_aux src tgt prio in do aux (λ n, pure $ list.map name.to_string $ (env.structure_fields n).get_or_else []) >> aux (λ n, (list.map (λ (x : name), "to_" ++ x.to_string) <$> get_tagged_ancestors n)) >> aux (λ n, (env.constructors_of n).mmap $ λ cs, match cs with | (name.mk_string s pre) := (guard (pre = n) <|> fail "Bad constructor name") >> pure s | _ := fail "Bad constructor name" end) /-- The attribute `to_additive` can be used to automatically transport theorems and definitions (but not inductive types and structures) from a multiplicative theory to an additive theory. To use this attribute, just write: ``` @[to_additive] theorem mul_comm' {α} [comm_semigroup α] (x y : α) : x * y = y * x := comm_semigroup.mul_comm ``` This code will generate a theorem named `add_comm'`. It is also possible to manually specify the name of the new declaration, and provide a documentation string: ``` @[to_additive add_foo "add_foo doc string"] /-- foo doc string -/ theorem foo := sorry ``` The transport tries to do the right thing in most cases using several heuristics described below. However, in some cases it fails, and requires manual intervention. If the declaration to be transported has attributes which need to be copied to the additive version, then `to_additive` should come last: ``` @[simp, to_additive] lemma mul_one' {G : Type*} [group G] (x : G) : x * 1 = x := mul_one x ``` The exception to this rule is the `simps` attribute, which should come after `to_additive`: ``` @[to_additive, simps] instance {M N} [has_mul M] [has_mul N] : has_mul (M × N) := ⟨λ p q, ⟨p.1 * q.1, p.2 * q.2⟩⟩ ``` ## Implementation notes The transport process generally works by taking all the names of identifiers appearing in the name, type, and body of a declaration and creating a new declaration by mapping those names to additive versions using a simple string-based dictionary and also using all declarations that have previously been labeled with `to_additive`. In the `mul_comm'` example above, `to_additive` maps: * `mul_comm'` to `add_comm'`, * `comm_semigroup` to `add_comm_semigroup`, * `x * y` to `x + y` and `y * x` to `y + x`, and * `comm_semigroup.mul_comm'` to `add_comm_semigroup.add_comm'`. ### Heuristics `to_additive` uses heuristics to determine whether a particular identifier has to be mapped to its additive version. The basic heuristic is * Only map an identifier to its additive version if its first argument doesn't contain any unapplied identifiers. Examples: * `@has_mul.mul ℕ n m` (i.e. `(n * m : ℕ)`) will not change to `+`, since its first argument is `ℕ`, an identifier not applied to any arguments. * `@has_mul.mul (α × β) x y` will change to `+`. It's first argument contains only the identifier `prod`, but this is applied to arguments, `α` and `β`. * `@has_mul.mul (α × ℤ) x y` will not change to `+`, since its first argument contains `ℤ`. The reasoning behind the heuristic is that the first argument is the type which is "additivized", and this usually doesn't make sense if this is on a fixed type. There are two exceptions in this heuristic: * Identifiers that have the `@[to_additive]` attribute are ignored. For example, multiplication in `↥Semigroup` is replaced by addition in `↥AddSemigroup`. * If an identifier has attribute `@[to_additive_ignore_args n1 n2 ...]` then all the arguments in positions `n1`, `n2`, ... will not be checked for unapplied identifiers (start counting from 1). For example, `times_cont_mdiff_map` has attribute `@[to_additive_ignore_args 21]`, which means that its 21st argument `(n : with_top ℕ)` can contain `ℕ` (usually in the form `has_top.top ℕ ...`) and still be additivized. So `@has_mul.mul (C^∞⟮I, N; I', G⟯) _ f g` will be additivized. If you want to disable this heuristic and replace all multiplicative identifiers with their additive counterpart, use `@[to_additive!]`. If `to_additive` is unable to automatically generate the additive version of a declaration, it can be useful to apply the attribute manually: ``` attribute [to_additive foo_add_bar] foo_bar ``` This will allow future uses of `to_additive` to recognize that `foo_bar` should be replaced with `foo_add_bar`. ### Handling of hidden definitions Before transporting the “main” declaration `src`, `to_additive` first scans its type and value for names starting with `src`, and transports them. This includes auxiliary definitions like `src._match_1`, `src._proof_1`. After transporting the “main” declaration, `to_additive` transports its equational lemmas. ### Structure fields and constructors If `src` is a structure, then `to_additive` automatically adds structure fields to its mapping, and similarly for constructors of inductive types. For new structures this means that `to_additive` automatically handles coercions, and for old structures it does the same, if ancestry information is present in `@[ancestor]` attributes. The `ancestor` attribute must come before the `to_additive` attribute, and it is essential that the order of the base structures passed to `ancestor` matches between the multiplicative and additive versions of the structure. ### Name generation * If `@[to_additive]` is called without a `name` argument, then the new name is autogenerated. First, it takes the longest prefix of the source name that is already known to `to_additive`, and replaces this prefix with its additive counterpart. Second, it takes the last part of the name (i.e., after the last dot), and replaces common name parts (“mul”, “one”, “inv”, “prod”) with their additive versions. * Namespaces can be transformed using `map_namespace`. For example: ``` run_cmd to_additive.map_namespace `quotient_group `quotient_add_group ``` Later uses of `to_additive` on declarations in the `quotient_group` namespace will be created in the `quotient_add_group` namespaces. * If `@[to_additive]` is called with a `name` argument `new_name` /without a dot/, then `to_additive` updates the prefix as described above, then replaces the last part of the name with `new_name`. * If `@[to_additive]` is called with a `name` argument `new_namespace.new_name` /with a dot/, then `to_additive` uses this new name as is. As a safety check, in the first case `to_additive` double checks that the new name differs from the original one. -/ @[user_attribute] protected meta def attr : user_attribute unit value_type := { name := `to_additive, descr := "Transport multiplicative to additive", parser := parser, after_set := some $ λ src prio persistent, do guard persistent <|> fail "`to_additive` can't be used as a local attribute", env ← get_env, val ← attr.get_param src, dict ← aux_attr.get_cache, ignore ← ignore_args_attr.get_cache, tgt ← target_name src val.tgt dict, aux_attr.set src tgt tt, let dict := dict.insert src tgt, if env.contains tgt then proceed_fields env src tgt prio else do transform_decl_with_prefix_dict dict val.replace_all ignore src tgt [`reducible, `_refl_lemma, `simp, `instance, `refl, `symm, `trans, `elab_as_eliminator, `no_rsimp, `measurability], mwhen (has_attribute' `simps src) (trace "Apply the simps attribute after the to_additive attribute"), match val.doc with | some doc := add_doc_string tgt doc | none := skip end } add_tactic_doc { name := "to_additive", category := doc_category.attr, decl_names := [`to_additive.attr], tags := ["transport", "environment", "lemma derivation"] } end to_additive /- map operations -/ attribute [to_additive] has_mul has_one has_inv has_div /- the following types are supported by `@[to_additive]` and mapped to themselves. -/ attribute [to_additive empty] empty attribute [to_additive pempty] pempty attribute [to_additive punit] punit attribute [to_additive unit] unit /- We ignore the third argument of `has_coe_to_fun.F` when deciding whether the operation needs to be additivized. The reason is that this argument is the element to be coerced, which usually does not actually show up in the type after reduction. Hypothetically, this could be ignoring too much, in that case, we can remove this, but in that case we have to add the `to_additive_ignore_args` attribute more systematically to a lot of other definitions (like `times_cont_mdiff_map.comp`). -/ attribute [to_additive_ignore_args 3] has_coe_to_fun.F
866992f048a6be71efb784b921de887acbf3fd37
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/analysis/normed_space/units.lean
8a23c6b7c6c589bbeae6dbb63160479ca7add7e1
[ "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
12,084
lean
/- Copyright (c) 2020 Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth -/ import analysis.specific_limits /-! # The group of units of a complete normed ring This file contains the basic theory for the group of units (invertible elements) of a complete normed ring (Banach algebras being a notable special case). ## Main results The constructions `one_sub`, `add` and `unit_of_nearby` state, in varying forms, that perturbations of a unit are units. The latter two are not stated in their optimal form; more precise versions would use the spectral radius. The first main result is `is_open`: the group of units of a complete normed ring is an open subset of the ring. The function `inverse` (defined in `algebra.ring`), for a ring `R`, sends `a : R` to `a⁻¹` if `a` is a unit and 0 if not. The other major results of this file (notably `inverse_add`, `inverse_add_norm` and `inverse_add_norm_diff_nth_order`) cover the asymptotic properties of `inverse (x + t)` as `t → 0`. -/ noncomputable theory open_locale topological_space variables {R : Type*} [normed_ring R] [complete_space R] namespace units /-- In a complete normed ring, a perturbation of `1` by an element `t` of distance less than `1` from `1` is a unit. Here we construct its `units` structure. -/ @[simps coe] def one_sub (t : R) (h : ∥t∥ < 1) : Rˣ := { val := 1 - t, inv := ∑' n : ℕ, t ^ n, val_inv := mul_neg_geom_series t h, inv_val := geom_series_mul_neg t h } /-- In a complete normed ring, a perturbation of a unit `x` by an element `t` of distance less than `∥x⁻¹∥⁻¹` from `x` is a unit. Here we construct its `units` structure. -/ @[simps coe] def add (x : Rˣ) (t : R) (h : ∥t∥ < ∥(↑x⁻¹ : R)∥⁻¹) : Rˣ := units.copy -- to make `coe_add` true definitionally, for convenience (x * (units.one_sub (-(↑x⁻¹ * t)) begin nontriviality R using [zero_lt_one], have hpos : 0 < ∥(↑x⁻¹ : R)∥ := units.norm_pos x⁻¹, calc ∥-(↑x⁻¹ * t)∥ = ∥↑x⁻¹ * t∥ : by { rw norm_neg } ... ≤ ∥(↑x⁻¹ : R)∥ * ∥t∥ : norm_mul_le ↑x⁻¹ _ ... < ∥(↑x⁻¹ : R)∥ * ∥(↑x⁻¹ : R)∥⁻¹ : by nlinarith only [h, hpos] ... = 1 : mul_inv_cancel (ne_of_gt hpos) end)) (x + t) (by simp [mul_add]) _ rfl /-- In a complete normed ring, an element `y` of distance less than `∥x⁻¹∥⁻¹` from `x` is a unit. Here we construct its `units` structure. -/ @[simps coe] def unit_of_nearby (x : Rˣ) (y : R) (h : ∥y - x∥ < ∥(↑x⁻¹ : R)∥⁻¹) : Rˣ := units.copy (x.add (y - x : R) h) y (by simp) _ rfl /-- The group of units of a complete normed ring is an open subset of the ring. -/ protected lemma is_open : is_open {x : R | is_unit x} := begin nontriviality R, apply metric.is_open_iff.mpr, rintros x' ⟨x, rfl⟩, refine ⟨∥(↑x⁻¹ : R)∥⁻¹, _root_.inv_pos.mpr (units.norm_pos x⁻¹), _⟩, intros y hy, rw [metric.mem_ball, dist_eq_norm] at hy, exact (x.unit_of_nearby y hy).is_unit end protected lemma nhds (x : Rˣ) : {x : R | is_unit x} ∈ 𝓝 (x : R) := is_open.mem_nhds units.is_open x.is_unit end units namespace normed_ring open_locale classical big_operators open asymptotics filter metric finset ring lemma inverse_one_sub (t : R) (h : ∥t∥ < 1) : inverse (1 - t) = ↑(units.one_sub t h)⁻¹ := by rw [← inverse_unit (units.one_sub t h), units.coe_one_sub] /-- The formula `inverse (x + t) = inverse (1 + x⁻¹ * t) * x⁻¹` holds for `t` sufficiently small. -/ lemma inverse_add (x : Rˣ) : ∀ᶠ t in (𝓝 0), inverse ((x : R) + t) = inverse (1 + ↑x⁻¹ * t) * ↑x⁻¹ := begin nontriviality R, rw [eventually_iff, metric.mem_nhds_iff], have hinv : 0 < ∥(↑x⁻¹ : R)∥⁻¹, by cancel_denoms, use [∥(↑x⁻¹ : R)∥⁻¹, hinv], intros t ht, simp only [mem_ball, dist_zero_right] at ht, have ht' : ∥-↑x⁻¹ * t∥ < 1, { refine lt_of_le_of_lt (norm_mul_le _ _) _, rw norm_neg, refine lt_of_lt_of_le (mul_lt_mul_of_pos_left ht x⁻¹.norm_pos) _, cancel_denoms }, have hright := inverse_one_sub (-↑x⁻¹ * t) ht', have hleft := inverse_unit (x.add t ht), simp only [← neg_mul_eq_neg_mul, sub_neg_eq_add] at hright, simp only [units.coe_add] at hleft, simp [hleft, hright, units.add] end lemma inverse_one_sub_nth_order (n : ℕ) : ∀ᶠ t in (𝓝 0), inverse ((1:R) - t) = (∑ i in range n, t ^ i) + (t ^ n) * inverse (1 - t) := begin simp only [eventually_iff, metric.mem_nhds_iff], use [1, by norm_num], intros t ht, simp only [mem_ball, dist_zero_right] at ht, simp only [inverse_one_sub t ht, set.mem_set_of_eq], have h : 1 = ((range n).sum (λ i, t ^ i)) * (units.one_sub t ht) + t ^ n, { simp only [units.coe_one_sub], rw [← geom_sum, geom_sum_mul_neg], simp }, rw [← one_mul ↑(units.one_sub t ht)⁻¹, h, add_mul], congr, { rw [mul_assoc, (units.one_sub t ht).mul_inv], simp }, { simp only [units.coe_one_sub], rw [← add_mul, ← geom_sum, geom_sum_mul_neg], simp } end /-- The formula `inverse (x + t) = (∑ i in range n, (- x⁻¹ * t) ^ i) * x⁻¹ + (- x⁻¹ * t) ^ n * inverse (x + t)` holds for `t` sufficiently small. -/ lemma inverse_add_nth_order (x : Rˣ) (n : ℕ) : ∀ᶠ t in (𝓝 0), inverse ((x : R) + t) = (∑ i in range n, (- ↑x⁻¹ * t) ^ i) * ↑x⁻¹ + (- ↑x⁻¹ * t) ^ n * inverse (x + t) := begin refine (inverse_add x).mp _, have hzero : tendsto (λ (t : R), - ↑x⁻¹ * t) (𝓝 0) (𝓝 0), { convert ((mul_left_continuous (- (↑x⁻¹ : R))).tendsto 0).comp tendsto_id, simp }, refine (hzero.eventually (inverse_one_sub_nth_order n)).mp (eventually_of_forall _), simp only [neg_mul_eq_neg_mul_symm, sub_neg_eq_add], intros t h1 h2, have h := congr_arg (λ (a : R), a * ↑x⁻¹) h1, dsimp at h, convert h, rw [add_mul, mul_assoc], simp [h2.symm] end lemma inverse_one_sub_norm : is_O (λ t, inverse ((1:R) - t)) (λ t, (1:ℝ)) (𝓝 (0:R)) := begin simp only [is_O, is_O_with, eventually_iff, metric.mem_nhds_iff], refine ⟨∥(1:R)∥ + 1, (2:ℝ)⁻¹, by norm_num, _⟩, intros t ht, simp only [ball, dist_zero_right, set.mem_set_of_eq] at ht, have ht' : ∥t∥ < 1, { have : (2:ℝ)⁻¹ < 1 := by cancel_denoms, linarith }, simp only [inverse_one_sub t ht', norm_one, mul_one, set.mem_set_of_eq], change ∥∑' n : ℕ, t ^ n∥ ≤ _, have := normed_ring.tsum_geometric_of_norm_lt_1 t ht', have : (1 - ∥t∥)⁻¹ ≤ 2, { rw ← inv_inv₀ (2:ℝ), refine inv_le_inv_of_le (by norm_num) _, have : (2:ℝ)⁻¹ + (2:ℝ)⁻¹ = 1 := by ring, linarith }, linarith end /-- The function `λ t, inverse (x + t)` is O(1) as `t → 0`. -/ lemma inverse_add_norm (x : Rˣ) : is_O (λ t, inverse (↑x + t)) (λ t, (1:ℝ)) (𝓝 (0:R)) := begin simp only [is_O_iff, norm_one, mul_one], cases is_O_iff.mp (@inverse_one_sub_norm R _ _) with C hC, use C * ∥((x⁻¹:Rˣ):R)∥, have hzero : tendsto (λ t, - (↑x⁻¹ : R) * t) (𝓝 0) (𝓝 0), { convert ((mul_left_continuous (-↑x⁻¹ : R)).tendsto 0).comp tendsto_id, simp }, refine (inverse_add x).mp ((hzero.eventually hC).mp (eventually_of_forall _)), intros t bound iden, rw iden, simp at bound, have hmul := norm_mul_le (inverse (1 + ↑x⁻¹ * t)) ↑x⁻¹, nlinarith [norm_nonneg (↑x⁻¹ : R)] end /-- The function `λ t, inverse (x + t) - (∑ i in range n, (- x⁻¹ * t) ^ i) * x⁻¹` is `O(t ^ n)` as `t → 0`. -/ lemma inverse_add_norm_diff_nth_order (x : Rˣ) (n : ℕ) : is_O (λ (t : R), inverse (↑x + t) - (∑ i in range n, (- ↑x⁻¹ * t) ^ i) * ↑x⁻¹) (λ t, ∥t∥ ^ n) (𝓝 (0:R)) := begin by_cases h : n = 0, { simpa [h] using inverse_add_norm x }, have hn : 0 < n := nat.pos_of_ne_zero h, simp [is_O_iff], cases (is_O_iff.mp (inverse_add_norm x)) with C hC, use C * ∥(1:ℝ)∥ * ∥(↑x⁻¹ : R)∥ ^ n, have h : eventually_eq (𝓝 (0:R)) (λ t, inverse (↑x + t) - (∑ i in range n, (- ↑x⁻¹ * t) ^ i) * ↑x⁻¹) (λ t, ((- ↑x⁻¹ * t) ^ n) * inverse (x + t)), { refine (inverse_add_nth_order x n).mp (eventually_of_forall _), intros t ht, convert congr_arg (λ a, a - (range n).sum (pow (-↑x⁻¹ * t)) * ↑x⁻¹) ht, simp }, refine h.mp (hC.mp (eventually_of_forall _)), intros t _ hLHS, simp only [neg_mul_eq_neg_mul_symm] at hLHS, rw hLHS, refine le_trans (norm_mul_le _ _ ) _, have h' : ∥(-(↑x⁻¹ * t)) ^ n∥ ≤ ∥(↑x⁻¹ : R)∥ ^ n * ∥t∥ ^ n, { calc ∥(-(↑x⁻¹ * t)) ^ n∥ ≤ ∥(-(↑x⁻¹ * t))∥ ^ n : norm_pow_le' _ hn ... = ∥↑x⁻¹ * t∥ ^ n : by rw norm_neg ... ≤ (∥(↑x⁻¹ : R)∥ * ∥t∥) ^ n : _ ... = ∥(↑x⁻¹ : R)∥ ^ n * ∥t∥ ^ n : mul_pow _ _ n, exact pow_le_pow_of_le_left (norm_nonneg _) (norm_mul_le ↑x⁻¹ t) n }, have h'' : 0 ≤ ∥(↑x⁻¹ : R)∥ ^ n * ∥t∥ ^ n, { refine mul_nonneg _ _; exact pow_nonneg (norm_nonneg _) n }, nlinarith [norm_nonneg (inverse (↑x + t))], end /-- The function `λ t, inverse (x + t) - x⁻¹` is `O(t)` as `t → 0`. -/ lemma inverse_add_norm_diff_first_order (x : Rˣ) : is_O (λ t, inverse (↑x + t) - ↑x⁻¹) (λ t, ∥t∥) (𝓝 (0:R)) := by simpa using inverse_add_norm_diff_nth_order x 1 /-- The function `λ t, inverse (x + t) - x⁻¹ + x⁻¹ * t * x⁻¹` is `O(t ^ 2)` as `t → 0`. -/ lemma inverse_add_norm_diff_second_order (x : Rˣ) : is_O (λ t, inverse (↑x + t) - ↑x⁻¹ + ↑x⁻¹ * t * ↑x⁻¹) (λ t, ∥t∥ ^ 2) (𝓝 (0:R)) := begin convert inverse_add_norm_diff_nth_order x 2, ext t, simp only [range_succ, range_one, sum_insert, mem_singleton, sum_singleton, not_false_iff, one_ne_zero, pow_zero, add_mul, pow_one, one_mul, neg_mul_eq_neg_mul_symm, sub_add_eq_sub_sub_swap, sub_neg_eq_add], end /-- The function `inverse` is continuous at each unit of `R`. -/ lemma inverse_continuous_at (x : Rˣ) : continuous_at inverse (x : R) := begin have h_is_o : is_o (λ (t : R), inverse (↑x + t) - ↑x⁻¹) (λ _, 1 : R → ℝ) (𝓝 0), from ((inverse_add_norm_diff_first_order x).trans_is_o (is_o_id_const (@one_ne_zero ℝ _ _)).norm_left), have h_lim : tendsto (λ (y:R), y - x) (𝓝 x) (𝓝 0), { refine tendsto_zero_iff_norm_tendsto_zero.mpr _, exact tendsto_iff_norm_tendsto_zero.mp tendsto_id }, rw [continuous_at, tendsto_iff_norm_tendsto_zero, inverse_unit], simpa [(∘)] using h_is_o.norm_left.tendsto_div_nhds_zero.comp h_lim end end normed_ring namespace units open mul_opposite filter normed_ring /-- In a normed ring, the coercion from `Rˣ` (equipped with the induced topology from the embedding in `R × R`) to `R` is an open map. -/ lemma is_open_map_coe : is_open_map (coe : Rˣ → R) := begin rw is_open_map_iff_nhds_le, intros x s, rw [mem_map, mem_nhds_induced], rintros ⟨t, ht, hts⟩, obtain ⟨u, hu, v, hv, huvt⟩ : ∃ (u : set R), u ∈ 𝓝 ↑x ∧ ∃ (v : set Rᵐᵒᵖ), v ∈ 𝓝 (op ↑x⁻¹) ∧ u ×ˢ v ⊆ t, { simpa [embed_product, mem_nhds_prod_iff] using ht }, have : u ∩ (op ∘ ring.inverse) ⁻¹' v ∩ (set.range (coe : Rˣ → R)) ∈ 𝓝 ↑x, { refine inter_mem (inter_mem hu _) (units.nhds x), refine (continuous_op.continuous_at.comp (inverse_continuous_at x)).preimage_mem_nhds _, simpa using hv }, refine mem_of_superset this _, rintros _ ⟨⟨huy, hvy⟩, ⟨y, rfl⟩⟩, have : embed_product R y ∈ u ×ˢ v := ⟨huy, by simpa using hvy⟩, simpa using hts (huvt this) end /-- In a normed ring, the coercion from `Rˣ` (equipped with the induced topology from the embedding in `R × R`) to `R` is an open embedding. -/ lemma open_embedding_coe : open_embedding (coe : Rˣ → R) := open_embedding_of_continuous_injective_open continuous_coe ext is_open_map_coe end units
f9604d29689363568afdc8d44e4ceb328f072ce5
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/set_theory/cardinal.lean
424549c4946a024b3d073488810feb93b597d205
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
52,027
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, Floris van Doorn -/ import data.set.countable import set_theory.schroeder_bernstein import data.fintype.card import data.nat.enat /-! # Cardinal Numbers We define cardinal numbers as a quotient of types under the equivalence relation of equinumerity. ## Main definitions * `cardinal` the type of cardinal numbers (in a given universe). * `cardinal.mk α` or `#α` is the cardinality of `α`. The notation `#` lives in the locale `cardinal`. * There is an instance that `cardinal` forms a `canonically_ordered_comm_semiring`. * Addition `c₁ + c₂` is defined by `cardinal.add_def α β : #α + #β = #(α ⊕ β)`. * Multiplication `c₁ * c₂` is defined by `cardinal.mul_def : #α * #β = #(α * β)`. * The order `c₁ ≤ c₂` is defined by `cardinal.le_def α β : #α ≤ #β ↔ nonempty (α ↪ β)`. * Exponentiation `c₁ ^ c₂` is defined by `cardinal.power_def α β : #α ^ #β = #(β → α)`. * `cardinal.omega` the cardinality of `ℕ`. This definition is universe polymorphic: `cardinal.omega.{u} : cardinal.{u}` (contrast with `ℕ : Type`, which lives in a specific universe). In some cases the universe level has to be given explicitly. * `cardinal.min (I : nonempty ι) (c : ι → cardinal)` is the minimal cardinal in the range of `c`. * `cardinal.succ c` is the successor cardinal, the smallest cardinal larger than `c`. * `cardinal.sum` is the sum of a collection of cardinals. * `cardinal.sup` is the supremum of a collection of cardinals. * `cardinal.powerlt c₁ c₂` or `c₁ ^< c₂` is defined as `sup_{γ < β} α^γ`. ## Main Statements * Cantor's theorem: `cardinal.cantor c : c < 2 ^ c`. * König's theorem: `cardinal.sum_lt_prod` ## Implementation notes * There is a type of cardinal numbers in every universe level: `cardinal.{u} : Type (u + 1)` is the quotient of types in `Type u`. The operation `cardinal.lift` lifts cardinal numbers to a higher level. * Cardinal arithmetic specifically for infinite cardinals (like `κ * κ = κ`) is in the file `set_theory/cardinal_ordinal.lean`. * There is an instance `has_pow cardinal`, but this will only fire if Lean already knows that both the base and the exponent live in the same universe. As a workaround, you can add ``` local infixr ^ := @has_pow.pow cardinal cardinal cardinal.has_pow ``` to a file. This notation will work even if Lean doesn't know yet that the base and the exponent live in the same universe (but no exponents in other types can be used). ## References * <https://en.wikipedia.org/wiki/Cardinal_number> ## Tags cardinal number, cardinal arithmetic, cardinal exponentiation, omega, Cantor's theorem, König's theorem -/ open function set open_locale classical universes u v w x variables {α β : Type u} /-- The equivalence relation on types given by equivalence (bijective correspondence) of types. Quotienting by this equivalence relation gives the cardinal numbers. -/ instance cardinal.is_equivalent : setoid (Type u) := { r := λα β, nonempty (α ≃ β), iseqv := ⟨λα, ⟨equiv.refl α⟩, λα β ⟨e⟩, ⟨e.symm⟩, λα β γ ⟨e₁⟩ ⟨e₂⟩, ⟨e₁.trans e₂⟩⟩ } /-- `cardinal.{u}` is the type of cardinal numbers in `Type u`, defined as the quotient of `Type u` by existence of an equivalence (a bijection with explicit inverse). -/ def cardinal : Type (u + 1) := quotient cardinal.is_equivalent namespace cardinal /-- The cardinal number of a type -/ def mk : Type u → cardinal := quotient.mk localized "notation `#` := cardinal.mk" in cardinal protected lemma eq : mk α = mk β ↔ nonempty (α ≃ β) := quotient.eq @[simp] theorem mk_def (α : Type u) : @eq cardinal ⟦α⟧ (mk α) := rfl @[simp] theorem mk_out (c : cardinal) : mk (c.out) = c := quotient.out_eq _ /-- We define the order on cardinal numbers by `mk α ≤ mk β` if and only if there exists an embedding (injective function) from α to β. -/ instance : has_le cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, nonempty $ α ↪ β) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, propext ⟨assume ⟨e⟩, ⟨e.congr e₁ e₂⟩, assume ⟨e⟩, ⟨e.congr e₁.symm e₂.symm⟩⟩⟩ theorem le_def (α β : Type u) : mk α ≤ mk β ↔ nonempty (α ↪ β) := iff.rfl theorem mk_le_of_injective {α β : Type u} {f : α → β} (hf : injective f) : mk α ≤ mk β := ⟨⟨f, hf⟩⟩ theorem mk_le_of_surjective {α β : Type u} {f : α → β} (hf : surjective f) : mk β ≤ mk α := ⟨embedding.of_surjective f hf⟩ theorem le_mk_iff_exists_set {c : cardinal} {α : Type u} : c ≤ mk α ↔ ∃ p : set α, mk p = c := ⟨quotient.induction_on c $ λ β ⟨⟨f, hf⟩⟩, ⟨set.range f, eq.symm $ quot.sound ⟨equiv.of_injective f hf⟩⟩, λ ⟨p, e⟩, e ▸ ⟨⟨subtype.val, λ a b, subtype.eq⟩⟩⟩ theorem out_embedding {c c' : cardinal} : c ≤ c' ↔ nonempty (c.out ↪ c'.out) := by { transitivity _, rw [←quotient.out_eq c, ←quotient.out_eq c'], refl } protected lemma eq_congr : α ≃ β → # α = # β := λ h, quot.sound ⟨h⟩ noncomputable instance : linear_order cardinal.{u} := { le := (≤), le_refl := by rintros ⟨α⟩; exact ⟨embedding.refl _⟩, le_trans := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨e₁.trans e₂⟩, le_antisymm := by rintros ⟨α⟩ ⟨β⟩ ⟨e₁⟩ ⟨e₂⟩; exact quotient.sound (e₁.antisymm e₂), le_total := by rintros ⟨α⟩ ⟨β⟩; exact embedding.total, decidable_le := classical.dec_rel _ } -- short-circuit type class inference noncomputable instance : distrib_lattice cardinal.{u} := by apply_instance instance : has_zero cardinal.{u} := ⟨⟦pempty⟧⟩ instance : inhabited cardinal.{u} := ⟨0⟩ lemma eq_zero_iff_is_empty {α : Type u} : mk α = 0 ↔ is_empty α := ⟨λ e, let ⟨h⟩ := quotient.exact e in equiv.equiv_empty_equiv α $ h.trans equiv.empty_equiv_pempty.symm, λ h, by exactI quotient.sound ⟨equiv.equiv_pempty α⟩⟩ theorem ne_zero_iff_nonempty {α : Type u} : mk α ≠ 0 ↔ nonempty α := (not_iff_not.2 eq_zero_iff_is_empty).trans not_is_empty_iff instance : has_one cardinal.{u} := ⟨⟦punit⟧⟩ instance : nontrivial cardinal.{u} := ⟨⟨1, 0, ne_zero_iff_nonempty.2 ⟨punit.star⟩⟩⟩ theorem le_one_iff_subsingleton {α : Type u} : mk α ≤ 1 ↔ subsingleton α := ⟨λ ⟨f⟩, ⟨λ a b, f.injective (subsingleton.elim _ _)⟩, λ ⟨h⟩, ⟨⟨λ a, punit.star, λ a b _, h _ _⟩⟩⟩ theorem one_lt_iff_nontrivial {α : Type u} : 1 < mk α ↔ nontrivial α := by { rw [← not_iff_not, not_nontrivial_iff_subsingleton, ← le_one_iff_subsingleton], simp } instance : has_add cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, mk (α ⊕ β)) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, quotient.sound ⟨equiv.sum_congr e₁ e₂⟩⟩ @[simp] theorem add_def (α β) : mk α + mk β = mk (α ⊕ β) := rfl instance : has_mul cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, mk (α × β)) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, quotient.sound ⟨equiv.prod_congr e₁ e₂⟩⟩ @[simp] theorem mul_def (α β : Type u) : mk α * mk β = mk (α × β) := rfl private theorem add_comm (a b : cardinal.{u}) : a + b = b + a := quotient.induction_on₂ a b $ assume α β, quotient.sound ⟨equiv.sum_comm α β⟩ private theorem mul_comm (a b : cardinal.{u}) : a * b = b * a := quotient.induction_on₂ a b $ assume α β, quotient.sound ⟨equiv.prod_comm α β⟩ private theorem zero_add (a : cardinal.{u}) : 0 + a = a := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.empty_sum pempty α⟩ private theorem zero_mul (a : cardinal.{u}) : 0 * a = 0 := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_prod α⟩ private theorem one_mul (a : cardinal.{u}) : 1 * a = a := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.punit_prod α⟩ private theorem left_distrib (a b c : cardinal.{u}) : a * (b + c) = a * b + a * c := quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.prod_sum_distrib α β γ⟩ protected theorem eq_zero_or_eq_zero_of_mul_eq_zero {a b : cardinal.{u}} : a * b = 0 → a = 0 ∨ b = 0 := begin refine quotient.induction_on b _, refine quotient.induction_on a _, intros a b h, contrapose h, simp_rw [not_or_distrib, ← ne.def] at h, have := @prod.nonempty a b (ne_zero_iff_nonempty.mp h.1) (ne_zero_iff_nonempty.mp h.2), exact ne_zero_iff_nonempty.mpr this end instance : comm_semiring cardinal.{u} := { zero := 0, one := 1, add := (+), mul := (*), zero_add := zero_add, add_zero := assume a, by rw [add_comm a 0, zero_add a], add_assoc := λa b c, quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.sum_assoc α β γ⟩, add_comm := add_comm, zero_mul := zero_mul, mul_zero := assume a, by rw [mul_comm a 0, zero_mul a], one_mul := one_mul, mul_one := assume a, by rw [mul_comm a 1, one_mul a], mul_assoc := λa b c, quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.prod_assoc α β γ⟩, mul_comm := mul_comm, left_distrib := left_distrib, right_distrib := assume a b c, by rw [mul_comm (a + b) c, left_distrib c a b, mul_comm c a, mul_comm c b] } /-- The cardinal exponential. `mk α ^ mk β` is the cardinal of `β → α`. -/ protected def power (a b : cardinal.{u}) : cardinal.{u} := quotient.lift_on₂ a b (λα β, mk (β → α)) $ assume α₁ α₂ β₁ β₂ ⟨e₁⟩ ⟨e₂⟩, quotient.sound ⟨equiv.arrow_congr e₂ e₁⟩ instance : has_pow cardinal cardinal := ⟨cardinal.power⟩ local infixr ^ := @has_pow.pow cardinal cardinal cardinal.has_pow @[simp] theorem power_def (α β) : mk α ^ mk β = mk (β → α) := rfl @[simp] theorem power_zero {a : cardinal} : a ^ 0 = 1 := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_arrow_equiv_punit α⟩ @[simp] theorem power_one {a : cardinal} : a ^ 1 = a := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.punit_arrow_equiv α⟩ @[simp] theorem one_power {a : cardinal} : 1 ^ a = 1 := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.arrow_punit_equiv_punit α⟩ @[simp] theorem prop_eq_two : mk (ulift Prop) = 2 := quot.sound ⟨equiv.ulift.trans $ equiv.Prop_equiv_bool.trans equiv.bool_equiv_punit_sum_punit⟩ @[simp] theorem zero_power {a : cardinal} : a ≠ 0 → 0 ^ a = 0 := quotient.induction_on a $ assume α heq, (ne_zero_iff_nonempty.1 heq).elim $ assume a, by { haveI : nonempty α := ⟨a⟩, exact quotient.sound ⟨equiv.equiv_pempty _⟩ } theorem power_ne_zero {a : cardinal} (b) : a ≠ 0 → a ^ b ≠ 0 := quotient.induction_on₂ a b $ λ α β h, let ⟨a⟩ := ne_zero_iff_nonempty.1 h in ne_zero_iff_nonempty.2 ⟨λ _, a⟩ theorem mul_power {a b c : cardinal} : (a * b) ^ c = a ^ c * b ^ c := quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.arrow_prod_equiv_prod_arrow α β γ⟩ theorem power_add {a b c : cardinal} : a ^ (b + c) = a ^ b * a ^ c := quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.sum_arrow_equiv_prod_arrow β γ α⟩ theorem power_mul {a b c : cardinal} : a ^ (b * c) = (a ^ b) ^ c := by rw [_root_.mul_comm b c]; from (quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.curry γ β α⟩) @[simp] lemma pow_cast_right (κ : cardinal.{u}) : ∀ n : ℕ, (κ ^ (↑n : cardinal.{u})) = @has_pow.pow _ _ monoid.has_pow κ n | 0 := by simp | (_+1) := by rw [nat.cast_succ, power_add, power_one, _root_.mul_comm, pow_succ, pow_cast_right] section order_properties open sum protected theorem zero_le : ∀(a : cardinal), 0 ≤ a := by rintro ⟨α⟩; exact ⟨embedding.of_not_nonempty $ λ ⟨a⟩, a.elim⟩ protected theorem add_le_add : ∀{a b c d : cardinal}, a ≤ b → c ≤ d → a + c ≤ b + d := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨δ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨e₁.sum_map e₂⟩ protected theorem add_le_add_left (a) {b c : cardinal} : b ≤ c → a + b ≤ a + c := cardinal.add_le_add (le_refl _) protected theorem le_iff_exists_add {a b : cardinal} : a ≤ b ↔ ∃ c, b = a + c := ⟨quotient.induction_on₂ a b $ λ α β ⟨⟨f, hf⟩⟩, have (α ⊕ ((range f)ᶜ : set β)) ≃ β, from (equiv.sum_congr (equiv.of_injective f hf) (equiv.refl _)).trans $ (equiv.set.sum_compl (range f)), ⟨⟦↥(range f)ᶜ⟧, quotient.sound ⟨this.symm⟩⟩, λ ⟨c, e⟩, add_zero a ▸ e.symm ▸ cardinal.add_le_add_left _ (cardinal.zero_le _)⟩ instance : order_bot cardinal.{u} := { bot := 0, bot_le := cardinal.zero_le, ..cardinal.linear_order } instance : canonically_ordered_comm_semiring cardinal.{u} := { add_le_add_left := λ a b h c, cardinal.add_le_add_left _ h, lt_of_add_lt_add_left := λ a b c, lt_imp_lt_of_le_imp_le (cardinal.add_le_add_left _), le_iff_exists_add := @cardinal.le_iff_exists_add, eq_zero_or_eq_zero_of_mul_eq_zero := @cardinal.eq_zero_or_eq_zero_of_mul_eq_zero, ..cardinal.order_bot, ..cardinal.comm_semiring, ..cardinal.linear_order } noncomputable instance : canonically_linear_ordered_add_monoid cardinal.{u} := { .. (infer_instance : canonically_ordered_add_monoid cardinal.{u}), .. cardinal.linear_order } @[simp] theorem zero_lt_one : (0 : cardinal) < 1 := lt_of_le_of_ne (zero_le _) zero_ne_one lemma zero_power_le (c : cardinal.{u}) : (0 : cardinal.{u}) ^ c ≤ 1 := by { by_cases h : c = 0, rw [h, power_zero], rw [zero_power h], apply zero_le } theorem power_le_power_left : ∀{a b c : cardinal}, a ≠ 0 → b ≤ c → a ^ b ≤ a ^ c := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ hα ⟨e⟩; exact let ⟨a⟩ := ne_zero_iff_nonempty.1 hα in ⟨@embedding.arrow_congr_right _ _ _ ⟨a⟩ e⟩ theorem power_le_max_power_one {a b c : cardinal} (h : b ≤ c) : a ^ b ≤ max (a ^ c) 1 := begin by_cases ha : a = 0, simp [ha, zero_power_le], exact le_trans (power_le_power_left ha h) (le_max_left _ _) end theorem power_le_power_right {a b c : cardinal} : a ≤ b → a ^ c ≤ b ^ c := quotient.induction_on₃ a b c $ assume α β γ ⟨e⟩, ⟨embedding.arrow_congr_left e⟩ end order_properties theorem cantor : ∀(a : cardinal.{u}), a < 2 ^ a := by rw ← prop_eq_two; rintros ⟨a⟩; exact ⟨ ⟨⟨λ a b, ⟨a = b⟩, λ a b h, cast (ulift.up.inj (@congr_fun _ _ _ _ h b)).symm rfl⟩⟩, λ ⟨⟨f, hf⟩⟩, cantor_injective (λ s, f (λ a, ⟨s a⟩)) $ λ s t h, by funext a; injection congr_fun (hf h) a⟩ instance : no_top_order cardinal.{u} := { no_top := λ a, ⟨_, cantor a⟩, ..cardinal.linear_order } /-- The minimum cardinal in a family of cardinals (the existence of which is provided by `injective_min`). -/ noncomputable def min {ι} (I : nonempty ι) (f : ι → cardinal) : cardinal := f $ classical.some $ @embedding.min_injective _ (λ i, (f i).out) I theorem min_eq {ι} (I) (f : ι → cardinal) : ∃ i, min I f = f i := ⟨_, rfl⟩ theorem min_le {ι I} (f : ι → cardinal) (i) : min I f ≤ f i := by rw [← mk_out (min I f), ← mk_out (f i)]; exact let ⟨g⟩ := classical.some_spec (@embedding.min_injective _ (λ i, (f i).out) I) in ⟨g i⟩ theorem le_min {ι I} {f : ι → cardinal} {a} : a ≤ min I f ↔ ∀ i, a ≤ f i := ⟨λ h i, le_trans h (min_le _ _), λ h, let ⟨i, e⟩ := min_eq I f in e.symm ▸ h i⟩ protected theorem wf : @well_founded cardinal.{u} (<) := ⟨λ a, classical.by_contradiction $ λ h, let ι := {c :cardinal // ¬ acc (<) c}, f : ι → cardinal := subtype.val, ⟨⟨c, hc⟩, hi⟩ := @min_eq ι ⟨⟨_, h⟩⟩ f in hc (acc.intro _ (λ j ⟨_, h'⟩, classical.by_contradiction $ λ hj, h' $ by have := min_le f ⟨j, hj⟩; rwa hi at this))⟩ instance has_wf : @has_well_founded cardinal.{u} := ⟨(<), cardinal.wf⟩ instance wo : @is_well_order cardinal.{u} (<) := ⟨cardinal.wf⟩ /-- The successor cardinal - the smallest cardinal greater than `c`. This is not the same as `c + 1` except in the case of finite `c`. -/ noncomputable def succ (c : cardinal) : cardinal := @min {c' // c < c'} ⟨⟨_, cantor _⟩⟩ subtype.val theorem lt_succ_self (c : cardinal) : c < succ c := by cases min_eq _ _ with s e; rw [succ, e]; exact s.2 theorem succ_le {a b : cardinal} : succ a ≤ b ↔ a < b := ⟨lt_of_lt_of_le (lt_succ_self _), λ h, by exact min_le _ (subtype.mk b h)⟩ theorem lt_succ {a b : cardinal} : a < succ b ↔ a ≤ b := by rw [← not_le, succ_le, not_lt] theorem add_one_le_succ (c : cardinal) : c + 1 ≤ succ c := begin refine quot.induction_on c (λ α, _) (lt_succ_self c), refine quot.induction_on (succ (quot.mk setoid.r α)) (λ β h, _), cases h.left with f, have : ¬ surjective f := λ hn, ne_of_lt h (quotient.sound ⟨equiv.of_bijective f ⟨f.injective, hn⟩⟩), cases not_forall.1 this with b nex, refine ⟨⟨sum.rec (by exact f) _, _⟩⟩, { exact λ _, b }, { intros a b h, rcases a with a|⟨⟨⟨⟩⟩⟩; rcases b with b|⟨⟨⟨⟩⟩⟩, { rw f.injective h }, { exact nex.elim ⟨_, h⟩ }, { exact nex.elim ⟨_, h.symm⟩ }, { refl } } end lemma succ_ne_zero (c : cardinal) : succ c ≠ 0 := by { rw [←pos_iff_ne_zero, lt_succ], apply zero_le } /-- The indexed sum of cardinals is the cardinality of the indexed disjoint union, i.e. sigma type. -/ def sum {ι} (f : ι → cardinal) : cardinal := mk Σ i, (f i).out theorem le_sum {ι} (f : ι → cardinal) (i) : f i ≤ sum f := by rw ← quotient.out_eq (f i); exact ⟨⟨λ a, ⟨i, a⟩, λ a b h, eq_of_heq $ by injection h⟩⟩ @[simp] theorem sum_mk {ι} (f : ι → Type*) : sum (λ i, mk (f i)) = mk (Σ i, f i) := quot.sound ⟨equiv.sigma_congr_right $ λ i, classical.choice $ quotient.exact $ quot.out_eq $ mk (f i)⟩ theorem sum_const (ι : Type u) (a : cardinal.{u}) : sum (λ _:ι, a) = mk ι * a := quotient.induction_on a $ λ α, by simp; exact quotient.sound ⟨equiv.sigma_equiv_prod _ _⟩ theorem sum_le_sum {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sum f ≤ sum g := ⟨(embedding.refl _).sigma_map $ λ i, classical.choice $ by have := H i; rwa [← quot.out_eq (f i), ← quot.out_eq (g i)] at this⟩ /-- The indexed supremum of cardinals is the smallest cardinal above everything in the family. -/ noncomputable def sup {ι} (f : ι → cardinal) : cardinal := @min {c // ∀ i, f i ≤ c} ⟨⟨sum f, le_sum f⟩⟩ (λ a, a.1) theorem le_sup {ι} (f : ι → cardinal) (i) : f i ≤ sup f := by dsimp [sup]; cases min_eq _ _ with c hc; rw hc; exact c.2 i theorem sup_le {ι} {f : ι → cardinal} {a} : sup f ≤ a ↔ ∀ i, f i ≤ a := ⟨λ h i, le_trans (le_sup _ _) h, λ h, by dsimp [sup]; change a with (⟨a, h⟩:subtype _).1; apply min_le⟩ theorem sup_le_sup {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sup f ≤ sup g := sup_le.2 $ λ i, le_trans (H i) (le_sup _ _) theorem sup_le_sum {ι} (f : ι → cardinal) : sup f ≤ sum f := sup_le.2 $ le_sum _ theorem sum_le_sup {ι : Type u} (f : ι → cardinal.{u}) : sum f ≤ mk ι * sup.{u u} f := by rw ← sum_const; exact sum_le_sum _ _ (le_sup _) theorem sup_eq_zero {ι} {f : ι → cardinal} (h : ι → false) : sup f = 0 := by { rw [← nonpos_iff_eq_zero, sup_le], intro x, exfalso, exact h x } /-- The indexed product of cardinals is the cardinality of the Pi type (dependent product). -/ def prod {ι : Type u} (f : ι → cardinal) : cardinal := mk (Π i, (f i).out) @[simp] theorem prod_mk {ι} (f : ι → Type*) : prod (λ i, mk (f i)) = mk (Π i, f i) := quot.sound ⟨equiv.Pi_congr_right $ λ i, classical.choice $ quotient.exact $ mk_out $ mk (f i)⟩ theorem prod_const (ι : Type u) (a : cardinal.{u}) : prod (λ _:ι, a) = a ^ mk ι := quotient.induction_on a $ by simp theorem prod_le_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : prod f ≤ prod g := ⟨embedding.Pi_congr_right $ λ i, classical.choice $ by have := H i; rwa [← mk_out (f i), ← mk_out (g i)] at this⟩ theorem prod_ne_zero {ι} (f : ι → cardinal) : prod f ≠ 0 ↔ ∀ i, f i ≠ 0 := begin suffices : nonempty (Π i, (f i).out) ↔ ∀ i, nonempty (f i).out, { simpa [← ne_zero_iff_nonempty, prod] }, exact classical.nonempty_pi end theorem prod_eq_zero {ι} (f : ι → cardinal) : prod f = 0 ↔ ∃ i, f i = 0 := not_iff_not.1 $ by simpa using prod_ne_zero f /-- The universe lift operation on cardinals. You can specify the universes explicitly with `lift.{u v} : cardinal.{u} → cardinal.{max u v}` -/ def lift (c : cardinal.{u}) : cardinal.{max u v} := quotient.lift_on c (λ α, ⟦ulift α⟧) $ λ α β ⟨e⟩, quotient.sound ⟨equiv.ulift.trans $ e.trans equiv.ulift.symm⟩ theorem lift_mk (α) : lift.{u v} (mk α) = mk (ulift.{v u} α) := rfl theorem lift_umax : lift.{u (max u v)} = lift.{u v} := funext $ λ a, quot.induction_on a $ λ α, quotient.sound ⟨equiv.ulift.trans equiv.ulift.symm⟩ theorem lift_id' (a : cardinal) : lift a = a := quot.induction_on a $ λ α, quot.sound ⟨equiv.ulift⟩ @[simp] theorem lift_id : ∀ a, lift.{u u} a = a := lift_id'.{u u} @[simp] theorem lift_lift (a : cardinal) : lift.{(max u v) w} (lift.{u v} a) = lift.{u (max v w)} a := quot.induction_on a $ λ α, quotient.sound ⟨equiv.ulift.trans $ equiv.ulift.trans equiv.ulift.symm⟩ theorem lift_mk_le {α : Type u} {β : Type v} : lift.{u (max v w)} (mk α) ≤ lift.{v (max u w)} (mk β) ↔ nonempty (α ↪ β) := ⟨λ ⟨f⟩, ⟨embedding.congr equiv.ulift equiv.ulift f⟩, λ ⟨f⟩, ⟨embedding.congr equiv.ulift.symm equiv.ulift.symm f⟩⟩ theorem lift_mk_eq {α : Type u} {β : Type v} : lift.{u (max v w)} (mk α) = lift.{v (max u w)} (mk β) ↔ nonempty (α ≃ β) := quotient.eq.trans ⟨λ ⟨f⟩, ⟨equiv.ulift.symm.trans $ f.trans equiv.ulift⟩, λ ⟨f⟩, ⟨equiv.ulift.trans $ f.trans equiv.ulift.symm⟩⟩ @[simp] theorem lift_le {a b : cardinal} : lift a ≤ lift b ↔ a ≤ b := quotient.induction_on₂ a b $ λ α β, by rw ← lift_umax; exact lift_mk_le @[simp] theorem lift_inj {a b : cardinal} : lift a = lift b ↔ a = b := by simp [le_antisymm_iff] @[simp] theorem lift_lt {a b : cardinal} : lift a < lift b ↔ a < b := by simp [lt_iff_le_not_le, -not_le] @[simp] theorem lift_zero : lift 0 = 0 := quotient.sound ⟨equiv.ulift.trans equiv.pempty_equiv_pempty⟩ @[simp] theorem lift_one : lift 1 = 1 := quotient.sound ⟨equiv.ulift.trans equiv.punit_equiv_punit⟩ @[simp] theorem lift_add (a b) : lift (a + b) = lift a + lift b := quotient.induction_on₂ a b $ λ α β, quotient.sound ⟨equiv.ulift.trans (equiv.sum_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_mul (a b) : lift (a * b) = lift a * lift b := quotient.induction_on₂ a b $ λ α β, quotient.sound ⟨equiv.ulift.trans (equiv.prod_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_power (a b) : lift (a ^ b) = lift a ^ lift b := quotient.induction_on₂ a b $ λ α β, quotient.sound ⟨equiv.ulift.trans (equiv.arrow_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_two_power (a) : lift (2 ^ a) = 2 ^ lift a := by simp [bit0] @[simp] theorem lift_min {ι I} (f : ι → cardinal) : lift (min I f) = min I (lift ∘ f) := le_antisymm (le_min.2 $ λ a, lift_le.2 $ min_le _ a) $ let ⟨i, e⟩ := min_eq I (lift ∘ f) in by rw e; exact lift_le.2 (le_min.2 $ λ j, lift_le.1 $ by have := min_le (lift ∘ f) j; rwa e at this) theorem lift_down {a : cardinal.{u}} {b : cardinal.{max u v}} : b ≤ lift a → ∃ a', lift a' = b := quotient.induction_on₂ a b $ λ α β, by dsimp; rw [← lift_id (mk β), ← lift_umax, ← lift_umax.{u v}, lift_mk_le]; exact λ ⟨f⟩, ⟨mk (set.range f), eq.symm $ lift_mk_eq.2 ⟨embedding.equiv_of_surjective (embedding.cod_restrict _ f set.mem_range_self) $ λ ⟨a, ⟨b, e⟩⟩, ⟨b, subtype.eq e⟩⟩⟩ theorem le_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} : b ≤ lift a ↔ ∃ a', lift a' = b ∧ a' ≤ a := ⟨λ h, let ⟨a', e⟩ := lift_down h in ⟨a', e, lift_le.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_le.2 h⟩ theorem lt_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} : b < lift a ↔ ∃ a', lift a' = b ∧ a' < a := ⟨λ h, let ⟨a', e⟩ := lift_down (le_of_lt h) in ⟨a', e, lift_lt.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_lt.2 h⟩ @[simp] theorem lift_succ (a) : lift (succ a) = succ (lift a) := le_antisymm (le_of_not_gt $ λ h, begin rcases lt_lift_iff.1 h with ⟨b, e, h⟩, rw [lt_succ, ← lift_le, e] at h, exact not_lt_of_le h (lt_succ_self _) end) (succ_le.2 $ lift_lt.2 $ lt_succ_self _) @[simp] theorem lift_max {a : cardinal.{u}} {b : cardinal.{v}} : lift.{u (max v w)} a = lift.{v (max u w)} b ↔ lift.{u v} a = lift.{v u} b := calc lift.{u (max v w)} a = lift.{v (max u w)} b ↔ lift.{(max u v) w} (lift.{u v} a) = lift.{(max u v) w} (lift.{v u} b) : by simp ... ↔ lift.{u v} a = lift.{v u} b : lift_inj theorem mk_prod {α : Type u} {β : Type v} : mk (α × β) = lift.{u v} (mk α) * lift.{v u} (mk β) := quotient.sound ⟨equiv.prod_congr (equiv.ulift).symm (equiv.ulift).symm⟩ theorem sum_const_eq_lift_mul (ι : Type u) (a : cardinal.{v}) : sum (λ _:ι, a) = lift.{u v} (mk ι) * lift.{v u} a := begin apply quotient.induction_on a, intro α, simp only [cardinal.mk_def, cardinal.sum_mk, cardinal.lift_id], convert mk_prod using 1, exact quotient.sound ⟨equiv.sigma_equiv_prod ι α⟩, end /-- `ω` is the smallest infinite cardinal, also known as ℵ₀. -/ def omega : cardinal.{u} := lift (mk ℕ) lemma mk_nat : mk nat = omega := (lift_id _).symm theorem omega_ne_zero : omega ≠ 0 := ne_zero_iff_nonempty.2 ⟨⟨0⟩⟩ theorem omega_pos : 0 < omega := pos_iff_ne_zero.2 omega_ne_zero @[simp] theorem lift_omega : lift omega = omega := lift_lift _ /- properties about the cast from nat -/ @[simp] theorem mk_fin : ∀ (n : ℕ), mk (fin n) = n | 0 := quotient.sound ⟨equiv.equiv_pempty _⟩ | (n+1) := by rw [nat.cast_succ, ← mk_fin]; exact quotient.sound (fintype.card_eq.1 $ by simp) @[simp] theorem lift_nat_cast (n : ℕ) : lift n = n := by induction n; simp * lemma lift_eq_nat_iff {a : cardinal.{u}} {n : ℕ} : lift.{u v} a = n ↔ a = n := by rw [← lift_nat_cast.{u v} n, lift_inj] lemma nat_eq_lift_eq_iff {n : ℕ} {a : cardinal.{u}} : (n : cardinal) = lift.{u v} a ↔ (n : cardinal) = a := by rw [← lift_nat_cast.{u v} n, lift_inj] theorem lift_mk_fin (n : ℕ) : lift (mk (fin n)) = n := by simp theorem fintype_card (α : Type u) [fintype α] : mk α = fintype.card α := by rw [← lift_mk_fin.{u}, ← lift_id (mk α), lift_mk_eq.{u 0 u}]; exact fintype.card_eq.1 (by simp) theorem card_le_of_finset {α} (s : finset α) : (s.card : cardinal) ≤ cardinal.mk α := begin rw (_ : (s.card : cardinal) = cardinal.mk (↑s : set α)), { exact ⟨function.embedding.subtype _⟩ }, rw [cardinal.fintype_card, fintype.card_coe] end @[simp, norm_cast] theorem nat_cast_pow {m n : ℕ} : (↑(pow m n) : cardinal) = m ^ n := by induction n; simp [pow_succ', -_root_.add_comm, power_add, *] @[simp, norm_cast] theorem nat_cast_le {m n : ℕ} : (m : cardinal) ≤ n ↔ m ≤ n := by rw [← lift_mk_fin, ← lift_mk_fin, lift_le]; exact ⟨λ ⟨⟨f, hf⟩⟩, by simpa only [fintype.card_fin] using fintype.card_le_of_injective f hf, λ h, ⟨(fin.cast_le h).to_embedding⟩⟩ @[simp, norm_cast] theorem nat_cast_lt {m n : ℕ} : (m : cardinal) < n ↔ m < n := by simp [lt_iff_le_not_le, -not_le] @[simp, norm_cast] theorem nat_cast_inj {m n : ℕ} : (m : cardinal) = n ↔ m = n := by simp [le_antisymm_iff] @[simp, norm_cast, priority 900] theorem nat_succ (n : ℕ) : (n.succ : cardinal) = succ n := le_antisymm (add_one_le_succ _) (succ_le.2 $ nat_cast_lt.2 $ nat.lt_succ_self _) @[simp] theorem succ_zero : succ 0 = 1 := by norm_cast theorem card_le_of {α : Type u} {n : ℕ} (H : ∀ s : finset α, s.card ≤ n) : # α ≤ n := begin refine lt_succ.1 (lt_of_not_ge $ λ hn, _), rw [← cardinal.nat_succ, ← cardinal.lift_mk_fin n.succ] at hn, cases hn with f, refine not_lt_of_le (H $ finset.univ.map f) _, rw [finset.card_map, ← fintype.card, fintype.card_ulift, fintype.card_fin], exact n.lt_succ_self end theorem cantor' (a) {b : cardinal} (hb : 1 < b) : a < b ^ a := by rw [← succ_le, (by norm_cast : succ 1 = 2)] at hb; exact lt_of_lt_of_le (cantor _) (power_le_power_right hb) theorem one_le_iff_pos {c : cardinal} : 1 ≤ c ↔ 0 < c := by rw [← succ_zero, succ_le] theorem one_le_iff_ne_zero {c : cardinal} : 1 ≤ c ↔ c ≠ 0 := by rw [one_le_iff_pos, pos_iff_ne_zero] theorem nat_lt_omega (n : ℕ) : (n : cardinal.{u}) < omega := succ_le.1 $ by rw [← nat_succ, ← lift_mk_fin, omega, lift_mk_le.{0 0 u}]; exact ⟨⟨coe, λ a b, fin.ext⟩⟩ @[simp] theorem one_lt_omega : 1 < omega := by simpa using nat_lt_omega 1 theorem lt_omega {c : cardinal.{u}} : c < omega ↔ ∃ n : ℕ, c = n := ⟨λ h, begin rcases lt_lift_iff.1 h with ⟨c, rfl, h'⟩, rcases le_mk_iff_exists_set.1 h'.1 with ⟨S, rfl⟩, suffices : finite S, { cases this, resetI, existsi fintype.card S, rw [← lift_nat_cast.{0 u}, lift_inj, fintype_card S] }, by_contra nf, have P : ∀ (n : ℕ) (IH : ∀ i<n, S), ∃ a : S, ¬ ∃ y h, IH y h = a := λ n IH, let g : {i | i < n} → S := λ ⟨i, h⟩, IH i h in not_forall.1 (λ h, nf ⟨fintype.of_surjective g (λ a, subtype.exists.2 (h a))⟩), let F : ℕ → S := nat.lt_wf.fix (λ n IH, classical.some (P n IH)), refine not_le_of_lt h' ⟨⟨F, _⟩⟩, suffices : ∀ (n : ℕ) (m < n), F m ≠ F n, { refine λ m n, not_imp_not.1 (λ ne, _), rcases lt_trichotomy m n with h|h|h, { exact this n m h }, { contradiction }, { exact (this m n h).symm } }, intros n m h, have := classical.some_spec (P n (λ y _, F y)), rw [← show F n = classical.some (P n (λ y _, F y)), from nat.lt_wf.fix_eq (λ n IH, classical.some (P n IH)) n] at this, exact λ e, this ⟨m, h, e⟩, end, λ ⟨n, e⟩, e.symm ▸ nat_lt_omega _⟩ theorem omega_le {c : cardinal.{u}} : omega ≤ c ↔ ∀ n : ℕ, (n:cardinal) ≤ c := ⟨λ h n, le_trans (le_of_lt (nat_lt_omega _)) h, λ h, le_of_not_lt $ λ hn, begin rcases lt_omega.1 hn with ⟨n, rfl⟩, exact not_le_of_lt (nat.lt_succ_self _) (nat_cast_le.1 (h (n+1))) end⟩ theorem lt_omega_iff_fintype {α : Type u} : mk α < omega ↔ nonempty (fintype α) := lt_omega.trans ⟨λ ⟨n, e⟩, begin rw [← lift_mk_fin n] at e, cases quotient.exact e with f, exact ⟨fintype.of_equiv _ f.symm⟩ end, λ ⟨_⟩, by exactI ⟨_, fintype_card _⟩⟩ theorem lt_omega_iff_finite {α} {S : set α} : mk S < omega ↔ finite S := lt_omega_iff_fintype instance can_lift_cardinal_nat : can_lift cardinal ℕ := ⟨ coe, λ x, x < omega, λ x hx, let ⟨n, hn⟩ := lt_omega.mp hx in ⟨n, hn.symm⟩⟩ theorem add_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a + b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_add]; apply nat_lt_omega end lemma add_lt_omega_iff {a b : cardinal} : a + b < omega ↔ a < omega ∧ b < omega := ⟨λ h, ⟨lt_of_le_of_lt (self_le_add_right _ _) h, lt_of_le_of_lt (self_le_add_left _ _) h⟩, λ⟨h1, h2⟩, add_lt_omega h1 h2⟩ theorem mul_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a * b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_mul]; apply nat_lt_omega end lemma mul_lt_omega_iff {a b : cardinal} : a * b < omega ↔ a = 0 ∨ b = 0 ∨ a < omega ∧ b < omega := begin split, { intro h, by_cases ha : a = 0, { left, exact ha }, right, by_cases hb : b = 0, { left, exact hb }, right, rw [← ne, ← one_le_iff_ne_zero] at ha hb, split, { rw [← mul_one a], refine lt_of_le_of_lt (canonically_ordered_semiring.mul_le_mul (le_refl a) hb) h }, { rw [← _root_.one_mul b], refine lt_of_le_of_lt (canonically_ordered_semiring.mul_le_mul ha (le_refl b)) h }}, rintro (rfl|rfl|⟨ha,hb⟩); simp only [*, mul_lt_omega, omega_pos, _root_.zero_mul, mul_zero] end lemma mul_lt_omega_iff_of_ne_zero {a b : cardinal} (ha : a ≠ 0) (hb : b ≠ 0) : a * b < omega ↔ a < omega ∧ b < omega := by simp [mul_lt_omega_iff, ha, hb] theorem power_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a ^ b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat_cast_pow]; apply nat_lt_omega end lemma eq_one_iff_unique {α : Type*} : mk α = 1 ↔ subsingleton α ∧ nonempty α := calc mk α = 1 ↔ mk α ≤ 1 ∧ ¬mk α < 1 : eq_iff_le_not_lt ... ↔ subsingleton α ∧ nonempty α : begin apply and_congr le_one_iff_subsingleton, push_neg, rw [one_le_iff_ne_zero, ne_zero_iff_nonempty] end theorem infinite_iff {α : Type u} : infinite α ↔ omega ≤ mk α := by rw [←not_lt, lt_omega_iff_fintype, not_nonempty_fintype] lemma denumerable_iff {α : Type u} : nonempty (denumerable α) ↔ mk α = omega := ⟨λ⟨h⟩, quotient.sound $ by exactI ⟨ (denumerable.eqv α).trans equiv.ulift.symm ⟩, λ h, by { cases quotient.exact h with f, exact ⟨denumerable.mk' $ f.trans equiv.ulift⟩ }⟩ lemma countable_iff (s : set α) : countable s ↔ mk s ≤ omega := begin rw [countable_iff_exists_injective], split, rintro ⟨f, hf⟩, exact ⟨embedding.trans ⟨f, hf⟩ equiv.ulift.symm.to_embedding⟩, rintro ⟨f'⟩, cases embedding.trans f' equiv.ulift.to_embedding with f hf, exact ⟨f, hf⟩ end /-- This function sends finite cardinals to the corresponding natural, and infinite cardinals to 0. -/ noncomputable def to_nat : zero_hom cardinal ℕ := ⟨λ c, if h : c < omega.{v} then classical.some (lt_omega.1 h) else 0, begin have h : 0 < omega := nat_lt_omega 0, rw [dif_pos h, ← cardinal.nat_cast_inj, ← classical.some_spec (lt_omega.1 h), nat.cast_zero], end⟩ lemma to_nat_apply_of_lt_omega {c : cardinal} (h : c < omega) : c.to_nat = classical.some (lt_omega.1 h) := dif_pos h @[simp] lemma to_nat_apply_of_omega_le {c : cardinal} (h : omega ≤ c) : c.to_nat = 0 := dif_neg (not_lt_of_le h) @[simp] lemma cast_to_nat_of_lt_omega {c : cardinal} (h : c < omega) : ↑c.to_nat = c := by rw [to_nat_apply_of_lt_omega h, ← classical.some_spec (lt_omega.1 h)] @[simp] lemma to_nat_cast (n : ℕ) : cardinal.to_nat n = n := begin rw [to_nat_apply_of_lt_omega (nat_lt_omega n), ← nat_cast_inj], exact (classical.some_spec (lt_omega.1 (nat_lt_omega n))).symm, end /-- `to_nat` has a right-inverse: coercion. -/ lemma to_nat_right_inverse : function.right_inverse (coe : ℕ → cardinal) to_nat := to_nat_cast lemma to_nat_surjective : surjective to_nat := to_nat_right_inverse.surjective @[simp] lemma mk_to_nat_of_infinite [h : infinite α] : (mk α).to_nat = 0 := dif_neg (not_lt_of_le (infinite_iff.1 h)) @[simp] lemma mk_to_nat_eq_card [fintype α] : (mk α).to_nat = fintype.card α := by simp [fintype_card] @[simp] lemma zero_to_nat : cardinal.to_nat 0 = 0 := by rw [← to_nat_cast 0, nat.cast_zero] @[simp] lemma one_to_nat : cardinal.to_nat 1 = 1 := by rw [← to_nat_cast 1, nat.cast_one] /-- This function sends finite cardinals to the corresponding natural, and infinite cardinals to `⊤`. -/ noncomputable def to_enat : cardinal →+ enat := { to_fun := λ c, if c < omega.{v} then c.to_nat else ⊤, map_zero' := by simp [if_pos (lt_trans zero_lt_one one_lt_omega)], map_add' := λ x y, begin by_cases hx : x < omega, { obtain ⟨x0, rfl⟩ := lt_omega.1 hx, by_cases hy : y < omega, { obtain ⟨y0, rfl⟩ := lt_omega.1 hy, simp only [add_lt_omega hx hy, hx, hy, to_nat_cast, if_true], rw [← nat.cast_add, to_nat_cast, enat.coe_add] }, { rw [if_neg hy, if_neg, enat.add_top], contrapose! hy, apply lt_of_le_of_lt le_add_self hy } }, { rw [if_neg hx, if_neg, enat.top_add], contrapose! hx, apply lt_of_le_of_lt le_self_add hx }, end } @[simp] lemma to_enat_apply_of_lt_omega {c : cardinal} (h : c < omega) : c.to_enat = c.to_nat := if_pos h @[simp] lemma to_enat_apply_of_omega_le {c : cardinal} (h : omega ≤ c) : c.to_enat = ⊤ := if_neg (not_lt_of_le h) @[simp] lemma to_enat_cast (n : ℕ) : cardinal.to_enat n = n := by rw [to_enat_apply_of_lt_omega (nat_lt_omega n), to_nat_cast] @[simp] lemma mk_to_enat_of_infinite [h : infinite α] : (mk α).to_enat = ⊤ := to_enat_apply_of_omega_le (infinite_iff.1 h) lemma to_enat_surjective : surjective to_enat := begin intro x, exact enat.cases_on x ⟨omega, to_enat_apply_of_omega_le (le_refl omega)⟩ (λ n, ⟨n, to_enat_cast n⟩), end @[simp] lemma mk_to_enat_eq_coe_card [fintype α] : (mk α).to_enat = fintype.card α := by simp [fintype_card] lemma mk_int : mk ℤ = omega := denumerable_iff.mp ⟨by apply_instance⟩ lemma mk_pnat : mk ℕ+ = omega := denumerable_iff.mp ⟨by apply_instance⟩ lemma two_le_iff : (2 : cardinal) ≤ mk α ↔ ∃x y : α, x ≠ y := begin split, { rintro ⟨f⟩, refine ⟨f $ sum.inl ⟨⟩, f $ sum.inr ⟨⟩, _⟩, intro h, cases f.2 h }, { rintro ⟨x, y, h⟩, by_contra h', rw [not_le, ←nat.cast_two, nat_succ, lt_succ, nat.cast_one, le_one_iff_subsingleton] at h', apply h, exactI subsingleton.elim _ _ } end lemma two_le_iff' (x : α) : (2 : cardinal) ≤ mk α ↔ ∃y : α, x ≠ y := begin rw [two_le_iff], split, { rintro ⟨y, z, h⟩, refine classical.by_cases (λ(h' : x = y), _) (λ h', ⟨y, h'⟩), rw [←h'] at h, exact ⟨z, h⟩ }, { rintro ⟨y, h⟩, exact ⟨x, y, h⟩ } end /-- König's theorem -/ theorem sum_lt_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i < g i) : sum f < prod g := lt_of_not_ge $ λ ⟨F⟩, begin have : inhabited (Π (i : ι), (g i).out), { refine ⟨λ i, classical.choice $ ne_zero_iff_nonempty.1 _⟩, rw mk_out, exact ne_of_gt (lt_of_le_of_lt (zero_le _) (H i)) }, resetI, let G := inv_fun F, have sG : surjective G := inv_fun_surjective F.2, choose C hc using show ∀ i, ∃ b, ∀ a, G ⟨i, a⟩ i ≠ b, { assume i, simp only [- not_exists, not_exists.symm, not_forall.symm], refine λ h, not_le_of_lt (H i) _, rw [← mk_out (f i), ← mk_out (g i)], exact ⟨embedding.of_surjective _ h⟩ }, exact (let ⟨⟨i, a⟩, h⟩ := sG C in hc i a (congr_fun h _)) end @[simp] theorem mk_empty : mk empty = 0 := fintype_card empty @[simp] theorem mk_pempty : mk pempty = 0 := fintype_card pempty @[simp] theorem mk_plift_of_false {p : Prop} (h : ¬ p) : mk (plift p) = 0 := by { haveI : is_empty p := ⟨h⟩, exact quotient.sound ⟨equiv.plift.trans $ equiv.equiv_pempty _⟩ } theorem mk_unit : mk unit = 1 := (fintype_card unit).trans nat.cast_one @[simp] theorem mk_punit : mk punit = 1 := (fintype_card punit).trans nat.cast_one @[simp] theorem mk_singleton {α : Type u} (x : α) : mk ({x} : set α) = 1 := quotient.sound ⟨equiv.set.singleton x⟩ @[simp] theorem mk_plift_of_true {p : Prop} (h : p) : mk (plift p) = 1 := quotient.sound ⟨equiv.plift.trans $ equiv.prop_equiv_punit h⟩ @[simp] theorem mk_bool : mk bool = 2 := quotient.sound ⟨equiv.bool_equiv_punit_sum_punit⟩ @[simp] theorem mk_Prop : mk Prop = 2 := (quotient.sound ⟨equiv.Prop_equiv_bool⟩ : mk Prop = mk bool).trans mk_bool @[simp] theorem mk_set {α : Type u} : mk (set α) = 2 ^ mk α := begin rw [← prop_eq_two, cardinal.power_def (ulift Prop) α, cardinal.eq], exact ⟨equiv.arrow_congr (equiv.refl _) equiv.ulift.symm⟩, end @[simp] theorem mk_option {α : Type u} : mk (option α) = mk α + 1 := quotient.sound ⟨equiv.option_equiv_sum_punit α⟩ theorem mk_list_eq_sum_pow (α : Type u) : mk (list α) = sum (λ n : ℕ, (mk α)^(n:cardinal.{u})) := calc mk (list α) = mk (Σ n, vector α n) : quotient.sound ⟨(equiv.sigma_preimage_equiv list.length).symm⟩ ... = mk (Σ n, fin n → α) : quotient.sound ⟨equiv.sigma_congr_right $ λ n, ⟨vector.nth, vector.of_fn, vector.of_fn_nth, λ f, funext $ vector.nth_of_fn f⟩⟩ ... = mk (Σ n : ℕ, ulift.{u} (fin n) → α) : quotient.sound ⟨equiv.sigma_congr_right $ λ n, equiv.arrow_congr equiv.ulift.symm (equiv.refl α)⟩ ... = sum (λ n : ℕ, (mk α)^(n:cardinal.{u})) : by simp only [(lift_mk_fin _).symm, lift_mk, power_def, sum_mk] theorem mk_quot_le {α : Type u} {r : α → α → Prop} : mk (quot r) ≤ mk α := mk_le_of_surjective quot.exists_rep theorem mk_quotient_le {α : Type u} {s : setoid α} : mk (quotient s) ≤ mk α := mk_quot_le theorem mk_subtype_le {α : Type u} (p : α → Prop) : mk (subtype p) ≤ mk α := ⟨embedding.subtype p⟩ theorem mk_subtype_le_of_subset {α : Type u} {p q : α → Prop} (h : ∀ ⦃x⦄, p x → q x) : mk (subtype p) ≤ mk (subtype q) := ⟨embedding.subtype_map (embedding.refl α) h⟩ @[simp] theorem mk_emptyc (α : Type u) : mk (∅ : set α) = 0 := quotient.sound ⟨equiv.set.pempty α⟩ lemma mk_emptyc_iff {α : Type u} {s : set α} : mk s = 0 ↔ s = ∅ := begin split, { intro h, have h2 : cardinal.mk s = cardinal.mk pempty, by simp [h], refine set.eq_empty_iff_forall_not_mem.mpr (λ _ hx, _), rcases cardinal.eq.mp h2 with ⟨f, _⟩, cases f ⟨_, hx⟩ }, { intro, convert mk_emptyc _ } end theorem mk_univ {α : Type u} : mk (@univ α) = mk α := quotient.sound ⟨equiv.set.univ α⟩ theorem mk_image_le {α β : Type u} {f : α → β} {s : set α} : mk (f '' s) ≤ mk s := mk_le_of_surjective surjective_onto_image theorem mk_image_le_lift {α : Type u} {β : Type v} {f : α → β} {s : set α} : lift.{v u} (mk (f '' s)) ≤ lift.{u v} (mk s) := lift_mk_le.{v u 0}.mpr ⟨embedding.of_surjective _ surjective_onto_image⟩ theorem mk_range_le {α β : Type u} {f : α → β} : mk (range f) ≤ mk α := mk_le_of_surjective surjective_onto_range lemma mk_range_eq (f : α → β) (h : injective f) : mk (range f) = mk α := quotient.sound ⟨(equiv.of_injective f h).symm⟩ lemma mk_range_eq_of_injective {α : Type u} {β : Type v} {f : α → β} (hf : injective f) : lift.{v u} (mk (range f)) = lift.{u v} (mk α) := begin have := (@lift_mk_eq.{v u max u v} (range f) α).2 ⟨(equiv.of_injective f hf).symm⟩, simp only [lift_umax.{u v}, lift_umax.{v u}] at this, exact this end lemma mk_range_eq_lift {α : Type u} {β : Type v} {f : α → β} (hf : injective f) : lift.{v (max u w)} (# (range f)) = lift.{u (max v w)} (# α) := lift_mk_eq.mpr ⟨(equiv.of_injective f hf).symm⟩ theorem mk_image_eq {α β : Type u} {f : α → β} {s : set α} (hf : injective f) : mk (f '' s) = mk s := quotient.sound ⟨(equiv.set.image f s hf).symm⟩ theorem mk_Union_le_sum_mk {α ι : Type u} {f : ι → set α} : mk (⋃ i, f i) ≤ sum (λ i, mk (f i)) := calc mk (⋃ i, f i) ≤ mk (Σ i, f i) : mk_le_of_surjective (set.sigma_to_Union_surjective f) ... = sum (λ i, mk (f i)) : (sum_mk _).symm theorem mk_Union_eq_sum_mk {α ι : Type u} {f : ι → set α} (h : ∀i j, i ≠ j → disjoint (f i) (f j)) : mk (⋃ i, f i) = sum (λ i, mk (f i)) := calc mk (⋃ i, f i) = mk (Σi, f i) : quot.sound ⟨set.Union_eq_sigma_of_disjoint h⟩ ... = sum (λi, mk (f i)) : (sum_mk _).symm lemma mk_Union_le {α ι : Type u} (f : ι → set α) : mk (⋃ i, f i) ≤ mk ι * cardinal.sup.{u u} (λ i, mk (f i)) := le_trans mk_Union_le_sum_mk (sum_le_sup _) lemma mk_sUnion_le {α : Type u} (A : set (set α)) : mk (⋃₀ A) ≤ mk A * cardinal.sup.{u u} (λ s : A, mk s) := by { rw [sUnion_eq_Union], apply mk_Union_le } lemma mk_bUnion_le {ι α : Type u} (A : ι → set α) (s : set ι) : mk (⋃(x ∈ s), A x) ≤ mk s * cardinal.sup.{u u} (λ x : s, mk (A x.1)) := by { rw [bUnion_eq_Union], apply mk_Union_le } @[simp] lemma finset_card {α : Type u} {s : finset α} : ↑(finset.card s) = mk (↑s : set α) := by rw [fintype_card, nat_cast_inj, fintype.card_coe] lemma finset_card_lt_omega (s : finset α) : mk (↑s : set α) < omega := by { rw [lt_omega_iff_fintype], exact ⟨finset.subtype.fintype s⟩ } theorem mk_eq_nat_iff_finset {α} {s : set α} {n : ℕ} : mk s = n ↔ ∃ t : finset α, (t : set α) = s ∧ t.card = n := begin split, { intro h, have : # s < omega, by { rw h, exact nat_lt_omega n }, refine ⟨(lt_omega_iff_finite.1 this).to_finset, finite.coe_to_finset _, nat_cast_inj.1 _⟩, rwa [finset_card, finite.coe_to_finset] }, { rintro ⟨t, rfl, rfl⟩, exact finset_card.symm } end theorem mk_union_add_mk_inter {α : Type u} {S T : set α} : mk (S ∪ T : set α) + mk (S ∩ T : set α) = mk S + mk T := quot.sound ⟨equiv.set.union_sum_inter S T⟩ /-- The cardinality of a union is at most the sum of the cardinalities of the two sets. -/ lemma mk_union_le {α : Type u} (S T : set α) : mk (S ∪ T : set α) ≤ mk S + mk T := @mk_union_add_mk_inter α S T ▸ self_le_add_right (mk (S ∪ T : set α)) (mk (S ∩ T : set α)) theorem mk_union_of_disjoint {α : Type u} {S T : set α} (H : disjoint S T) : mk (S ∪ T : set α) = mk S + mk T := quot.sound ⟨equiv.set.union H⟩ lemma mk_sum_compl {α} (s : set α) : #s + #(sᶜ : set α) = #α := quotient.sound ⟨equiv.set.sum_compl s⟩ lemma mk_le_mk_of_subset {α} {s t : set α} (h : s ⊆ t) : mk s ≤ mk t := ⟨set.embedding_of_subset s t h⟩ lemma mk_subtype_mono {p q : α → Prop} (h : ∀x, p x → q x) : mk {x // p x} ≤ mk {x // q x} := ⟨embedding_of_subset _ _ h⟩ lemma mk_set_le (s : set α) : mk s ≤ mk α := mk_subtype_le s lemma mk_image_eq_lift {α : Type u} {β : Type v} (f : α → β) (s : set α) (h : injective f) : lift.{v u} (mk (f '' s)) = lift.{u v} (mk s) := lift_mk_eq.{v u 0}.mpr ⟨(equiv.set.image f s h).symm⟩ lemma mk_image_eq_of_inj_on_lift {α : Type u} {β : Type v} (f : α → β) (s : set α) (h : inj_on f s) : lift.{v u} (mk (f '' s)) = lift.{u v} (mk s) := lift_mk_eq.{v u 0}.mpr ⟨(equiv.set.image_of_inj_on f s h).symm⟩ lemma mk_image_eq_of_inj_on {α β : Type u} (f : α → β) (s : set α) (h : inj_on f s) : mk (f '' s) = mk s := quotient.sound ⟨(equiv.set.image_of_inj_on f s h).symm⟩ lemma mk_subtype_of_equiv {α β : Type u} (p : β → Prop) (e : α ≃ β) : mk {a : α // p (e a)} = mk {b : β // p b} := quotient.sound ⟨equiv.subtype_equiv_of_subtype e⟩ lemma mk_sep (s : set α) (t : α → Prop) : mk ({ x ∈ s | t x } : set α) = mk { x : s | t x.1 } := quotient.sound ⟨equiv.set.sep s t⟩ lemma mk_preimage_of_injective_lift {α : Type u} {β : Type v} (f : α → β) (s : set β) (h : injective f) : lift.{u v} (mk (f ⁻¹' s)) ≤ lift.{v u} (mk s) := begin rw lift_mk_le.{u v 0}, use subtype.coind (λ x, f x.1) (λ x, x.2), apply subtype.coind_injective, exact h.comp subtype.val_injective end lemma mk_preimage_of_subset_range_lift {α : Type u} {β : Type v} (f : α → β) (s : set β) (h : s ⊆ range f) : lift.{v u} (mk s) ≤ lift.{u v} (mk (f ⁻¹' s)) := begin rw lift_mk_le.{v u 0}, refine ⟨⟨_, _⟩⟩, { rintro ⟨y, hy⟩, rcases classical.subtype_of_exists (h hy) with ⟨x, rfl⟩, exact ⟨x, hy⟩ }, rintro ⟨y, hy⟩ ⟨y', hy'⟩, dsimp, rcases classical.subtype_of_exists (h hy) with ⟨x, rfl⟩, rcases classical.subtype_of_exists (h hy') with ⟨x', rfl⟩, simp, intro hxx', rw hxx' end lemma mk_preimage_of_injective_of_subset_range_lift {β : Type v} (f : α → β) (s : set β) (h : injective f) (h2 : s ⊆ range f) : lift.{u v} (mk (f ⁻¹' s)) = lift.{v u} (mk s) := le_antisymm (mk_preimage_of_injective_lift f s h) (mk_preimage_of_subset_range_lift f s h2) lemma mk_preimage_of_injective (f : α → β) (s : set β) (h : injective f) : mk (f ⁻¹' s) ≤ mk s := by { convert mk_preimage_of_injective_lift.{u u} f s h using 1; rw [lift_id] } lemma mk_preimage_of_subset_range (f : α → β) (s : set β) (h : s ⊆ range f) : mk s ≤ mk (f ⁻¹' s) := by { convert mk_preimage_of_subset_range_lift.{u u} f s h using 1; rw [lift_id] } lemma mk_preimage_of_injective_of_subset_range (f : α → β) (s : set β) (h : injective f) (h2 : s ⊆ range f) : mk (f ⁻¹' s) = mk s := by { convert mk_preimage_of_injective_of_subset_range_lift.{u u} f s h h2 using 1; rw [lift_id] } lemma mk_subset_ge_of_subset_image_lift {α : Type u} {β : Type v} (f : α → β) {s : set α} {t : set β} (h : t ⊆ f '' s) : lift.{v u} (mk t) ≤ lift.{u v} (mk ({ x ∈ s | f x ∈ t } : set α)) := by { rw [image_eq_range] at h, convert mk_preimage_of_subset_range_lift _ _ h using 1, rw [mk_sep], refl } lemma mk_subset_ge_of_subset_image (f : α → β) {s : set α} {t : set β} (h : t ⊆ f '' s) : mk t ≤ mk ({ x ∈ s | f x ∈ t } : set α) := by { rw [image_eq_range] at h, convert mk_preimage_of_subset_range _ _ h using 1, rw [mk_sep], refl } theorem le_mk_iff_exists_subset {c : cardinal} {α : Type u} {s : set α} : c ≤ mk s ↔ ∃ p : set α, p ⊆ s ∧ mk p = c := begin rw [le_mk_iff_exists_set, ←subtype.exists_set_subtype], apply exists_congr, intro t, rw [mk_image_eq], apply subtype.val_injective end /-- The function α^{<β}, defined to be sup_{γ < β} α^γ. We index over {s : set β.out // mk s < β } instead of {γ // γ < β}, because the latter lives in a higher universe -/ noncomputable def powerlt (α β : cardinal.{u}) : cardinal.{u} := sup.{u u} (λ(s : {s : set β.out // mk s < β}), α ^ mk.{u} s) infix ` ^< `:80 := powerlt theorem powerlt_aux {c c' : cardinal} (h : c < c') : ∃(s : {s : set c'.out // mk s < c'}), mk s = c := begin cases out_embedding.mp (le_of_lt h) with f, have : mk ↥(range ⇑f) = c, { rwa [mk_range_eq, mk, quotient.out_eq c], exact f.2 }, exact ⟨⟨range f, by convert h⟩, this⟩ end lemma le_powerlt {c₁ c₂ c₃ : cardinal} (h : c₂ < c₃) : c₁ ^ c₂ ≤ c₁ ^< c₃ := by { rcases powerlt_aux h with ⟨s, rfl⟩, apply le_sup _ s } lemma powerlt_le {c₁ c₂ c₃ : cardinal} : c₁ ^< c₂ ≤ c₃ ↔ ∀(c₄ < c₂), c₁ ^ c₄ ≤ c₃ := begin rw [powerlt, sup_le], split, { intros h c₄ hc₄, rcases powerlt_aux hc₄ with ⟨s, rfl⟩, exact h s }, intros h s, exact h _ s.2 end lemma powerlt_le_powerlt_left {a b c : cardinal} (h : b ≤ c) : a ^< b ≤ a ^< c := by { rw [powerlt, sup_le], rintro ⟨s, hs⟩, apply le_powerlt, exact lt_of_lt_of_le hs h } lemma powerlt_succ {c₁ c₂ : cardinal} (h : c₁ ≠ 0) : c₁ ^< c₂.succ = c₁ ^ c₂ := begin apply le_antisymm, { rw powerlt_le, intros c₃ h2, apply power_le_power_left h, rwa [←lt_succ] }, { apply le_powerlt, apply lt_succ_self } end lemma powerlt_max {c₁ c₂ c₃ : cardinal} : c₁ ^< max c₂ c₃ = max (c₁ ^< c₂) (c₁ ^< c₃) := by { cases le_total c₂ c₃; simp only [max_eq_left, max_eq_right, h, powerlt_le_powerlt_left] } lemma zero_powerlt {a : cardinal} (h : a ≠ 0) : 0 ^< a = 1 := begin apply le_antisymm, { rw [powerlt_le], intros c hc, apply zero_power_le }, convert le_powerlt (pos_iff_ne_zero.2 h), rw [power_zero] end lemma powerlt_zero {a : cardinal} : a ^< 0 = 0 := by { apply sup_eq_zero, rintro ⟨x, hx⟩, rw [←not_le] at hx, apply hx, apply zero_le } end cardinal lemma equiv.cardinal_eq {α β} : α ≃ β → cardinal.mk α = cardinal.mk β := cardinal.eq_congr
9f70bd94ae5d35e5ea0908fd40b28464cacb4a07
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/pointwise.lean
16fb91cd128e6642a48f51091e25717d9e215b0b
[]
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
18,265
lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Floris van Doorn -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.module.basic import Mathlib.data.set.finite import Mathlib.group_theory.submonoid.basic import Mathlib.PostPort universes u_1 u_2 u_3 u_4 namespace Mathlib /-! # Pointwise addition, multiplication, and scalar multiplication of sets. This file defines pointwise algebraic operations on sets. * For a type `α` with multiplication, multiplication is defined on `set α` by taking `s * t` to be the set of all `x * y` where `x ∈ s` and `y ∈ t`. Similarly for addition. * For `α` a semigroup, `set α` is a semigroup. * If `α` is a (commutative) monoid, we define an alias `set_semiring α` for `set α`, which then becomes a (commutative) semiring with union as addition and pointwise multiplication as multiplication. * For a type `β` with scalar multiplication by another type `α`, this file defines a scalar multiplication of `set β` by `set α` and a separate scalar multiplication of `set β` by `α`. * We also define pointwise multiplication on `finset`. Appropriate definitions and results are also transported to the additive theory via `to_additive`. ## Implementation notes * The following expressions are considered in simp-normal form in a group: `(λ h, h * g) ⁻¹' s`, `(λ h, g * h) ⁻¹' s`, `(λ h, h * g⁻¹) ⁻¹' s`, `(λ h, g⁻¹ * h) ⁻¹' s`, `s * t`, `s⁻¹`, `(1 : set _)` (and similarly for additive variants). Expressions equal to one of these will be simplified. ## Tags set multiplication, set addition, pointwise addition, pointwise multiplication -/ namespace set /-! ### Properties about 1 -/ protected instance has_one {α : Type u_1} [HasOne α] : HasOne (set α) := { one := singleton 1 } theorem singleton_one {α : Type u_1} [HasOne α] : singleton 1 = 1 := rfl @[simp] theorem mem_zero {α : Type u_1} {a : α} [HasZero α] : a ∈ 0 ↔ a = 0 := iff.rfl theorem one_mem_one {α : Type u_1} [HasOne α] : 1 ∈ 1 := Eq.refl 1 @[simp] theorem zero_subset {α : Type u_1} {s : set α} [HasZero α] : 0 ⊆ s ↔ 0 ∈ s := singleton_subset_iff theorem zero_nonempty {α : Type u_1} [HasZero α] : set.nonempty 0 := Exists.intro 0 rfl @[simp] theorem image_zero {α : Type u_1} {β : Type u_2} [HasZero α] {f : α → β} : f '' 0 = singleton (f 0) := image_singleton /-! ### Properties about multiplication -/ protected instance has_add {α : Type u_1} [Add α] : Add (set α) := { add := image2 Add.add } @[simp] theorem image2_mul {α : Type u_1} {s : set α} {t : set α} [Mul α] : image2 Mul.mul s t = s * t := rfl theorem mem_add {α : Type u_1} {s : set α} {t : set α} {a : α} [Add α] : a ∈ s + t ↔ ∃ (x : α), ∃ (y : α), x ∈ s ∧ y ∈ t ∧ x + y = a := iff.rfl theorem mul_mem_mul {α : Type u_1} {s : set α} {t : set α} {a : α} {b : α} [Mul α] (ha : a ∈ s) (hb : b ∈ t) : a * b ∈ s * t := mem_image2_of_mem ha hb theorem add_image_prod {α : Type u_1} {s : set α} {t : set α} [Add α] : (fun (x : α × α) => prod.fst x + prod.snd x) '' set.prod s t = s + t := image_prod Add.add @[simp] theorem image_mul_left {α : Type u_1} {t : set α} {a : α} [group α] : (fun (b : α) => a * b) '' t = (fun (b : α) => a⁻¹ * b) ⁻¹' t := sorry @[simp] theorem image_add_right {α : Type u_1} {t : set α} {b : α} [add_group α] : (fun (a : α) => a + b) '' t = (fun (a : α) => a + -b) ⁻¹' t := sorry theorem image_add_left' {α : Type u_1} {t : set α} {a : α} [add_group α] : (fun (b : α) => -a + b) '' t = (fun (b : α) => a + b) ⁻¹' t := sorry theorem image_mul_right' {α : Type u_1} {t : set α} {b : α} [group α] : (fun (a : α) => a * (b⁻¹)) '' t = (fun (a : α) => a * b) ⁻¹' t := sorry @[simp] theorem preimage_add_left_singleton {α : Type u_1} {a : α} {b : α} [add_group α] : Add.add a ⁻¹' singleton b = singleton (-a + b) := eq.mpr (id (Eq._oldrec (Eq.refl (Add.add a ⁻¹' singleton b = singleton (-a + b))) (Eq.symm image_add_left'))) (eq.mpr (id (Eq._oldrec (Eq.refl ((fun (b : α) => -a + b) '' singleton b = singleton (-a + b))) image_singleton)) (Eq.refl (singleton (-a + b)))) @[simp] theorem preimage_mul_right_singleton {α : Type u_1} {a : α} {b : α} [group α] : (fun (_x : α) => _x * a) ⁻¹' singleton b = singleton (b * (a⁻¹)) := sorry @[simp] theorem preimage_add_left_zero {α : Type u_1} {a : α} [add_group α] : (fun (b : α) => a + b) ⁻¹' 0 = singleton (-a) := sorry @[simp] theorem preimage_mul_right_one {α : Type u_1} {b : α} [group α] : (fun (a : α) => a * b) ⁻¹' 1 = singleton (b⁻¹) := sorry theorem preimage_add_left_zero' {α : Type u_1} {a : α} [add_group α] : (fun (b : α) => -a + b) ⁻¹' 0 = singleton a := sorry theorem preimage_add_right_zero' {α : Type u_1} {b : α} [add_group α] : (fun (a : α) => a + -b) ⁻¹' 0 = singleton b := sorry @[simp] theorem mul_singleton {α : Type u_1} {s : set α} {b : α} [Mul α] : s * singleton b = (fun (a : α) => a * b) '' s := image2_singleton_right @[simp] theorem singleton_add {α : Type u_1} {t : set α} {a : α} [Add α] : singleton a + t = (fun (b : α) => a + b) '' t := image2_singleton_left @[simp] theorem singleton_add_singleton {α : Type u_1} {a : α} {b : α} [Add α] : singleton a + singleton b = singleton (a + b) := image2_singleton protected instance semigroup {α : Type u_1} [semigroup α] : semigroup (set α) := semigroup.mk Mul.mul sorry protected instance monoid {α : Type u_1} [monoid α] : monoid (set α) := monoid.mk semigroup.mul sorry 1 sorry sorry protected theorem mul_comm {α : Type u_1} {s : set α} {t : set α} [comm_semigroup α] : s * t = t * s := sorry protected instance add_comm_monoid {α : Type u_1} [add_comm_monoid α] : add_comm_monoid (set α) := add_comm_monoid.mk add_monoid.add sorry add_monoid.zero sorry sorry sorry theorem singleton.is_mul_hom {α : Type u_1} [Mul α] : is_mul_hom singleton := is_mul_hom.mk fun (a b : α) => Eq.symm singleton_mul_singleton @[simp] theorem empty_add {α : Type u_1} {s : set α} [Add α] : ∅ + s = ∅ := image2_empty_left @[simp] theorem mul_empty {α : Type u_1} {s : set α} [Mul α] : s * ∅ = ∅ := image2_empty_right theorem add_subset_add {α : Type u_1} {s₁ : set α} {s₂ : set α} {t₁ : set α} {t₂ : set α} [Add α] (h₁ : s₁ ⊆ t₁) (h₂ : s₂ ⊆ t₂) : s₁ + s₂ ⊆ t₁ + t₂ := image2_subset h₁ h₂ theorem union_add {α : Type u_1} {s : set α} {t : set α} {u : set α} [Add α] : s ∪ t + u = s + u ∪ (t + u) := image2_union_left theorem mul_union {α : Type u_1} {s : set α} {t : set α} {u : set α} [Mul α] : s * (t ∪ u) = s * t ∪ s * u := image2_union_right theorem Union_mul_left_image {α : Type u_1} {s : set α} {t : set α} [Mul α] : (Union fun (a : α) => Union fun (H : a ∈ s) => (fun (x : α) => a * x) '' t) = s * t := Union_image_left fun (a x : α) => a * x theorem Union_mul_right_image {α : Type u_1} {s : set α} {t : set α} [Mul α] : (Union fun (a : α) => Union fun (H : a ∈ t) => (fun (x : α) => x * a) '' s) = s * t := Union_image_right fun (x a : α) => x * a @[simp] theorem univ_mul_univ {α : Type u_1} [monoid α] : univ * univ = univ := sorry /-- `singleton` is a monoid hom. -/ def singleton_add_hom {α : Type u_1} [add_monoid α] : α →+ set α := add_monoid_hom.mk singleton sorry sorry theorem nonempty.add {α : Type u_1} {s : set α} {t : set α} [Add α] : set.nonempty s → set.nonempty t → set.nonempty (s + t) := nonempty.image2 theorem finite.mul {α : Type u_1} {s : set α} {t : set α} [Mul α] (hs : finite s) (ht : finite t) : finite (s * t) := finite.image2 (fun (a b : α) => a * b) hs ht /-- multiplication preserves finiteness -/ def fintype_mul {α : Type u_1} [Mul α] [DecidableEq α] (s : set α) (t : set α) [hs : fintype ↥s] [ht : fintype ↥t] : fintype ↥(s * t) := set.fintype_image2 (fun (a b : α) => a * b) s t theorem bdd_above_add {α : Type u_1} [ordered_add_comm_monoid α] {A : set α} {B : set α} : bdd_above A → bdd_above B → bdd_above (A + B) := sorry /-! ### Properties about inversion -/ protected instance has_inv {α : Type u_1} [has_inv α] : has_inv (set α) := has_inv.mk (preimage has_inv.inv) @[simp] theorem mem_inv {α : Type u_1} {s : set α} {a : α} [has_inv α] : a ∈ (s⁻¹) ↔ a⁻¹ ∈ s := iff.rfl theorem inv_mem_inv {α : Type u_1} {s : set α} {a : α} [group α] : a⁻¹ ∈ (s⁻¹) ↔ a ∈ s := sorry @[simp] theorem inv_preimage {α : Type u_1} {s : set α} [has_inv α] : has_inv.inv ⁻¹' s = (s⁻¹) := rfl @[simp] theorem image_inv {α : Type u_1} {s : set α} [group α] : has_inv.inv '' s = (s⁻¹) := sorry @[simp] theorem inter_neg {α : Type u_1} {s : set α} {t : set α} [Neg α] : -(s ∩ t) = -s ∩ -t := preimage_inter @[simp] theorem union_neg {α : Type u_1} {s : set α} {t : set α} [Neg α] : -(s ∪ t) = -s ∪ -t := preimage_union @[simp] theorem compl_inv {α : Type u_1} {s : set α} [has_inv α] : sᶜ⁻¹ = (s⁻¹ᶜ) := preimage_compl @[simp] protected theorem inv_inv {α : Type u_1} {s : set α} [group α] : s⁻¹⁻¹ = s := sorry @[simp] protected theorem univ_inv {α : Type u_1} [group α] : univ⁻¹ = univ := preimage_univ @[simp] theorem neg_subset_neg {α : Type u_1} [add_group α] {s : set α} {t : set α} : -s ⊆ -t ↔ s ⊆ t := function.surjective.preimage_subset_preimage_iff (equiv.surjective (equiv.neg α)) theorem neg_subset {α : Type u_1} [add_group α] {s : set α} {t : set α} : -s ⊆ t ↔ s ⊆ -t := eq.mpr (id (Eq._oldrec (Eq.refl (-s ⊆ t ↔ s ⊆ -t)) (Eq.symm (propext neg_subset_neg)))) (eq.mpr (id (Eq._oldrec (Eq.refl ( --s ⊆ -t ↔ s ⊆ -t)) set.neg_neg)) (iff.refl (s ⊆ -t))) /-! ### Properties about scalar multiplication -/ /-- Scaling a set: multiplying every element by a scalar. -/ protected instance has_scalar_set {α : Type u_1} {β : Type u_2} [has_scalar α β] : has_scalar α (set β) := has_scalar.mk fun (a : α) => image (has_scalar.smul a) @[simp] theorem image_smul {α : Type u_1} {β : Type u_2} {a : α} [has_scalar α β] {t : set β} : (fun (x : β) => a • x) '' t = a • t := rfl theorem mem_smul_set {α : Type u_1} {β : Type u_2} {a : α} {x : β} [has_scalar α β] {t : set β} : x ∈ a • t ↔ ∃ (y : β), y ∈ t ∧ a • y = x := iff.rfl theorem smul_mem_smul_set {α : Type u_1} {β : Type u_2} {a : α} {y : β} [has_scalar α β] {t : set β} (hy : y ∈ t) : a • y ∈ a • t := Exists.intro y { left := hy, right := rfl } theorem smul_set_union {α : Type u_1} {β : Type u_2} {a : α} [has_scalar α β] {s : set β} {t : set β} : a • (s ∪ t) = a • s ∪ a • t := sorry @[simp] theorem smul_set_empty {α : Type u_1} {β : Type u_2} [has_scalar α β] (a : α) : a • ∅ = ∅ := eq.mpr (id (Eq._oldrec (Eq.refl (a • ∅ = ∅)) (Eq.symm image_smul))) (eq.mpr (id (Eq._oldrec (Eq.refl ((fun (x : β) => a • x) '' ∅ = ∅)) (image_empty fun (x : β) => a • x))) (Eq.refl ∅)) theorem smul_set_mono {α : Type u_1} {β : Type u_2} {a : α} [has_scalar α β] {s : set β} {t : set β} (h : s ⊆ t) : a • s ⊆ a • t := sorry /-- Pointwise scalar multiplication by a set of scalars. -/ protected instance has_scalar {α : Type u_1} {β : Type u_2} [has_scalar α β] : has_scalar (set α) (set β) := has_scalar.mk (image2 has_scalar.smul) @[simp] theorem image2_smul {α : Type u_1} {β : Type u_2} {s : set α} [has_scalar α β] {t : set β} : image2 has_scalar.smul s t = s • t := rfl theorem mem_smul {α : Type u_1} {β : Type u_2} {s : set α} {x : β} [has_scalar α β] {t : set β} : x ∈ s • t ↔ ∃ (a : α), ∃ (y : β), a ∈ s ∧ y ∈ t ∧ a • y = x := iff.rfl theorem image_smul_prod {α : Type u_1} {β : Type u_2} {s : set α} [has_scalar α β] {t : set β} : (fun (x : α × β) => prod.fst x • prod.snd x) '' set.prod s t = s • t := image_prod has_scalar.smul theorem range_smul_range {α : Type u_1} {β : Type u_2} [has_scalar α β] {ι : Type u_3} {κ : Type u_4} (b : ι → α) (c : κ → β) : range b • range c = range fun (p : ι × κ) => b (prod.fst p) • c (prod.snd p) := sorry theorem singleton_smul {α : Type u_1} {β : Type u_2} {a : α} [has_scalar α β] {t : set β} : singleton a • t = a • t := image2_singleton_left /-! ### `set α` as a `(∪,*)`-semiring -/ /-- An alias for `set α`, which has a semiring structure given by `∪` as "addition" and pointwise multiplication `*` as "multiplication". -/ def set_semiring (α : Type u_1) := set α /-- The identitiy function `set α → set_semiring α`. -/ /-- The identitiy function `set_semiring α → set α`. -/ protected def up {α : Type u_1} (s : set α) : set_semiring α := s protected def set_semiring.down {α : Type u_1} (s : set_semiring α) : set α := s @[simp] protected theorem down_up {α : Type u_1} {s : set α} : set_semiring.down (set.up s) = s := rfl @[simp] protected theorem up_down {α : Type u_1} {s : set_semiring α} : set.up (set_semiring.down s) = s := rfl protected instance set_semiring.semiring {α : Type u_1} [monoid α] : semiring (set_semiring α) := semiring.mk (fun (s t : set_semiring α) => s ∪ t) union_assoc ∅ empty_union union_empty union_comm monoid.mul sorry monoid.one sorry sorry sorry sorry sorry sorry protected instance set_semiring.comm_semiring {α : Type u_1} [comm_monoid α] : comm_semiring (set_semiring α) := comm_semiring.mk semiring.add sorry semiring.zero sorry sorry sorry comm_monoid.mul sorry comm_monoid.one sorry sorry sorry sorry sorry sorry sorry /-- A multiplicative action of a monoid on a type β gives also a multiplicative action on the subsets of β. -/ protected instance mul_action_set {α : Type u_1} {β : Type u_2} [monoid α] [mul_action α β] : mul_action α (set β) := mul_action.mk sorry sorry theorem image_add {α : Type u_1} {β : Type u_2} {s : set α} {t : set α} [Add α] [Add β] (m : α → β) [is_add_hom m] : m '' (s + t) = m '' s + m '' t := sorry theorem preimage_mul_preimage_subset {α : Type u_1} {β : Type u_2} [Mul α] [Mul β] (m : α → β) [is_mul_hom m] {s : set β} {t : set β} : m ⁻¹' s * m ⁻¹' t ⊆ m ⁻¹' (s * t) := sorry /-- The image of a set under function is a ring homomorphism with respect to the pointwise operations on sets. -/ def image_hom {α : Type u_1} {β : Type u_2} [monoid α] [monoid β] (f : α →* β) : set_semiring α →+* set_semiring β := ring_hom.mk (image ⇑f) sorry sorry sorry sorry end set /-- A nonempty set in a semimodule is scaled by zero to the singleton containing 0 in the semimodule. -/ theorem zero_smul_set {α : Type u_1} {β : Type u_2} [semiring α] [add_comm_monoid β] [semimodule α β] {s : set β} (h : set.nonempty s) : 0 • s = 0 := sorry theorem mem_inv_smul_set_iff {α : Type u_1} {β : Type u_2} [field α] [mul_action α β] {a : α} (ha : a ≠ 0) (A : set β) (x : β) : x ∈ a⁻¹ • A ↔ a • x ∈ A := sorry theorem mem_smul_set_iff_inv_smul_mem {α : Type u_1} {β : Type u_2} [field α] [mul_action α β] {a : α} (ha : a ≠ 0) (A : set β) (x : β) : x ∈ a • A ↔ a⁻¹ • x ∈ A := eq.mpr (id (Eq._oldrec (Eq.refl (x ∈ a • A ↔ a⁻¹ • x ∈ A)) (Eq.symm (propext (mem_inv_smul_set_iff (inv_ne_zero ha) A x))))) (eq.mpr (id (Eq._oldrec (Eq.refl (x ∈ a • A ↔ x ∈ a⁻¹⁻¹ • A)) (inv_inv' a))) (iff.refl (x ∈ a • A))) namespace finset /-- The pointwise product of two finite sets `s` and `t`: `st = s ⬝ t = s * t = { x * y | x ∈ s, y ∈ t }`. -/ protected instance has_add {α : Type u_1} [DecidableEq α] [Add α] : Add (finset α) := { add := fun (s t : finset α) => image (fun (p : α × α) => prod.fst p + prod.snd p) (finset.product s t) } theorem mul_def {α : Type u_1} [DecidableEq α] [Mul α] {s : finset α} {t : finset α} : s * t = image (fun (p : α × α) => prod.fst p * prod.snd p) (finset.product s t) := rfl theorem mem_add {α : Type u_1} [DecidableEq α] [Add α] {s : finset α} {t : finset α} {x : α} : x ∈ s + t ↔ ∃ (y : α), ∃ (z : α), y ∈ s ∧ z ∈ t ∧ y + z = x := sorry @[simp] theorem coe_add {α : Type u_1} [DecidableEq α] [Add α] {s : finset α} {t : finset α} : ↑(s + t) = ↑s + ↑t := sorry theorem mul_mem_mul {α : Type u_1} [DecidableEq α] [Mul α] {s : finset α} {t : finset α} {x : α} {y : α} (hx : x ∈ s) (hy : y ∈ t) : x * y ∈ s * t := eq.mpr (id (propext mem_mul)) (Exists.intro x (Exists.intro y { left := hx, right := { left := hy, right := rfl } })) theorem add_card_le {α : Type u_1} [DecidableEq α] [Add α] {s : finset α} {t : finset α} : card (s + t) ≤ card s * card t := sorry theorem mul_card_le {α : Type u_1} [DecidableEq α] [Mul α] {s : finset α} {t : finset α} : card (s * t) ≤ card s * card t := sorry /-- A finite set `U` contained in the product of two sets `S * S'` is also contained in the product of two finite sets `T * T' ⊆ S * S'`. -/ theorem subset_add {M : Type u_1} [add_monoid M] {S : set M} {S' : set M} {U : finset M} (f : ↑U ⊆ S + S') : ∃ (T : finset M), ∃ (T' : finset M), ↑T ⊆ S ∧ ↑T' ⊆ S' ∧ U ⊆ T + T' := sorry end finset /-! Some lemmas about pointwise multiplication and submonoids. Ideally we put these in `group_theory.submonoid.basic`, but currently we cannot because that file is imported by this. -/ namespace submonoid theorem mul_subset {M : Type u_1} [monoid M] {s : set M} {t : set M} {S : submonoid M} (hs : s ⊆ ↑S) (ht : t ⊆ ↑S) : s * t ⊆ ↑S := sorry theorem mul_subset_closure {M : Type u_1} [monoid M] {s : set M} {t : set M} {u : set M} (hs : s ⊆ u) (ht : t ⊆ u) : s * t ⊆ ↑(closure u) := mul_subset (set.subset.trans hs subset_closure) (set.subset.trans ht subset_closure) theorem Mathlib.add_submonoid.coe_add_self_eq {M : Type u_1} [add_monoid M] (s : add_submonoid M) : ↑s + ↑s = ↑s := sorry
0f8530beb6462e4aca0c9de6ede43afbab25bd60
1fbca480c1574e809ae95a3eda58188ff42a5e41
/src/util/logic.lean
dcc5f30a0ba0f555142bd1e3a5aa8039cfb42136
[]
no_license
unitb/lean-lib
560eea0acf02b1fd4bcaac9986d3d7f1a4290e7e
439b80e606b4ebe4909a08b1d77f4f5c0ee3dee9
refs/heads/master
1,610,706,025,400
1,570,144,245,000
1,570,144,245,000
99,579,229
5
0
null
null
null
null
UTF-8
Lean
false
false
11,519
lean
import logic.basic universe variables u u' u₀ u₁ u₂ v variables {α α' : Sort u} {β : Sort u'} lemma forall_imp_forall {p q : α → Prop} (h : ∀ a, (p a → q a)) (p : ∀ a, p a) : ∀ a, q a := assume a, h _ (p a) lemma forall_imp_forall' {p : α → Prop} {q : β → Prop} (f : β → α) (h : ∀ a, (p (f a) → q a)) (P : ∀ a, p a) : ∀ a, q a := begin intro a, apply h, apply P end lemma exists_or {p q : α → Prop} : (∃ i, p i ∨ q i) ↔ (∃ i, p i) ∨ (∃ i, q i) := begin split ; intro h, { cases h with i h, apply or.imp _ _ h ; apply exists.intro }, { cases h with h h ; revert h ; apply exists_imp_exists ; intro, { apply or.intro_left }, { apply or.intro_right }, }, end lemma exists_imp_exists'' {p : α → Prop} {q : β → Prop} (f : ∀ x: α, p x → β) (h : ∀ a (h : p a), q (f a h)) (P : ∃ a, p a) : ∃ a, q a := begin cases P with a P, existsi f a P, apply h _ P, end lemma exists_imp_exists_simpl {p : β → Prop} (f : α → β) (P : ∃ a, p (f a)) : ∃ a, p a := begin cases P with a P, existsi f a, assumption, end lemma exists_imp_exists_prop {h₀ h₁ : Prop} {p : h₀ → Prop} {q : h₁ → Prop} (a : h₀) (f : h₀ → h₁) (h : p a → q (f a)) (P : ∃ a, p a) : ∃ a, q a := begin apply @exists_imp_exists' _ _ p q f _ P, intro, apply h end lemma exists_imp_iff_forall_imp (p : α → Prop) (q : Prop) : (∃ x, p x) → q ↔ (∀ x, p x → q) := begin split ; intros H, { intros x H', apply H _, exact ⟨_, H'⟩ }, { intros H', cases H' with x H', apply H _ H', }, end lemma and_exists (P : Prop) (Q : α → Prop) : P ∧ (∃ x, Q x) ↔ (∃ x, P ∧ Q x) := begin split ; intros H ; cases H with x H ; cases H with y H ; exact ⟨y,x,H⟩ end lemma exists_and (P : α → Prop) (Q : Prop) : (∃ x, P x) ∧ Q ↔ (∃ x, P x ∧ Q) := by simp lemma mem_set_of {α : Type u} (x : α) (P : α → Prop) : x ∈ set_of P ↔ P x := by refl lemma imp_mono {p p' q q' : Prop} (hp : p' → p) (hq : q → q') (h' : p → q) : (p' → q') := hq ∘ h' ∘ hp lemma imp_imp_imp_left {p q r : Prop} (h : p → q) (h' : q → r) : (p → r) := assume h'', h' (h h'') lemma imp_imp_imp_right {p q r : Prop} (h : p → q) (h' : r → p) : (r → q) := assume h'', h (h' h'') lemma imp_imp_imp_right' {p q r : Prop} (h : r → p → q) (h' : r → p) : (r → q) := assume h'', h h'' (h' h'') variables {a b c : Prop} lemma distrib_left_or : (a ∧ b) ∨ c ↔ (a ∨ c) ∧ (b ∨ c) := begin split, { intro h, cases h with ha hb, { split, apply or.inl ha^.left, apply or.inl ha^.right }, { split, apply or.inr hb, apply or.inr hb, } }, { intro h, cases h with hb hc, cases hb with hb ha, cases hc with hc ha, { apply or.inl (⟨hb,hc⟩ : a ∧ b) }, apply or.inr ha, apply or.inr ha, } end lemma iff_of_not_iff_not {p q : Prop} (h : ¬ p ↔ ¬ q) : p ↔ q := begin split ; intro h₀ ; apply classical.by_contradiction, { rw ← h, intro h₁, apply h₁ h₀ }, { rw h, intro h₁, apply h₁ h₀ }, end lemma not_iff_not_iff {p q : Prop} : (¬ p ↔ ¬ q) ↔ (p ↔ q) := ⟨ iff_of_not_iff_not, not_congr ⟩ lemma distrib_right_or : c ∨ (a ∧ b) ↔ (c ∨ a) ∧ (c ∨ b) := by { rw [or_comm,distrib_left_or], simp [or_comm], } lemma or_not_and (p q : Prop) : p ∨ (¬ p ∧ q) ↔ p ∨ q := by simp [distrib_right_or,iff_true_intro (classical.em p)] lemma not_or_iff_not_and_not {p q : Prop} : ¬ (p ∨ q) ↔ ¬ p ∧ ¬ q := not_or_distrib lemma and.mono_right (h : a → (b → c)) : a ∧ b → a ∧ c := assume ⟨ha,hb⟩, ⟨ha, h ha hb⟩ lemma and.mono_left (h : a → (b → c)) : b ∧ a → c ∧ a := assume ⟨ha,hb⟩, ⟨h hb ha, hb⟩ namespace classical local attribute [instance] prop_decidable lemma or.mono_right (h : ¬ a → (b → c)) : a ∨ b → a ∨ c := or.rec or.inl $ assume h' : b, if ha : a then or.inl ha else or.inr (h ha h') lemma or.mono_left (h : ¬ a → (b → c)) : b ∨ a → c ∨ a := assume h' : b ∨ a, or.symm $ or.mono_right h h'.symm lemma not_and_iff_not_or_not {p q : Prop} : ¬ (p ∧ q) ↔ ¬ p ∨ ¬ q := not_and_distrib end classical lemma not_not_iff_self {p : Prop} : ¬ ¬ p ↔ p := begin split , { intro hnnp, cases classical.em p with h h, apply h, cases hnnp h }, exact not_not_intro end lemma and_iff_imp (p q : Prop) (h : p) : p ∧ q ↔ p → q := by { split ; intros ; cases_matching* _ ∧ _ ; try { split } ; try { assumption }, exact a h } lemma and_shunting (p q r : Prop) : (p ∧ q → r) ↔ (p → q → r) := begin split ; intro h, { intros hp hq, apply h ⟨hp,hq⟩ }, { intro h', cases h' with hp hq, apply h hp hq } end lemma assume_neg {p : Prop} : (¬ p → p) → p := begin intro h, cases classical.em p with h' h', { apply h' }, { apply h h' }, end lemma not_forall_iff_exists_not {t : Type u} (P : t → Prop) : ¬ (∀ x, P x) ↔ (∃ x, ¬ P x) := begin split, { intro h, apply classical.by_contradiction, intros h', apply h, intro i, have h'' := forall_not_of_not_exists h' i, rw not_not_iff_self at h'', apply h'' }, { intros h₀ h₁, cases h₀ with i h₀, apply h₀, apply h₁ }, end lemma not_exists_iff_forall_not {t : Type u} (P : t → Prop) : ¬ (∃ x, P x) ↔ (∀ x, ¬ P x) := begin split, { intros h x h', apply h, existsi x, apply h' }, { intros h₀ h₁, cases h₁ with i h₁, apply h₀, apply h₁ }, end lemma forall_or {t : Type u} (P Q R : t → Prop) : (∀ x, P x ∨ Q x → R x) ↔ (∀ x, P x → R x) ∧ (∀ x, Q x → R x) := begin split ; intro h, split, all_goals { intros x h' }, any_goals { cases h with h₀ h₁, cases h' with h₂ h₂ }, { apply h, left, apply h' }, { apply h, right, apply h' }, { apply h₀, apply h₂ }, { apply h₁, apply h₂ }, end lemma exists_option {t : Type u} (P : option t → Prop) : (∃ x : option t, P x) ↔ P none ∨ ∃ x', P (some x') := begin split ; intro h, { cases h with x h, cases x with x, { left, assumption }, { right, exact ⟨_,h⟩ } }, { cases h with h h ; try { cases h with h h } ; exact ⟨_,h⟩ } end @[simp] lemma exists_true (P : true → Prop) : (∃ x : true, P x) ↔ P trivial := begin split ; intro h, { cases h with x h, cases x, apply h }, { exact ⟨_,h⟩ } end lemma true_imp (p : Prop) : true → p ↔ p := by { split ; intro h ; intros ; apply h ; trivial } lemma exists_of_nonempty {t} (p : t → Prop) : Π [nonempty t], (∀ x, p x) → ∃ x, p x | ⟨ x ⟩ H := ⟨x,H x⟩ lemma distrib_left_and (p q r : Prop) : p ∧ (q ∨ r) ↔ (p ∧ q) ∨ (p ∧ r) := begin cases classical.em p with h h, { simp [eq_true_intro h] }, { simp [eq_false_intro h] }, end lemma distrib_or_over_exists_left {t} [nonempty t] (p : t → Prop) (q : Prop) : q ∨ (∃ x, p x) ↔ (∃ x, q ∨ p x) := begin split ; intro h, cases h with h h, { apply exists_of_nonempty, intro, left, apply h }, { apply exists_imp_exists _ h, intro, apply or.intro_right }, cases h with x h, { apply or.imp_right _ h, apply Exists.intro }, end lemma or_iff_not_imp (p q : Prop) : p ∨ q ↔ ¬ p → q := begin cases classical.em p with hp hnp, { rw [eq_true_intro hp,true_or,not_true,false_implies_iff], }, { rw [eq_false_intro hnp,false_or,not_false_iff,true_imp], } end lemma not_imp_iff_and_not (p q : Prop) : ¬ (p → q) ↔ p ∧ ¬ q := by { apply @not_imp _ _ _, apply classical.prop_decidable } open function lemma exists_one_point_of_right_inverse {f : β → α} {g : α → β} (h₀ : right_inverse g f) (y : α) {p : α → Prop} (h₁ : ∀ x, p (f x) → f x = y) : (∃ x, p (f x)) ↔ p y := begin split ; intro h, { cases h with x h', rw [ ← h₁ _ h' ], apply h' }, { existsi g y, rw h₀, exact h } end lemma exists_one_point (y : α) {p : α → Prop} (h : ∀ x, p x → x = y) : (∃ x, p x) ↔ p y := by { refine exists_one_point_of_right_inverse _ y h, exact id, intro, refl } @[simp] lemma exists_one_point_iff_true (y : α) : (∃ x, x = y) ↔ true := iff_true_intro ⟨y,rfl⟩ @[simp] lemma exists_one_point_right (p : α → Prop) (y : α) : (∃ x, p x ∧ x = y) ↔ p y := by { rw exists_one_point y ; simp } @[simp] lemma exists_one_point_right' (p : α → Prop) (y : α) : (∃ x, p x ∧ y = x) ↔ p y := by { rw exists_one_point y ; simp, intros, subst x, } @[simp] lemma exists_one_point_left (p : α → Prop) (y : α) : (∃ x, x = y ∧ p x) ↔ p y := by { rw exists_one_point y ; simp } @[simp] lemma exists_one_point_left' (p : α → Prop) (y : α) : (∃ x, y = x ∧ p x) ↔ p y := by { rw exists_one_point y ; simp, } lemma exists_variable_change' (p : α → Prop) (q : β → Prop) (f : ∀ x : α, p x → β) (g : ∀ x : β, q x → α) (Hf : ∀ x (h: p x), q (f x h)) (Hg : ∀ x (h: q x), p (g x h)) : (∃ i, p i) ↔ (∃ j, q j) := begin split, { apply exists_imp_exists'' f Hf, }, { apply exists_imp_exists'' g Hg, }, end lemma exists_variable_change (p : α → Prop) (q : β → Prop) (f : α → β) (g : β → α) (Hf : ∀ x, p x → q (f x)) (Hg : ∀ x, q x → p (g x)) : (∃ i, p i) ↔ (∃ j, q j) := begin apply exists_variable_change' p q (λ x (h : p x), f x) (λ x (h : q x), g x), apply Hf, apply Hg, end @[simp] lemma exists_range_subtype {α : Sort u} (p : α → Prop) (q : α → Prop) : (∃ j : subtype p, q j.val) ↔ (∃ i, p i ∧ q i) := begin let f := λ (x : α) (h : p x ∧ q x), subtype.mk x h.left, let g := λ (x : subtype p) (h : q (x.val)), x.val, apply exists_variable_change' _ _ g f, { intros x h, exact ⟨x.property, h⟩ }, { intros x h, apply h.right }, end lemma forall_eq_iff_iff_eq {a b : α} : (∀ c, a = c ↔ c = b) ↔ a = b := by { split ; intro h ; rw h, cc, } lemma forall_eq_implies_iff_eq {a b : α} : (∀ c, a = c → c = b) ↔ a = b := by { split ; intro h, apply h, refl, intros, cc } lemma or_of_ite {c t f : Prop} [decidable c] (h : ite c t f) : (c ∧ t) ∨ (¬ c ∧ f) := begin cases decidable.em c with hc hnc, { left, rw [if_pos hc] at h, exact ⟨hc,h⟩ }, { right, rw [if_neg hnc] at h, exact ⟨hnc,h⟩ }, end lemma or_of_ite' {c t f : Prop} [decidable c] (h : ite c t f) : t ∨ f := begin apply or.imp _ _ (or_of_ite h) ; apply and.right end def rtc {α : Type u} (r : α → α → Prop) (x y : α) := x = y ∨ tc r x y def rtc_refl {α : Type u} {r : α → α → Prop} {x : α} : rtc r x x := begin unfold rtc, left, refl end def rtc_trans {α : Type u} {r : α → α → Prop} {x : α} (y : α) {z : α} (h₀ : rtc r x y) (h₁ : rtc r y z) : rtc r x z := begin unfold rtc at h₀, cases h₀ with h₀ h₀, { subst y, apply h₁ }, unfold rtc at h₁, cases h₁ with h₁ h₁, { subst z, apply or.intro_right _ h₀ }, { apply or.intro_right, apply tc.trans _ _ _ h₀ h₁, } end instance : is_associative _ (∨) := ⟨ by simp [or_assoc] ⟩ instance : is_associative _ (∧) := ⟨ by simp [and_assoc] ⟩ instance : is_commutative _ (∨) := ⟨ by simp [or_comm] ⟩ instance : is_commutative _ (∧) := ⟨ by simp [and_comm] ⟩
681e16f6d4cc986893cff31f5504e80bb48f4124
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/coe12.lean
0bf4b9ac8365e6ad75694dadd3e41c74e1b3e66c
[ "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
269
lean
import data.nat inductive foo (A B : Type) : Type := mk : (Π {C : Type}, A → C → B) → foo A B definition to_fun [coercion] {A B : Type} (f : foo A B) : Π {C : Type}, A → C → B := foo.rec (λf, f) f constant f : foo nat nat constant a : nat check f a true
fcb9bab85749e55532fb743d24d02b7873265541
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/run/def20.lean
2041cc77e390842223bf47d5e1525d0f372bc7bb
[ "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
758
lean
new_frontend def f : Char → Nat | 'a' => 0 | 'b' => 1 | 'c' => 2 | 'd' => 3 | 'e' => 4 | _ => 5 theorem ex1 : (f 'a', f 'b', f 'c', f 'd', f 'e', f 'f') = (0, 1, 2, 3, 4, 5) := rfl def g : Nat → Nat | 100000 => 0 | 200000 => 1 | 300000 => 2 | 400000 => 3 | _ => 5 theorem ex2 : (g 100000, g 200000, g 300000, g 400000, g 0) = (0, 1, 2, 3, 5) := rfl def h : String → Nat | "hello" => 0 | "world" => 1 | "bla" => 2 | "boo" => 3 | _ => 5 theorem ex3 : (h "hello", h "world", h "bla", h "boo", h "zoo") = (0, 1, 2, 3, 5) := rfl def r : String × String → Nat | ("hello", "world") => 0 | ("world", "hello") => 1 | _ => 2 theorem ex4 : (r ("hello", "world"), r ("world", "hello"), r ("a", "b")) = (0, 1, 2) := rfl
9428452c8cfa2e6dc8cfa1d11fe1d7e0719e020d
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/compiler/bytearray_bug.lean
d200af09b8e9063f8cf28c89e7540c4d677012e0
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
150
lean
def main (xs : List String) : IO Unit := let arr := (let e := ByteArray.empty; e.push (UInt8.ofNat 10)); let v := arr.data.get! 0; IO.println v
dd648983eb7a12bb1f2d13a92a42f89dc0a8a50c
d7189ea2ef694124821b033e533f18905b5e87ef
/galois/vector/tail_lemmas.lean
d40329aff0b2b7b7b38a6a7df433ac98e0ffa7d7
[ "Apache-2.0" ]
permissive
digama0/lean-protocol-support
eaa7e6f8b8e0d5bbfff1f7f52bfb79a3b11b0f59
cabfa3abedbdd6fdca6e2da6fbbf91a13ed48dda
refs/heads/master
1,625,421,450,627
1,506,035,462,000
1,506,035,462,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
700
lean
/- Lemmas for tail, and a total tail function. -/ import data.vector import ..list.tail universe variables u namespace vector variable {α : Type u} variable {n : ℕ} @[simp] theorem to_list_tail (v : vector α (nat.succ n)) : to_list (tail v) = list.tail (to_list v) := begin cases v, cases val, contradiction, simp [ tail ], end -- Extends tail to work over total functions def total_tail : vector α n → vector α (n - 1) | ⟨ v, h ⟩ := ⟨ list.tail v, eq.trans (list.length_tail v) (congr_arg (λ x, x - 1) h) ⟩ @[simp] theorem to_list_total_tail (v : vector α n) : to_list (total_tail v) = list.tail (to_list v) := begin cases v, simp [ total_tail ], end end vector
b0462eda87ef87f2c22fd22029137cc6fea5569a
4727251e0cd73359b15b664c3170e5d754078599
/src/ring_theory/class_group.lean
5d6f4889966dfa9d1f763a32621fc105d6b2b3f2
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
10,445
lean
/- Copyright (c) 2021 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import group_theory.quotient_group import ring_theory.dedekind_domain.ideal /-! # The ideal class group This file defines the ideal class group `class_group R K` of fractional ideals of `R` inside `A`'s field of fractions `K`. ## Main definitions - `to_principal_ideal` sends an invertible `x : K` to an invertible fractional ideal - `class_group` is the quotient of invertible fractional ideals modulo `to_principal_ideal.range` - `class_group.mk0` sends a nonzero integral ideal in a Dedekind domain to its class ## Main results - `class_group.mk0_eq_mk0_iff` shows the equivalence with the "classical" definition, where `I ~ J` iff `x I = y J` for `x y ≠ (0 : R)` -/ variables {R K L : Type*} [comm_ring R] variables [field K] [field L] [decidable_eq L] variables [algebra R K] [is_fraction_ring R K] variables [algebra K L] [finite_dimensional K L] variables [algebra R L] [is_scalar_tower R K L] open_locale non_zero_divisors open is_localization is_fraction_ring fractional_ideal units section variables (R K) /-- `to_principal_ideal R K x` sends `x ≠ 0 : K` to the fractional `R`-ideal generated by `x` -/ @[irreducible] def to_principal_ideal : Kˣ →* (fractional_ideal R⁰ K)ˣ := { to_fun := λ x, ⟨span_singleton _ x, span_singleton _ x⁻¹, by simp only [span_singleton_one, units.mul_inv', span_singleton_mul_span_singleton], by simp only [span_singleton_one, units.inv_mul', span_singleton_mul_span_singleton]⟩, map_mul' := λ x y, ext (by simp only [units.coe_mk, units.coe_mul, span_singleton_mul_span_singleton]), map_one' := ext (by simp only [span_singleton_one, units.coe_mk, units.coe_one]) } local attribute [semireducible] to_principal_ideal variables {R K} @[simp] lemma coe_to_principal_ideal (x : Kˣ) : (to_principal_ideal R K x : fractional_ideal R⁰ K) = span_singleton _ x := rfl @[simp] lemma to_principal_ideal_eq_iff {I : (fractional_ideal R⁰ K)ˣ} {x : Kˣ} : to_principal_ideal R K x = I ↔ span_singleton R⁰ (x : K) = I := units.ext_iff end instance principal_ideals.normal : (to_principal_ideal R K).range.normal := subgroup.normal_of_comm _ section variables (R K) /-- The ideal class group of `R` in a field of fractions `K` is the group of invertible fractional ideals modulo the principal ideals. -/ @[derive(comm_group)] def class_group := (fractional_ideal R⁰ K)ˣ ⧸ (to_principal_ideal R K).range instance : inhabited (class_group R K) := ⟨1⟩ variables {R} [is_domain R] /-- Send a nonzero integral ideal to an invertible fractional ideal. -/ @[simps] noncomputable def fractional_ideal.mk0 [is_dedekind_domain R] : (ideal R)⁰ →* (fractional_ideal R⁰ K)ˣ := { to_fun := λ I, units.mk0 I ((fractional_ideal.coe_to_fractional_ideal_ne_zero (le_refl R⁰)).mpr (mem_non_zero_divisors_iff_ne_zero.mp I.2)), map_one' := by simp, map_mul' := λ x y, by simp } /-- Send a nonzero ideal to the corresponding class in the class group. -/ @[simps] noncomputable def class_group.mk0 [is_dedekind_domain R] : (ideal R)⁰ →* class_group R K := (quotient_group.mk' _).comp (fractional_ideal.mk0 K) variables {K} lemma quotient_group.mk'_eq_mk' {G : Type*} [group G] {N : subgroup G} [hN : N.normal] {x y : G} : quotient_group.mk' N x = quotient_group.mk' N y ↔ ∃ z ∈ N, x * z = y := (@quotient.eq _ (quotient_group.left_rel _) _ _).trans ⟨λ (h : x⁻¹ * y ∈ N), ⟨_, h, by rw [← mul_assoc, mul_right_inv, one_mul]⟩, λ ⟨z, z_mem, eq_y⟩, by { rw ← eq_y, show x⁻¹ * (x * z) ∈ N, rwa [← mul_assoc, mul_left_inv, one_mul] }⟩ lemma class_group.mk0_eq_mk0_iff_exists_fraction_ring [is_dedekind_domain R] {I J : (ideal R)⁰} : class_group.mk0 K I = class_group.mk0 K J ↔ ∃ (x ≠ (0 : K)), span_singleton R⁰ x * I = J := begin simp only [class_group.mk0, monoid_hom.comp_apply, quotient_group.mk'_eq_mk'], split, { rintros ⟨_, ⟨x, rfl⟩, hx⟩, refine ⟨x, x.ne_zero, _⟩, simpa only [mul_comm, coe_mk0, monoid_hom.to_fun_eq_coe, coe_to_principal_ideal, units.coe_mul] using congr_arg (coe : _ → fractional_ideal R⁰ K) hx }, { rintros ⟨x, hx, eq_J⟩, refine ⟨_, ⟨units.mk0 x hx, rfl⟩, units.ext _⟩, simpa only [fractional_ideal.mk0_apply, units.coe_mk0, mul_comm, coe_to_principal_ideal, coe_coe, units.coe_mul] using eq_J } end lemma class_group.mk0_eq_mk0_iff [is_dedekind_domain R] {I J : (ideal R)⁰} : class_group.mk0 K I = class_group.mk0 K J ↔ ∃ (x y : R) (hx : x ≠ 0) (hy : y ≠ 0), ideal.span {x} * (I : ideal R) = ideal.span {y} * J := begin refine class_group.mk0_eq_mk0_iff_exists_fraction_ring.trans ⟨_, _⟩, { rintros ⟨z, hz, h⟩, obtain ⟨x, ⟨y, hy⟩, rfl⟩ := is_localization.mk'_surjective R⁰ z, refine ⟨x, y, _, mem_non_zero_divisors_iff_ne_zero.mp hy, _⟩, { rintro hx, apply hz, rw [hx, is_fraction_ring.mk'_eq_div, (algebra_map R K).map_zero, zero_div] }, { exact (fractional_ideal.mk'_mul_coe_ideal_eq_coe_ideal K hy).mp h } }, { rintros ⟨x, y, hx, hy, h⟩, have hy' : y ∈ R⁰ := mem_non_zero_divisors_iff_ne_zero.mpr hy, refine ⟨is_localization.mk' K x ⟨y, hy'⟩, _, _⟩, { contrapose! hx, rwa [is_localization.mk'_eq_iff_eq_mul, zero_mul, ← (algebra_map R K).map_zero, (is_fraction_ring.injective R K).eq_iff] at hx }, { exact (fractional_ideal.mk'_mul_coe_ideal_eq_coe_ideal K hy').mpr h } }, end lemma class_group.mk0_surjective [is_dedekind_domain R] : function.surjective (class_group.mk0 K : (ideal R)⁰ → class_group R K) := begin rintros ⟨I⟩, obtain ⟨a, a_ne_zero', ha⟩ := I.1.2, have a_ne_zero := mem_non_zero_divisors_iff_ne_zero.mp a_ne_zero', have fa_ne_zero : (algebra_map R K) a ≠ 0 := is_fraction_ring.to_map_ne_zero_of_mem_non_zero_divisors a_ne_zero', refine ⟨⟨{ carrier := { x | (algebra_map R K a)⁻¹ * algebra_map R K x ∈ I.1 }, .. }, _⟩, _⟩, { simp only [ring_hom.map_add, set.mem_set_of_eq, mul_zero, ring_hom.map_mul, mul_add], exact λ _ _ ha hb, submodule.add_mem I ha hb }, { simp only [ring_hom.map_zero, set.mem_set_of_eq, mul_zero, ring_hom.map_mul], exact submodule.zero_mem I }, { intros c _ hb, simp only [smul_eq_mul, set.mem_set_of_eq, mul_zero, ring_hom.map_mul, mul_add, mul_left_comm ((algebra_map R K) a)⁻¹], rw ← algebra.smul_def c, exact submodule.smul_mem I c hb }, { rw [mem_non_zero_divisors_iff_ne_zero, submodule.zero_eq_bot, submodule.ne_bot_iff], obtain ⟨x, x_ne, x_mem⟩ := exists_ne_zero_mem_is_integer I.ne_zero, refine ⟨a * x, _, mul_ne_zero a_ne_zero x_ne⟩, change ((algebra_map R K) a)⁻¹ * (algebra_map R K) (a * x) ∈ I.1, rwa [ring_hom.map_mul, ← mul_assoc, inv_mul_cancel fa_ne_zero, one_mul] }, { symmetry, apply quotient.sound, refine ⟨units.mk0 (algebra_map R K a) fa_ne_zero, _⟩, apply @mul_left_cancel _ _ I, rw [← mul_assoc, mul_right_inv, one_mul, eq_comm, mul_comm I], apply units.ext, simp only [monoid_hom.coe_mk, subtype.coe_mk, ring_hom.map_mul, coe_coe, units.coe_mul, coe_to_principal_ideal, coe_mk0, fractional_ideal.eq_span_singleton_mul], split, { intros zJ' hzJ', obtain ⟨zJ, hzJ : (algebra_map R K a)⁻¹ * algebra_map R K zJ ∈ ↑I, rfl⟩ := (mem_coe_ideal R⁰).mp hzJ', refine ⟨_, hzJ, _⟩, rw [← mul_assoc, mul_inv_cancel fa_ne_zero, one_mul] }, { intros zI' hzI', obtain ⟨y, hy⟩ := ha zI' hzI', rw [← algebra.smul_def, fractional_ideal.mk0_apply, coe_mk0, coe_coe, mem_coe_ideal], refine ⟨y, _, hy⟩, show (algebra_map R K a)⁻¹ * algebra_map R K y ∈ (I : fractional_ideal R⁰ K), rwa [hy, algebra.smul_def, ← mul_assoc, inv_mul_cancel fa_ne_zero, one_mul] } } end end lemma class_group.mk_eq_one_iff {I : (fractional_ideal R⁰ K)ˣ} : quotient_group.mk' (to_principal_ideal R K).range I = 1 ↔ (I : submodule R K).is_principal := begin rw [← (quotient_group.mk' _).map_one, eq_comm, quotient_group.mk'_eq_mk'], simp only [exists_prop, one_mul, exists_eq_right, to_principal_ideal_eq_iff, monoid_hom.mem_range, coe_coe], refine ⟨λ ⟨x, hx⟩, ⟨⟨x, by rw [← hx, coe_span_singleton]⟩⟩, _⟩, unfreezingI { intros hI }, obtain ⟨x, hx⟩ := @submodule.is_principal.principal _ _ _ _ _ _ hI, have hx' : (I : fractional_ideal R⁰ K) = span_singleton R⁰ x, { apply subtype.coe_injective, rw [hx, coe_span_singleton] }, refine ⟨units.mk0 x _, _⟩, { intro x_eq, apply units.ne_zero I, simp [hx', x_eq] }, simp [hx'] end variables [is_domain R] lemma class_group.mk0_eq_one_iff [is_dedekind_domain R] {I : ideal R} (hI : I ∈ (ideal R)⁰) : class_group.mk0 K ⟨I, hI⟩ = 1 ↔ I.is_principal := class_group.mk_eq_one_iff.trans (coe_submodule_is_principal R K) /-- The class group of principal ideal domain is finite (in fact a singleton). TODO: generalize to Dedekind domains -/ instance [is_principal_ideal_ring R] : fintype (class_group R K) := { elems := {1}, complete := begin rintros ⟨I⟩, rw [finset.mem_singleton], exact class_group.mk_eq_one_iff.mpr (I : fractional_ideal R⁰ K).is_principal end } /-- The class number of a principal ideal domain is `1`. -/ lemma card_class_group_eq_one [is_principal_ideal_ring R] : fintype.card (class_group R K) = 1 := begin rw fintype.card_eq_one_iff, use 1, rintros ⟨I⟩, exact class_group.mk_eq_one_iff.mpr (I : fractional_ideal R⁰ K).is_principal end /-- The class number is `1` iff the ring of integers is a principal ideal domain. -/ lemma card_class_group_eq_one_iff [is_dedekind_domain R] [fintype (class_group R K)] : fintype.card (class_group R K) = 1 ↔ is_principal_ideal_ring R := begin split, swap, { introsI, convert card_class_group_eq_one, assumption, assumption, }, rw fintype.card_eq_one_iff, rintros ⟨I, hI⟩, have eq_one : ∀ J : class_group R K, J = 1 := λ J, trans (hI J) (hI 1).symm, refine ⟨λ I, _⟩, by_cases hI : I = ⊥, { rw hI, exact bot_is_principal }, exact (class_group.mk0_eq_one_iff (mem_non_zero_divisors_iff_ne_zero.mpr hI)).mp (eq_one _), end
739294dc626ff98a402b880ce9539d664ab65f8c
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/module/big_operators.lean
4a918ebcfe9872027359da5bd4bacd4bcc4bfa66
[ "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
1,113
lean
/- Copyright (c) 2015 Nathaniel Thomas. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nathaniel Thomas, Jeremy Avigad, Johannes Hölzl, Mario Carneiro -/ import algebra.module.basic import algebra.big_operators.basic /-! # Finite sums over modules over a ring -/ open_locale big_operators universes u v variables {α R k S M M₂ M₃ ι : Type*} section add_comm_monoid variables [semiring R] [add_comm_monoid M] [module R M] (r s : R) (x y : M) variables {R M} lemma list.sum_smul {l : list R} {x : M} : l.sum • x = (l.map (λ r, r • x)).sum := ((smul_add_hom R M).flip x).map_list_sum l lemma multiset.sum_smul {l : multiset R} {x : M} : l.sum • x = (l.map (λ r, r • x)).sum := ((smul_add_hom R M).flip x).map_multiset_sum l lemma finset.sum_smul {f : ι → R} {s : finset ι} {x : M} : (∑ i in s, f i) • x = (∑ i in s, (f i) • x) := ((smul_add_hom R M).flip x).map_sum f s end add_comm_monoid lemma finset.cast_card [comm_semiring R] (s : finset α) : (s.card : R) = ∑ a in s, 1 := by rw [finset.sum_const, nat.smul_one_eq_coe]
4f41510020d49d41dbf64ce203234a4ded9ec4c7
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/stage0/src/Lean/LocalContext.lean
83c6c76a54de1315c72946ebf33e7a3cbf3ad5fa
[ "Apache-2.0" ]
permissive
walterhu1015/lean4
b2c71b688975177402758924eaa513475ed6ce72
2214d81e84646a905d0b20b032c89caf89c737ad
refs/heads/master
1,671,342,096,906
1,599,695,985,000
1,599,695,985,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,681
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 Std.Data.PersistentArray import Lean.Expr import Lean.Hygiene namespace Lean inductive LocalDecl | cdecl (index : Nat) (fvarId : FVarId) (userName : Name) (type : Expr) (bi : BinderInfo) | ldecl (index : Nat) (fvarId : FVarId) (userName : Name) (type : Expr) (value : Expr) (nonDep : Bool) @[export lean_mk_local_decl] def mkLocalDeclEx (index : Nat) (fvarId : FVarId) (userName : Name) (type : Expr) (bi : BinderInfo) : LocalDecl := LocalDecl.cdecl index fvarId userName type bi @[export lean_mk_let_decl] def mkLetDeclEx (index : Nat) (fvarId : FVarId) (userName : Name) (type : Expr) (val : Expr) : LocalDecl := LocalDecl.ldecl index fvarId userName type val false @[export lean_local_decl_binder_info] def LocalDecl.binderInfoEx : LocalDecl → BinderInfo | LocalDecl.cdecl _ _ _ _ bi => bi | _ => BinderInfo.default namespace LocalDecl instance : Inhabited LocalDecl := ⟨ldecl (arbitrary _) (arbitrary _) (arbitrary _) (arbitrary _) (arbitrary _) false⟩ def isLet : LocalDecl → Bool | cdecl _ _ _ _ _ => false | ldecl _ _ _ _ _ _ => true def index : LocalDecl → Nat | cdecl idx _ _ _ _ => idx | ldecl idx _ _ _ _ _ => idx def setIndex : LocalDecl → Nat → LocalDecl | cdecl _ id n t bi, idx => cdecl idx id n t bi | ldecl _ id n t v nd, idx => ldecl idx id n t v nd def fvarId : LocalDecl → FVarId | cdecl _ id _ _ _ => id | ldecl _ id _ _ _ _ => id def userName : LocalDecl → Name | cdecl _ _ n _ _ => n | ldecl _ _ n _ _ _ => n def type : LocalDecl → Expr | cdecl _ _ _ t _ => t | ldecl _ _ _ t _ _ => t def setType : LocalDecl → Expr → LocalDecl | cdecl idx id n _ bi, t => cdecl idx id n t bi | ldecl idx id n _ v nd, t => ldecl idx id n t v nd def binderInfo : LocalDecl → BinderInfo | cdecl _ _ _ _ bi => bi | ldecl _ _ _ _ _ _ => BinderInfo.default def value? : LocalDecl → Option Expr | cdecl _ _ _ _ _ => none | ldecl _ _ _ _ v _ => some v def value : LocalDecl → Expr | cdecl _ _ _ _ _ => panic! "let declaration expected" | ldecl _ _ _ _ v _ => v def setValue : LocalDecl → Expr → LocalDecl | ldecl idx id n t _ nd, v => ldecl idx id n t v nd | d, _ => d def updateUserName : LocalDecl → Name → LocalDecl | cdecl index id _ type bi, userName => cdecl index id userName type bi | ldecl index id _ type val nd, userName => ldecl index id userName type val nd def updateBinderInfo : LocalDecl → BinderInfo → LocalDecl | cdecl index id n type _, bi => cdecl index id n type bi | ldecl _ _ _ _ _ _, _ => panic! "unexpected let declaration" def toExpr (decl : LocalDecl) : Expr := mkFVar decl.fvarId end LocalDecl open Std (PersistentHashMap PersistentArray PArray) structure LocalContext := (fvarIdToDecl : PersistentHashMap FVarId LocalDecl := {}) (decls : PersistentArray (Option LocalDecl) := {}) namespace LocalContext instance : Inhabited LocalContext := ⟨{}⟩ @[export lean_mk_empty_local_ctx] def mkEmpty : Unit → LocalContext := fun _ => {} def empty : LocalContext := {} @[export lean_local_ctx_is_empty] def isEmpty (lctx : LocalContext) : Bool := lctx.fvarIdToDecl.isEmpty /- Low level API for creating local declarations. It is used to implement actions in the monads `Elab` and `Tactic`. It should not be used directly since the argument `(name : Name)` is assumed to be "unique". -/ @[export lean_local_ctx_mk_local_decl] def mkLocalDecl (lctx : LocalContext) (fvarId : FVarId) (userName : Name) (type : Expr) (bi : BinderInfo := BinderInfo.default) : LocalContext := match lctx with | { fvarIdToDecl := map, decls := decls } => let idx := decls.size; let decl := LocalDecl.cdecl idx fvarId userName type bi; { fvarIdToDecl := map.insert fvarId decl, decls := decls.push decl } @[export lean_local_ctx_mk_let_decl] def mkLetDecl (lctx : LocalContext) (fvarId : FVarId) (userName : Name) (type : Expr) (value : Expr) (nonDep := false) : LocalContext := match lctx with | { fvarIdToDecl := map, decls := decls } => let idx := decls.size; let decl := LocalDecl.ldecl idx fvarId userName type value nonDep; { fvarIdToDecl := map.insert fvarId decl, decls := decls.push decl } /- Low level API -/ def addDecl (lctx : LocalContext) (newDecl : LocalDecl) : LocalContext := match lctx with | { fvarIdToDecl := map, decls := decls } => let idx := decls.size; let newDecl := newDecl.setIndex idx; { fvarIdToDecl := map.insert newDecl.fvarId newDecl, decls := decls.push newDecl } @[export lean_local_ctx_find] def find? (lctx : LocalContext) (fvarId : FVarId) : Option LocalDecl := lctx.fvarIdToDecl.find? fvarId def findFVar? (lctx : LocalContext) (e : Expr) : Option LocalDecl := lctx.find? e.fvarId! def get! (lctx : LocalContext) (fvarId : FVarId) : LocalDecl := match lctx.find? fvarId with | some d => d | none => panic! "unknown free variable" def getFVar! (lctx : LocalContext) (e : Expr) : LocalDecl := lctx.get! e.fvarId! def contains (lctx : LocalContext) (fvarId : FVarId) : Bool := lctx.fvarIdToDecl.contains fvarId def containsFVar (lctx : LocalContext) (e : Expr) : Bool := lctx.contains e.fvarId! def getFVarIds (lctx : LocalContext) : Array FVarId := lctx.decls.foldl (fun (r : Array FVarId) decl? => match decl? with | some decl => r.push decl.fvarId | none => r) #[] def getFVars (lctx : LocalContext) : Array Expr := lctx.getFVarIds.map mkFVar private partial def popTailNoneAux : PArray (Option LocalDecl) → PArray (Option LocalDecl) | a => if a.size == 0 then a else match a.get! (a.size - 1) with | none => popTailNoneAux a.pop | some _ => a @[export lean_local_ctx_erase] def erase (lctx : LocalContext) (fvarId : FVarId) : LocalContext := match lctx with | { fvarIdToDecl := map, decls := decls } => match map.find? fvarId with | none => lctx | some decl => { fvarIdToDecl := map.erase fvarId, decls := popTailNoneAux (decls.set decl.index none) } @[export lean_local_ctx_pop] def pop (lctx : LocalContext): LocalContext := match lctx with | { fvarIdToDecl := map, decls := decls } => if decls.size == 0 then lctx else match decls.get! (decls.size - 1) with | none => lctx -- unreachable | some decl => { fvarIdToDecl := map.erase decl.fvarId, decls := popTailNoneAux decls.pop } @[export lean_local_ctx_find_from_user_name] def findFromUserName? (lctx : LocalContext) (userName : Name) : Option LocalDecl := lctx.decls.findSomeRev? (fun decl => match decl with | none => none | some decl => if decl.userName == userName then some decl else none) @[export lean_local_ctx_uses_user_name] def usesUserName (lctx : LocalContext) (userName : Name) : Bool := (lctx.findFromUserName? userName).isSome private partial def getUnusedNameAux (lctx : LocalContext) (suggestion : Name) : Nat → Name × Nat | i => let curr := suggestion.appendIndexAfter i; if lctx.usesUserName curr then getUnusedNameAux (i + 1) else (curr, i + 1) @[export lean_local_ctx_get_unused_name] def getUnusedName (lctx : LocalContext) (suggestion : Name) : Name := let suggestion := suggestion.eraseMacroScopes; if lctx.usesUserName suggestion then (getUnusedNameAux lctx suggestion 1).1 else suggestion @[export lean_local_ctx_last_decl] def lastDecl (lctx : LocalContext) : Option LocalDecl := lctx.decls.get! (lctx.decls.size - 1) @[export lean_local_ctx_rename_user_name] def renameUserName (lctx : LocalContext) (fromName : Name) (toName : Name) : LocalContext := match lctx with | { fvarIdToDecl := map, decls := decls } => match lctx.findFromUserName? fromName with | none => lctx | some decl => let decl := decl.updateUserName toName; { fvarIdToDecl := map.insert decl.fvarId decl, decls := decls.set decl.index decl } /-- Low-level function for updating the local context. Assumptions about `f`, the resulting nested expressions must be definitionally equal to their original values, the `index` nor `fvarId` are modified. -/ @[inline] def modifyLocalDecl (lctx : LocalContext) (fvarId : FVarId) (f : LocalDecl → LocalDecl) : LocalContext := match lctx with | { fvarIdToDecl := map, decls := decls } => match lctx.find? fvarId with | none => lctx | some decl => let decl := f decl; { fvarIdToDecl := map.insert decl.fvarId decl, decls := decls.set decl.index decl } def updateBinderInfo (lctx : LocalContext) (fvarId : FVarId) (bi : BinderInfo) : LocalContext := modifyLocalDecl lctx fvarId fun decl => decl.updateBinderInfo bi @[export lean_local_ctx_num_indices] def numIndices (lctx : LocalContext) : Nat := lctx.decls.size @[export lean_local_ctx_get] def getAt! (lctx : LocalContext) (i : Nat) : Option LocalDecl := lctx.decls.get! i section universes u v variables {m : Type u → Type v} [Monad m] variable {β : Type u} @[specialize] def foldlM (lctx : LocalContext) (f : β → LocalDecl → m β) (b : β) : m β := lctx.decls.foldlM (fun b decl => match decl with | none => pure b | some decl => f b decl) b @[specialize] def forM (lctx : LocalContext) (f : LocalDecl → m PUnit) : m PUnit := lctx.decls.forM $ fun decl => match decl with | none => pure PUnit.unit | some decl => f decl @[specialize] def findDeclM? (lctx : LocalContext) (f : LocalDecl → m (Option β)) : m (Option β) := lctx.decls.findSomeM? $ fun decl => match decl with | none => pure none | some decl => f decl @[specialize] def findDeclRevM? (lctx : LocalContext) (f : LocalDecl → m (Option β)) : m (Option β) := lctx.decls.findSomeRevM? $ fun decl => match decl with | none => pure none | some decl => f decl @[specialize] def foldlFromM (lctx : LocalContext) (f : β → LocalDecl → m β) (b : β) (decl : LocalDecl) : m β := lctx.decls.foldlFromM (fun b decl => match decl with | none => pure b | some decl => f b decl) b decl.index end @[inline] def foldl {β} (lctx : LocalContext) (f : β → LocalDecl → β) (b : β) : β := Id.run $ lctx.foldlM f b @[inline] def findDecl? {β} (lctx : LocalContext) (f : LocalDecl → Option β) : Option β := Id.run $ lctx.findDeclM? f @[inline] def findDeclRev? {β} (lctx : LocalContext) (f : LocalDecl → Option β) : Option β := Id.run $ lctx.findDeclRevM? f @[inline] def foldlFrom {β} (lctx : LocalContext) (f : β → LocalDecl → β) (b : β) (decl : LocalDecl) : β := Id.run $ lctx.foldlFromM f b decl partial def isSubPrefixOfAux (a₁ a₂ : PArray (Option LocalDecl)) (exceptFVars : Array Expr) : Nat → Nat → Bool | i, j => if i < a₁.size then match a₁.get! i with | none => isSubPrefixOfAux (i+1) j | some decl₁ => if exceptFVars.any $ fun fvar => fvar.fvarId! == decl₁.fvarId then isSubPrefixOfAux (i+1) j else if j < a₂.size then match a₂.get! j with | none => isSubPrefixOfAux i (j+1) | some decl₂ => if decl₁.fvarId == decl₂.fvarId then isSubPrefixOfAux (i+1) (j+1) else isSubPrefixOfAux i (j+1) else false else true /- Given `lctx₁ - exceptFVars` of the form `(x_1 : A_1) ... (x_n : A_n)`, then return true iff there is a local context `B_1* (x_1 : A_1) ... B_n* (x_n : A_n)` which is a prefix of `lctx₂` where `B_i`'s are (possibly empty) sequences of local declarations. -/ def isSubPrefixOf (lctx₁ lctx₂ : LocalContext) (exceptFVars : Array Expr := #[]) : Bool := isSubPrefixOfAux lctx₁.decls lctx₂.decls exceptFVars 0 0 @[inline] def mkBinding (isLambda : Bool) (lctx : LocalContext) (xs : Array Expr) (b : Expr) : Expr := let b := b.abstract xs; xs.size.foldRev (fun i b => let x := xs.get! i; match lctx.findFVar? x with | some (LocalDecl.cdecl _ _ n ty bi) => let ty := ty.abstractRange i xs; if isLambda then Lean.mkLambda n bi ty b else Lean.mkForall n bi ty b | some (LocalDecl.ldecl _ _ n ty val nonDep) => if b.hasLooseBVar 0 then let ty := ty.abstractRange i xs; let val := val.abstractRange i xs; mkLet n ty val b nonDep else b.lowerLooseBVars 1 1 | none => panic! "unknown free variable") b def mkLambda (lctx : LocalContext) (xs : Array Expr) (b : Expr) : Expr := mkBinding true lctx xs b def mkForall (lctx : LocalContext) (xs : Array Expr) (b : Expr) : Expr := mkBinding false lctx xs b section universes u variables {m : Type → Type u} [Monad m] @[inline] def anyM (lctx : LocalContext) (p : LocalDecl → m Bool) : m Bool := lctx.decls.anyM $ fun d => match d with | some decl => p decl | none => pure false @[inline] def allM (lctx : LocalContext) (p : LocalDecl → m Bool) : m Bool := lctx.decls.allM $ fun d => match d with | some decl => p decl | none => pure true end @[inline] def any (lctx : LocalContext) (p : LocalDecl → Bool) : Bool := Id.run $ lctx.anyM p @[inline] def all (lctx : LocalContext) (p : LocalDecl → Bool) : Bool := Id.run $ lctx.allM p end LocalContext class MonadLCtx (m : Type → Type) := (getLCtx : m LocalContext) export MonadLCtx (getLCtx) instance monadLCtxTrans (m n) [MonadLCtx m] [MonadLift m n] : MonadLCtx n := { getLCtx := liftM (getLCtx : m _) } def replaceFVarIdAtLocalDecl (fvarId : FVarId) (e : Expr) (d : LocalDecl) : LocalDecl := if d.fvarId == fvarId then d else match d with | LocalDecl.cdecl idx id n type bi => LocalDecl.cdecl idx id n (type.replaceFVarId fvarId e) bi | LocalDecl.ldecl idx id n type val nonDep => LocalDecl.ldecl idx id n (type.replaceFVarId fvarId e) (val.replaceFVarId fvarId e) nonDep end Lean
e1c6e5da8ca0a666766b99a6b9ee61d289707fdd
cc060cf567f81c404a13ee79bf21f2e720fa6db0
/lean/20170509-transport_lemmas.lean
1a04228bfba1677c0fce195db653acd47501fdcf
[ "Apache-2.0" ]
permissive
semorrison/proof
cf0a8c6957153bdb206fd5d5a762a75958a82bca
5ee398aa239a379a431190edbb6022b1a0aa2c70
refs/heads/master
1,610,414,502,842
1,518,696,851,000
1,518,696,851,000
78,375,937
2
1
null
null
null
null
UTF-8
Lean
false
false
12,665
lean
definition {u v} transport {A : Type u} { P : A → Type v} {x y : A} (p : x = y) (u : P x) : P y := by induction p; exact u definition {u v w} apdt011 {A : Type u} {Z : Type w} {B : A → Type v} (f : Πa, B a → Z) {a a' : A} {b : B a} {b' : B a'} (Ha : a = a') (Hb : transport Ha b = b') : f a b = f a' b' := by cases Ha; cases Hb; reflexivity set_option trace.check true -- set_option pp.implicit true -- @NaturalTransformation.components ?M_1 ?M_2 ?M_3 ?M_4 : -- @NaturalTransformation ?M_1 ?M_2 ?M_3 ?M_4 → Π (X : ?M_1.Obj), ?M_2.Hom (⇑?M_3 X) (⇑?M_4 X) -- α === Type (max u v) -- a === (@NaturalTransformation (C × C) C (@MonoidalStructure.tensor C m) -- (@FunctorComposition (C × C) (C × C) C (SwitchProductCategory C C) -- (@FunctorComposition (C × C) (C × C) C (SwitchProductCategory C C) (@MonoidalStructure.tensor C m)))) -- T === (λ (_x : Type (max u v)), _x) -- t : T a == a -- t === (@vertical_composition_of_NaturalTransformations (C × C) C (@MonoidalStructure.tensor C m) -- (@FunctorComposition (C × C) (C × C) C (SwitchProductCategory C C) (@MonoidalStructure.tensor C m)) -- (@FunctorComposition (C × C) (C × C) C (SwitchProductCategory C C) -- (@FunctorComposition (C × C) (C × C) C (SwitchProductCategory C C) (@MonoidalStructure.tensor C m))) -- (@isomorphism.Isomorphism.morphism (FunctorCategory (C × C) C) (@MonoidalStructure.tensor C m) -- (@FunctorComposition (C × C) (C × C) C (SwitchProductCategory C C) (@MonoidalStructure.tensor C m)) -- (@braided_monoidal_category.Symmetry.braiding C m β)) -- (@whisker_on_left (C × C) (C × C) C (SwitchProductCategory C C) (@MonoidalStructure.tensor C m) -- (@FunctorComposition (C × C) (C × C) C (SwitchProductCategory C C) (@MonoidalStructure.tensor C m)) -- (@isomorphism.Isomorphism.morphism (FunctorCategory (C × C) C) (@MonoidalStructure.tensor C m) -- (@FunctorComposition (C × C) (C × C) C (SwitchProductCategory C C) (@MonoidalStructure.tensor C m)) -- (@braided_monoidal_category.Symmetry.braiding C m β)))) -- b === (@NaturalTransformation (C × C) C (@MonoidalStructure.tensor C m) (@MonoidalStructure.tensor C m)) -- e : a = b -- @eq.rec α a T t b e : T b -- T b == b -- now we want to apply -- f === @NaturalTransformation.components (C × C) C (@MonoidalStructure.tensor C m) (@MonoidalStructure.tensor C m) -- to @eq.rec α a T b e. -- actually, we're going to need to think of this as applying -- f' === @NaturalTransformation.components (C × C) C (@MonoidalStructure.tensor C m) -- : Π (F : Functor (C × C) C), NaturalTransformation m.tensor F → Π (x : (C × C).Obj), C.Hom (m.tensor x) (F x) -- and here we may as well introduce S : Functor (C × C) C → Type as S F = Π (x : (C × C).Obj), C.Hom (m.tensor x) (F x), -- and then write f' : Π (F : Functor (C × C) C), NaturalTransformation m.tensor F → S F -- -- Thus we want to start with f' (@MonoidalStructure.tensor C m) (@eq.rec α a T t b e) : S (@MonoidalStructure.tensor C m) -- and by application of the lemma we're designing obtain ...? -- f' (@FunctorComposition (C × C) (C × C) C (SwitchProductCategory C C) -- (@FunctorComposition (C × C) (C × C) C (SwitchProductCategory C C) (@MonoidalStructure.tensor C m))) -- a -- Now this thing is of type S (@FunctorComposition (C × C) (C × C) C (SwitchProductCategory C C) -- (@FunctorComposition (C × C) (C × C) C (SwitchProductCategory C C) (@MonoidalStructure.tensor C m))) -- which is no good, so we're going to have to transport it through the type family S. But where do we obtain our -- path/equation to transport along? Somehow we take e : a = b, and think of that actually as e : R a' = R b' ... nope. ------------- -- 20170508 -- -- (@NaturalTransformation.components (C × C) C -- (@FunctorComposition (C × C) (C × C) C (SwitchProductCategory C C) (@MonoidalStructure.tensor C m)) -- (@MonoidalStructure.tensor C m) -- (@eq.rec (Functor (C × C) C) -- (@FunctorComposition (C × C) (C × C) C (IdentityFunctor (C × C)) (@MonoidalStructure.tensor C m)) -- (@NaturalTransformation (C × C) C -- (@FunctorComposition (C × C) (C × C) C (SwitchProductCategory C C) (@MonoidalStructure.tensor C m))) -- (t : NaturalTransformation (switch tensor) (id tensor)) -- (@MonoidalStructure.tensor C m) -- (FunctorComposition.left_identity (C × C) C (@MonoidalStructure.tensor C m))) -- X) -- S = (@NaturalTransformation (C × C) C -- f = @NaturalTransformation.components (C × C) C -- f : Π a a' : A, Π t : S a a', Z a a' -- Z a a' = Π X : (C × C).Obj, C.Hom (a X) (a' X) -- a = (@FunctorComposition (C × C) (C × C) C (SwitchProductCategory C C) (@MonoidalStructure.tensor C m)) -- a' = (@FunctorComposition (C × C) (C × C) C (IdentityFunctor (C × C)) (@MonoidalStructure.tensor C m)) -- A = (Functor (C × C) C) -- a a' : A -- b = (@MonoidalStructure.tensor C m) -- b : A -- p : a' = b -- t : S a a' -- (@eq.rec A a' (S a) t b p) : S a b -- f a b (@eq.rec A a' (S a) t b p) : Z a b -- f a a' t : Z a a' -- (@eq.rec A a' (Z a) (f a a' t) b p) : Z a b lemma {u1 u2 u3 u4} v2 { α : Type u1 } { β : Type u2 } { S : α → β → Type u3 } { Z : α → β → Type u4 } { a : α } { b : β } { t : S a b } { b' : β } { p : b = b' } ( f : Π ( c : α ) ( d : β ) , S c d → Z c d ): f a b' (@eq.rec β b (S a) t b' p) = (@eq.rec β b (Z a) (f a b t) b' p) := begin induction p, reflexivity end lemma {u1 u2 u3} v1 { β : Type u1 } { S : β → Type u2 } { Z : β → Type u3 } { b : β } { t : S b } { b' : β } { p : b = b' } ( f : Π d : β, S d → Z d ) : f b' (@eq.rec β b S t b' p) = (@eq.rec β b Z (f b t) b' p) := begin induction p, reflexivity end -- (@NaturalTransformation.components (C × C) C -- (@FunctorComposition (C × C) (C × C) C (SwitchProductCategory C C) (@MonoidalStructure.tensor C m)) -- (@FunctorComposition (C × C) (C × C) C (IdentityFunctor (C × C)) (@MonoidalStructure.tensor C m)) -- (@eq.rec (Functor (C × C) (C × C)) -- (@FunctorComposition (C × C) (C × C) (C × C) (SwitchProductCategory C C) (SwitchProductCategory C C)) -- (λ (a : Functor (C × C) (C × C)), -- @NaturalTransformation (C × C) C -- (@FunctorComposition (C × C) (C × C) C (SwitchProductCategory C C) (@MonoidalStructure.tensor C m)) -- (@FunctorComposition (C × C) (C × C) C a (@MonoidalStructure.tensor C m))) -- (t : NaturalTransformation (switch tensor) (switch switch tensor)) -- (IdentityFunctor (C × C)) -- (switch_twice_is_the_identity C C))) -- f = @NaturalTransformation.components (C × C) C -- α = Functor (C × C) C -- a : α -- a = (@FunctorComposition (C × C) (C × C) C (SwitchProductCategory C C) (@MonoidalStructure.tensor C m)) -- β = Functor (C × C) C -- f : Π (a : α) (b : β), S a b → Z a b -- γ = (Functor (C × C) (C × C) -- g = switch switch -- g' = id -- p : g = g' -- R : γ → β -- = λ g, (g tensor) -- S = λ a b, NaturalTransformation a b -- -- f a (R g') (@eq.rec γ g (S a) t g' p) -- c' = (@FunctorComposition (C × C) (C × C) C (IdentityFunctor (C × C)) (@MonoidalStructure.tensor C m)) -- c'' = (@FunctorComposition (C × C) (C × C) C (@FunctorComposition (C × C) (C × C) (C × C) (SwitchProductCategory C C) (SwitchProductCategory C C)) (@MonoidalStructure.tensor C m)) -- eq.rec ... : NaturalTransformation c c' -- γ = (Functor (C × C) (C × C) -- g = switch switch -- S = Π (a : α) (g : γ), NaturalTransformation a (R g) -- t : NaturalTransformation a (R g) -- t : S a g -- g' = Identity (C × C) -- p : g = g' -- c' = R g' -- c'' = R g -- R = Π g : γ, (g tensor) -- R : γ → β -- f a c' t' : Z a c' -- f a (R g') (@eq.rec γ g S t g' p) -- f a (@eq.rec γ g R c'' g' p) (@eq.rec γ g S t g' p) -- @eq.rec γ g (Z a (R g)) (f a (R g) t) g' p -- @eq.rec γ g (Z a ???) (f a (@eq.rec γ g' R c' g (eq.symm p)) t) g' p lemma {u1 u2 u3 u4 u5} w { α : Type u1 } { β : Type u2 } { γ : Type u3 } { S : α → β → Type u4 } { Z : α → β → Type u5 } { a : α } { g : γ } ( R : γ → β ) { t : S a (R g) } { g' : γ } { p : g = g' } ( f : Π (a : α) (b : β), S a b → Z a b ): f a (R g') (@eq.rec γ g (λ g, S a (R g)) t g' p) = @eq.rec γ g (λ g, Z a (R g)) (f a (R g) t) g' p := begin induction p, reflexivity end -- -- (@eq.rec (Functor (C × C) C) -- (@FunctorComposition (C × C) (C × C) C (IdentityFunctor (C × C)) (@MonoidalStructure.tensor C m)) -- (λ (G : Functor (C × C) C), -- Π (X : (C × C).Obj), -- C.Hom -- (@Functor.onObjects (C × C) C -- (@FunctorComposition (C × C) (C × C) C (IdentityFunctor (C × C)) -- (@MonoidalStructure.tensor C m)) -- X) -- (@Functor.onObjects (C × C) C G X)) -- (λ (X : (C × C).Obj), -- C.identity -- (@Functor.onObjects (C × C) C -- (@FunctorComposition (C × C) (C × C) C (IdentityFunctor (C × C)) -- (@MonoidalStructure.tensor C m)) -- X)) -- (@MonoidalStructure.tensor C m) -- (@squared_Braiding._proof_3 C m) -- X) lemma {u1 u2 u3} b { α : Type u1 } { a : α } { β : Type u2 } { Z : α → β → Type u3 } { t : Π (b : β), Z a b } { a' : α } { p : a = a' } : @eq.rec α a _ t a' p = λ b : β, @eq.rec α a (λ _a, Z _a b) (t b) a' p := begin induction p, reflexivity end -- (@eq.rec (Functor (C × C) C) -- (@FunctorComposition (C × C) (C × C) C (IdentityFunctor (C × C)) (@MonoidalStructure.tensor C m)) -- (λ (_a : Functor (C × C) C), -- C.Hom -- (@Functor.onObjects (C × C) C -- (@FunctorComposition (C × C) (C × C) C (IdentityFunctor (C × C)) -- (@MonoidalStructure.tensor C m)) -- (X_1, X_2)) -- (@Functor.onObjects (C × C) C _a (X_1, X_2))) -- (C.identity -- (@Functor.onObjects (C × C) C -- (@FunctorComposition (C × C) (C × C) C (IdentityFunctor (C × C)) -- (@MonoidalStructure.tensor C m)) -- (X_1, X_2))) -- (@MonoidalStructure.tensor C m) -- (@squared_Braiding._proof_3 C m)) -- α = (Functor (C × C) C) -- a = (@FunctorComposition (C × C) (C × C) C (IdentityFunctor (C × C)) (@MonoidalStructure.tensor C m)) -- f = C.identity -- : Π X : C.Obj, C.Hom X X -- r = @Functor.onObjects (C × C) C -- x : (C × C).Obj -- r a x : C.Obj -- t = f (r a x) -- : C.Hom (r a x) (r a x) lemma {u1 u2 u3 u4} pull_function_out { α : Type u1 } { a : α } { β : Type u2 } { Z : β → Type u3 } { γ : Type u4 } { r : Π a : α, γ → β } { x : γ } { a' : α } { p : a = a' } ( f : Π (b : β), Z b ) : @eq.rec α a _ (f (r a x)) a' p = f (r a' x) := begin induction p, reflexivity end -- This seems sensible, but applies too often. lemma {u} bar { α : Type u } { a : α } { b : α } ( p : a = b ) : @eq.rec α a (λ b: α, b = a) (eq.refl a) b p = eq.symm p := begin cases p, reflexivity end lemma {u} foo { α : Type u } { a b : α } { p : a = b } : eq.symm (eq.symm p) = p := by reflexivity @[simp] lemma {u v w} function_of_eq.rec { α : Type u } { a : α } { T : α → Type v } { S : α → Type w } ( t : T a ) { b : α } ( e : a = b ) ( f : Π { c : α }, T c → S c ) : @f b ( @eq.rec α a T t b e ) = @eq.rec α a S (@f a t) b e := begin cases e, reflexivity end @[simp] lemma {u v w} function_of_eq.drec { α : Type u } { a : α } { T : Π b : α, a = b → Type v } { S : Π b : α, a = b → Type v } ( t : T a (eq.refl a)) { b : α } ( e : a = b ) ( f : Π { c : α } { p : a = c }, T c p → S c p ) : f ( @eq.drec α a T t b e ) = @eq.drec α a S (f t) b e := begin cases e, reflexivity end lemma z {A : Type} { X : A } : (eq.mpr (propext (eq_self_iff_true X)) trivial) = rfl := begin -- unfold trivial, reflexivity end
3ed6c5e479498ea71b149bbdbaec923398e481b5
4950bf76e5ae40ba9f8491647d0b6f228ddce173
/src/algebra/field.lean
d8efa5e834a54f947b8586076322919263baf5a4
[ "Apache-2.0" ]
permissive
ntzwq/mathlib
ca50b21079b0a7c6781c34b62199a396dd00cee2
36eec1a98f22df82eaccd354a758ef8576af2a7f
refs/heads/master
1,675,193,391,478
1,607,822,996,000
1,607,822,996,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,876
lean
/- Copyright (c) 2014 Robert Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Lewis, Leonardo de Moura, Johannes Hölzl, Mario Carneiro -/ import algebra.ring.basic import algebra.group_with_zero open set set_option old_structure_cmd true universe u variables {α : Type u} /-- A `division_ring` is a `ring` with multiplicative inverses for nonzero elements -/ @[protect_proj, ancestor ring has_inv] class division_ring (α : Type u) extends ring α, has_inv α, nontrivial α := (mul_inv_cancel : ∀ {a : α}, a ≠ 0 → a * a⁻¹ = 1) (inv_mul_cancel : ∀ {a : α}, a ≠ 0 → a⁻¹ * a = 1) (inv_zero : (0 : α)⁻¹ = 0) section division_ring variables [division_ring α] {a b : α} @[priority 100] -- see Note [lower instance priority] instance division_ring_has_div : has_div α := ⟨λ a b, a * b⁻¹⟩ /-- Every division ring is a `group_with_zero`. -/ @[priority 100] -- see Note [lower instance priority] instance division_ring.to_group_with_zero : group_with_zero α := { .. ‹division_ring α›, .. (infer_instance : semiring α) } lemma inverse_eq_has_inv : (ring.inverse : α → α) = has_inv.inv := begin ext x, by_cases hx : x = 0, { simp [hx] }, { exact ring.inverse_unit (units.mk0 x hx) } end @[field_simps] lemma inv_eq_one_div (a : α) : a⁻¹ = 1 / a := by simp lemma mul_one_div (a b : α) : a * (1 / b) = a / b := by rw [← inv_eq_one_div, div_eq_mul_inv] local attribute [simp] division_def mul_comm mul_assoc mul_left_comm mul_inv_cancel inv_mul_cancel @[field_simps] lemma mul_div_assoc' (a b c : α) : a * (b / c) = (a * b) / c := by simp [mul_div_assoc] lemma one_div_neg_one_eq_neg_one : (1:α) / (-1) = -1 := have (-1) * (-1) = (1:α), by rw [neg_mul_neg, one_mul], eq.symm (eq_one_div_of_mul_eq_one this) lemma one_div_neg_eq_neg_one_div (a : α) : 1 / (- a) = - (1 / a) := calc 1 / (- a) = 1 / ((-1) * a) : by rw neg_eq_neg_one_mul ... = (1 / a) * (1 / (- 1)) : by rw one_div_mul_one_div_rev ... = (1 / a) * (-1) : by rw one_div_neg_one_eq_neg_one ... = - (1 / a) : by rw [mul_neg_eq_neg_mul_symm, mul_one] lemma div_neg_eq_neg_div (a b : α) : b / (- a) = - (b / a) := calc b / (- a) = b * (1 / (- a)) : by rw [← inv_eq_one_div, division_def] ... = b * -(1 / a) : by rw one_div_neg_eq_neg_one_div ... = -(b * (1 / a)) : by rw neg_mul_eq_mul_neg ... = - (b / a) : by rw mul_one_div lemma neg_div (a b : α) : (-b) / a = - (b / a) := by rw [neg_eq_neg_one_mul, mul_div_assoc, ← neg_eq_neg_one_mul] @[field_simps] lemma neg_div' {α : Type*} [division_ring α] (a b : α) : - (b / a) = (-b) / a := by simp [neg_div] lemma neg_div_neg_eq (a b : α) : (-a) / (-b) = a / b := by rw [div_neg_eq_neg_div, neg_div, neg_neg] @[field_simps] lemma div_add_div_same (a b c : α) : a / c + b / c = (a + b) / c := by simpa only [div_eq_mul_inv] using (right_distrib a b (c⁻¹)).symm lemma div_sub_div_same (a b c : α) : (a / c) - (b / c) = (a - b) / c := by rw [sub_eq_add_neg, ← neg_div, div_add_div_same, sub_eq_add_neg] lemma neg_inv : - a⁻¹ = (- a)⁻¹ := by rw [inv_eq_one_div, inv_eq_one_div, div_neg_eq_neg_div] lemma add_div (a b c : α) : (a + b) / c = a / c + b / c := (div_add_div_same _ _ _).symm lemma sub_div (a b c : α) : (a - b) / c = a / c - b / c := (div_sub_div_same _ _ _).symm lemma div_neg (a : α) : a / -b = -(a / b) := by rw [← div_neg_eq_neg_div] lemma inv_neg : (-a)⁻¹ = -(a⁻¹) := by rw neg_inv lemma one_div_mul_add_mul_one_div_eq_one_div_add_one_div (ha : a ≠ 0) (hb : b ≠ 0) : (1 / a) * (a + b) * (1 / b) = 1 / a + 1 / b := by rw [(left_distrib (1 / a)), (one_div_mul_cancel ha), right_distrib, one_mul, mul_assoc, (mul_one_div_cancel hb), mul_one, add_comm] lemma one_div_mul_sub_mul_one_div_eq_one_div_add_one_div (ha : a ≠ 0) (hb : b ≠ 0) : (1 / a) * (b - a) * (1 / b) = 1 / a - 1 / b := by rw [(mul_sub_left_distrib (1 / a)), (one_div_mul_cancel ha), mul_sub_right_distrib, one_mul, mul_assoc, (mul_one_div_cancel hb), mul_one] lemma add_div_eq_mul_add_div (a b : α) {c : α} (hc : c ≠ 0) : a + b / c = (a * c + b) / c := (eq_div_iff_mul_eq hc).2 $ by rw [right_distrib, (div_mul_cancel _ hc)] @[priority 100] -- see Note [lower instance priority] instance division_ring.to_domain : domain α := { ..‹division_ring α›, ..(by apply_instance : semiring α), ..(by apply_instance : no_zero_divisors α) } end division_ring /-- A `field` is a `comm_ring` with multiplicative inverses for nonzero elements -/ @[protect_proj, ancestor division_ring comm_ring] class field (α : Type u) extends comm_ring α, has_inv α, nontrivial α := (mul_inv_cancel : ∀ {a : α}, a ≠ 0 → a * a⁻¹ = 1) (inv_zero : (0 : α)⁻¹ = 0) section field variable [field α] @[priority 100] -- see Note [lower instance priority] instance field.to_division_ring : division_ring α := { inv_mul_cancel := λ _ h, by rw [mul_comm, field.mul_inv_cancel h] ..show field α, by apply_instance } /-- Every field is a `comm_group_with_zero`. -/ @[priority 100] -- see Note [lower instance priority] instance field.to_comm_group_with_zero : comm_group_with_zero α := { .. (_ : group_with_zero α), .. ‹field α› } lemma one_div_add_one_div {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : 1 / a + 1 / b = (a + b) / (a * b) := by rw [add_comm, ← div_mul_left ha, ← div_mul_right _ hb, division_def, division_def, division_def, ← right_distrib, mul_comm a] local attribute [simp] mul_assoc mul_comm mul_left_comm lemma div_add_div (a : α) {b : α} (c : α) {d : α} (hb : b ≠ 0) (hd : d ≠ 0) : (a / b) + (c / d) = ((a * d) + (b * c)) / (b * d) := by rw [← mul_div_mul_right _ b hd, ← mul_div_mul_left c d hb, div_add_div_same] @[field_simps] lemma div_sub_div (a : α) {b : α} (c : α) {d : α} (hb : b ≠ 0) (hd : d ≠ 0) : (a / b) - (c / d) = ((a * d) - (b * c)) / (b * d) := begin simp [sub_eq_add_neg], rw [neg_eq_neg_one_mul, ← mul_div_assoc, div_add_div _ _ hb hd, ← mul_assoc, mul_comm b, mul_assoc, ← neg_eq_neg_one_mul] end lemma inv_add_inv {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ + b⁻¹ = (a + b) / (a * b) := by rw [inv_eq_one_div, inv_eq_one_div, one_div_add_one_div ha hb] lemma inv_sub_inv {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ - b⁻¹ = (b - a) / (a * b) := by rw [inv_eq_one_div, inv_eq_one_div, div_sub_div _ _ ha hb, one_mul, mul_one] @[field_simps] lemma add_div' (a b c : α) (hc : c ≠ 0) : b + a / c = (b * c + a) / c := by simpa using div_add_div b a one_ne_zero hc @[field_simps] lemma sub_div' (a b c : α) (hc : c ≠ 0) : b - a / c = (b * c - a) / c := by simpa using div_sub_div b a one_ne_zero hc @[field_simps] lemma div_add' (a b c : α) (hc : c ≠ 0) : a / c + b = (a + b * c) / c := by rwa [add_comm, add_div', add_comm] @[field_simps] lemma div_sub' (a b c : α) (hc : c ≠ 0) : a / c - b = (a - c * b) / c := by simpa using div_sub_div a b hc one_ne_zero @[priority 100] -- see Note [lower instance priority] instance field.to_integral_domain : integral_domain α := { ..‹field α›, ..division_ring.to_domain } end field section is_field /-- A predicate to express that a ring is a field. This is mainly useful because such a predicate does not contain data, and can therefore be easily transported along ring isomorphisms. Additionaly, this is useful when trying to prove that a particular ring structure extends to a field. -/ structure is_field (R : Type u) [ring R] : Prop := (exists_pair_ne : ∃ (x y : R), x ≠ y) (mul_comm : ∀ (x y : R), x * y = y * x) (mul_inv_cancel : ∀ {a : R}, a ≠ 0 → ∃ b, a * b = 1) /-- Transferring from field to is_field -/ lemma field.to_is_field (R : Type u) [field R] : is_field R := { mul_inv_cancel := λ a ha, ⟨a⁻¹, field.mul_inv_cancel ha⟩, ..‹field R› } open_locale classical /-- Transferring from is_field to field -/ noncomputable def is_field.to_field (R : Type u) [ring R] (h : is_field R) : field R := { inv := λ a, if ha : a = 0 then 0 else classical.some (is_field.mul_inv_cancel h ha), inv_zero := dif_pos rfl, mul_inv_cancel := λ a ha, begin convert classical.some_spec (is_field.mul_inv_cancel h ha), exact dif_neg ha end, .. ‹ring R›, ..h } /-- For each field, and for each nonzero element of said field, there is a unique inverse. Since `is_field` doesn't remember the data of an `inv` function and as such, a lemma that there is a unique inverse could be useful. -/ lemma uniq_inv_of_is_field (R : Type u) [ring R] (hf : is_field R) : ∀ (x : R), x ≠ 0 → ∃! (y : R), x * y = 1 := begin intros x hx, apply exists_unique_of_exists_of_unique, { exact hf.mul_inv_cancel hx }, { intros y z hxy hxz, calc y = y * (x * z) : by rw [hxz, mul_one] ... = (x * y) * z : by rw [← mul_assoc, hf.mul_comm y x] ... = z : by rw [hxy, one_mul] } end end is_field namespace ring_hom section variables {R K : Type*} [semiring R] [division_ring K] (f : R →+* K) @[simp] lemma map_units_inv (u : units R) : f ↑u⁻¹ = (f ↑u)⁻¹ := (f : R →* K).map_units_inv u end section variables {β γ : Type*} [division_ring α] [semiring β] [nontrivial β] [division_ring γ] (f : α →+* β) (g : α →+* γ) {x y : α} lemma map_ne_zero : f x ≠ 0 ↔ x ≠ 0 := f.to_monoid_with_zero_hom.map_ne_zero lemma map_eq_zero : f x = 0 ↔ x = 0 := f.to_monoid_with_zero_hom.map_eq_zero variables (x y) lemma map_inv : g x⁻¹ = (g x)⁻¹ := g.to_monoid_with_zero_hom.map_inv' x lemma map_div : g (x / y) = g x / g y := g.to_monoid_with_zero_hom.map_div x y protected lemma injective : function.injective f := f.injective_iff.2 $ λ x, f.map_eq_zero.1 end end ring_hom
7ab1e86febb56e5083f8bf4d2f238824beb4a51d
3f7026ea8bef0825ca0339a275c03b911baef64d
/src/data/equiv/basic.lean
e9409915dfbb2a7b37675489483e683748bb7ccd
[ "Apache-2.0" ]
permissive
rspencer01/mathlib
b1e3afa5c121362ef0881012cc116513ab09f18c
c7d36292c6b9234dc40143c16288932ae38fdc12
refs/heads/master
1,595,010,346,708
1,567,511,503,000
1,567,511,503,000
206,071,681
0
0
Apache-2.0
1,567,513,643,000
1,567,513,643,000
null
UTF-8
Lean
false
false
39,727
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Mario Carneiro In the standard library we cannot assume the univalence axiom. We say two types are equivalent if they are isomorphic. Two equivalent types have the same cardinality. -/ import tactic.split_ifs logic.function logic.unique data.set.function data.bool data.quot open function universes u v w variables {α : Sort u} {β : Sort v} {γ : Sort w} /-- `α ≃ β` is the type of functions from `α → β` with a two-sided inverse. -/ structure equiv (α : Sort*) (β : Sort*) := (to_fun : α → β) (inv_fun : β → α) (left_inv : left_inverse inv_fun to_fun) (right_inv : right_inverse inv_fun to_fun) namespace equiv /-- `perm α` is the type of bijections from `α` to itself. -/ @[reducible] def perm (α : Sort*) := equiv α α infix ` ≃ `:25 := equiv instance : has_coe_to_fun (α ≃ β) := ⟨_, to_fun⟩ @[simp] theorem coe_fn_mk (f : α → β) (g l r) : (equiv.mk f g l r : α → β) = f := rfl theorem eq_of_to_fun_eq : ∀ {e₁ e₂ : equiv α β}, (e₁ : α → β) = e₂ → e₁ = e₂ | ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ h := have f₁ = f₂, from h, have g₁ = g₂, from funext $ assume x, have f₁ (g₁ x) = f₂ (g₂ x), from (r₁ x).trans (r₂ x).symm, have f₁ (g₁ x) = f₁ (g₂ x), by { subst f₂, exact this }, show g₁ x = g₂ x, from injective_of_left_inverse l₁ this, by simp * @[extensionality] lemma ext (f g : equiv α β) (H : ∀ x, f x = g x) : f = g := eq_of_to_fun_eq (funext H) @[extensionality] lemma perm.ext (σ τ : equiv.perm α) (H : ∀ x, σ x = τ x) : σ = τ := equiv.ext _ _ H @[refl] protected def refl (α : Sort*) : α ≃ α := ⟨id, id, λ x, rfl, λ x, rfl⟩ @[symm] protected def symm (e : α ≃ β) : β ≃ α := ⟨e.inv_fun, e.to_fun, e.right_inv, e.left_inv⟩ @[trans] protected def trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : α ≃ γ := ⟨e₂.to_fun ∘ e₁.to_fun, e₁.inv_fun ∘ e₂.inv_fun, e₂.left_inv.comp e₁.left_inv, e₂.right_inv.comp e₁.right_inv⟩ protected theorem injective : ∀ f : α ≃ β, injective f | ⟨f, g, h₁, h₂⟩ := injective_of_left_inverse h₁ protected theorem surjective : ∀ f : α ≃ β, surjective f | ⟨f, g, h₁, h₂⟩ := surjective_of_has_right_inverse ⟨_, h₂⟩ protected theorem bijective (f : α ≃ β) : bijective f := ⟨f.injective, f.surjective⟩ protected theorem subsingleton (e : α ≃ β) : ∀ [subsingleton β], subsingleton α | ⟨H⟩ := ⟨λ a b, e.injective (H _ _)⟩ protected def decidable_eq (e : α ≃ β) [H : decidable_eq β] : decidable_eq α | a b := decidable_of_iff _ e.injective.eq_iff lemma nonempty_iff_nonempty : α ≃ β → (nonempty α ↔ nonempty β) | ⟨f, g, _, _⟩ := nonempty.congr f g protected def cast {α β : Sort*} (h : α = β) : α ≃ β := ⟨cast h, cast h.symm, λ x, by { cases h, refl }, λ x, by { cases h, refl }⟩ @[simp] theorem coe_fn_symm_mk (f : α → β) (g l r) : ((equiv.mk f g l r).symm : β → α) = g := rfl @[simp] theorem refl_apply (x : α) : equiv.refl α x = x := rfl @[simp] theorem trans_apply (f : α ≃ β) (g : β ≃ γ) (a : α) : (f.trans g) a = g (f a) := rfl @[simp] theorem apply_symm_apply : ∀ (e : α ≃ β) (x : β), e (e.symm x) = x | ⟨f₁, g₁, l₁, r₁⟩ x := by { simp [equiv.symm], rw r₁ } @[simp] theorem symm_apply_apply : ∀ (e : α ≃ β) (x : α), e.symm (e x) = x | ⟨f₁, g₁, l₁, r₁⟩ x := by { simp [equiv.symm], rw l₁ } @[simp] lemma symm_trans_apply (f : α ≃ β) (g : β ≃ γ) (a : γ) : (f.trans g).symm a = f.symm (g.symm a) := rfl @[simp] theorem apply_eq_iff_eq : ∀ (f : α ≃ β) (x y : α), f x = f y ↔ x = y | ⟨f₁, g₁, l₁, r₁⟩ x y := (injective_of_left_inverse l₁).eq_iff @[simp] theorem cast_apply {α β} (h : α = β) (x : α) : equiv.cast h x = cast h x := rfl lemma symm_apply_eq {α β} (e : α ≃ β) {x y} : e.symm x = y ↔ x = e y := ⟨λ H, by simp [H.symm], λ H, by simp [H]⟩ lemma eq_symm_apply {α β} (e : α ≃ β) {x y} : y = e.symm x ↔ e y = x := (eq_comm.trans e.symm_apply_eq).trans eq_comm @[simp] theorem symm_symm (e : α ≃ β) : e.symm.symm = e := by { cases e, refl } @[simp] theorem symm_symm_apply (e : α ≃ β) (a : α) : e.symm.symm a = e a := by { cases e, refl } @[simp] theorem trans_refl (e : α ≃ β) : e.trans (equiv.refl β) = e := by { cases e, refl } @[simp] theorem refl_trans (e : α ≃ β) : (equiv.refl α).trans e = e := by { cases e, refl } @[simp] theorem symm_trans (e : α ≃ β) : e.symm.trans e = equiv.refl β := ext _ _ (by simp) @[simp] theorem trans_symm (e : α ≃ β) : e.trans e.symm = equiv.refl α := ext _ _ (by simp) lemma trans_assoc {δ} (ab : α ≃ β) (bc : β ≃ γ) (cd : γ ≃ δ) : (ab.trans bc).trans cd = ab.trans (bc.trans cd) := equiv.ext _ _ $ assume a, rfl theorem left_inverse_symm (f : equiv α β) : left_inverse f.symm f := f.left_inv theorem right_inverse_symm (f : equiv α β) : function.right_inverse f.symm f := f.right_inv def equiv_congr {δ} (ab : α ≃ β) (cd : γ ≃ δ) : (α ≃ γ) ≃ (β ≃ δ) := ⟨ λac, (ab.symm.trans ac).trans cd, λbd, ab.trans $ bd.trans $ cd.symm, assume ac, begin simp [trans_assoc], rw [← trans_assoc], simp end, assume ac, begin simp [trans_assoc], rw [← trans_assoc], simp end, ⟩ def perm_congr {α : Type*} {β : Type*} (e : α ≃ β) : perm α ≃ perm β := equiv_congr e e protected lemma image_eq_preimage {α β} (e : α ≃ β) (s : set α) : e '' s = e.symm ⁻¹' s := set.ext $ assume x, set.mem_image_iff_of_inverse e.left_inv e.right_inv protected lemma subset_image {α β} (e : α ≃ β) (s : set α) (t : set β) : t ⊆ e '' s ↔ e.symm '' t ⊆ s := by rw [set.image_subset_iff, e.image_eq_preimage] lemma symm_image_image {α β} (f : equiv α β) (s : set α) : f.symm '' (f '' s) = s := by { rw [← set.image_comp], simp } protected lemma image_compl {α β} (f : equiv α β) (s : set α) : f '' -s = -(f '' s) := set.image_compl_eq f.bijective /- The group of permutations (self-equivalences) of a type `α` -/ namespace perm instance perm_group {α : Type u} : group (perm α) := begin refine { mul := λ f g, equiv.trans g f, one := equiv.refl α, inv:= equiv.symm, ..}; intros; apply equiv.ext; try { apply trans_apply }, apply symm_apply_apply end @[simp] theorem mul_apply {α : Type u} (f g : perm α) (x) : (f * g) x = f (g x) := equiv.trans_apply _ _ _ @[simp] theorem one_apply {α : Type u} (x) : (1 : perm α) x = x := rfl @[simp] lemma inv_apply_self {α : Type u} (f : perm α) (x) : f⁻¹ (f x) = x := equiv.symm_apply_apply _ _ @[simp] lemma apply_inv_self {α : Type u} (f : perm α) (x) : f (f⁻¹ x) = x := equiv.apply_symm_apply _ _ lemma one_def {α : Type u} : (1 : perm α) = equiv.refl α := rfl lemma mul_def {α : Type u} (f g : perm α) : f * g = g.trans f := rfl lemma inv_def {α : Type u} (f : perm α) : f⁻¹ = f.symm := rfl end perm def equiv_empty (h : α → false) : α ≃ empty := ⟨λ x, (h x).elim, λ e, e.rec _, λ x, (h x).elim, λ e, e.rec _⟩ def false_equiv_empty : false ≃ empty := equiv_empty _root_.id def equiv_pempty (h : α → false) : α ≃ pempty := ⟨λ x, (h x).elim, λ e, e.rec _, λ x, (h x).elim, λ e, e.rec _⟩ def false_equiv_pempty : false ≃ pempty := equiv_pempty _root_.id def empty_equiv_pempty : empty ≃ pempty := equiv_pempty $ empty.rec _ def pempty_equiv_pempty : pempty.{v} ≃ pempty.{w} := equiv_pempty pempty.elim def empty_of_not_nonempty {α : Sort*} (h : ¬ nonempty α) : α ≃ empty := equiv_empty $ assume a, h ⟨a⟩ def pempty_of_not_nonempty {α : Sort*} (h : ¬ nonempty α) : α ≃ pempty := equiv_pempty $ assume a, h ⟨a⟩ def prop_equiv_punit {p : Prop} (h : p) : p ≃ punit := ⟨λ x, (), λ x, h, λ _, rfl, λ ⟨⟩, rfl⟩ def true_equiv_punit : true ≃ punit := prop_equiv_punit trivial protected def ulift {α : Type u} : ulift α ≃ α := ⟨ulift.down, ulift.up, ulift.up_down, λ a, rfl⟩ protected def plift : plift α ≃ α := ⟨plift.down, plift.up, plift.up_down, plift.down_up⟩ @[congr] def arrow_congr {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : (α₁ → β₁) ≃ (α₂ → β₂) := { to_fun := λ f, e₂.to_fun ∘ f ∘ e₁.inv_fun, inv_fun := λ f, e₂.inv_fun ∘ f ∘ e₁.to_fun, left_inv := λ f, funext $ λ x, by { dsimp, rw [e₂.left_inv, e₁.left_inv] }, right_inv := λ f, funext $ λ x, by { dsimp, rw [e₂.right_inv, e₁.right_inv] } } @[simp] lemma arrow_congr_apply {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) (f : α₁ → β₁) (x : α₂) : arrow_congr e₁ e₂ f x = (e₂ $ f $ e₁.symm x) := rfl lemma arrow_congr_comp {α₁ β₁ γ₁ α₂ β₂ γ₂ : Sort*} (ea : α₁ ≃ α₂) (eb : β₁ ≃ β₂) (ec : γ₁ ≃ γ₂) (f : α₁ → β₁) (g : β₁ → γ₁) : arrow_congr ea ec (g ∘ f) = (arrow_congr eb ec g) ∘ (arrow_congr ea eb f) := by { ext, simp only [comp, arrow_congr_apply, eb.symm_apply_apply] } @[simp] lemma arrow_congr_refl {α β : Sort*} : arrow_congr (equiv.refl α) (equiv.refl β) = equiv.refl (α → β) := rfl @[simp] lemma arrow_congr_trans {α₁ β₁ α₂ β₂ α₃ β₃ : Sort*} (e₁ : α₁ ≃ α₂) (e₁' : β₁ ≃ β₂) (e₂ : α₂ ≃ α₃) (e₂' : β₂ ≃ β₃) : arrow_congr (e₁.trans e₂) (e₁'.trans e₂') = (arrow_congr e₁ e₁').trans (arrow_congr e₂ e₂') := rfl @[simp] lemma arrow_congr_symm {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : (arrow_congr e₁ e₂).symm = arrow_congr e₁.symm e₂.symm := rfl def conj (e : α ≃ β) : (α → α) ≃ (β → β) := arrow_congr e e @[simp] lemma conj_apply (e : α ≃ β) (f : α → α) (x : β) : e.conj f x = (e $ f $ e.symm x) := rfl @[simp] lemma conj_refl : conj (equiv.refl α) = equiv.refl (α → α) := rfl @[simp] lemma conj_symm (e : α ≃ β) : e.conj.symm = e.symm.conj := rfl @[simp] lemma conj_trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : (e₁.trans e₂).conj = e₁.conj.trans e₂.conj := rfl @[simp] lemma conj_comp (e : α ≃ β) (f₁ f₂ : α → α) : e.conj (f₁ ∘ f₂) = (e.conj f₁) ∘ (e.conj f₂) := by apply arrow_congr_comp def punit_equiv_punit : punit.{v} ≃ punit.{w} := ⟨λ _, punit.star, λ _, punit.star, λ u, by { cases u, refl }, λ u, by { cases u, reflexivity }⟩ section @[simp] def arrow_punit_equiv_punit (α : Sort*) : (α → punit.{v}) ≃ punit.{w} := ⟨λ f, punit.star, λ u f, punit.star, λ f, by { funext x, cases f x, refl }, λ u, by { cases u, reflexivity }⟩ @[simp] def punit_arrow_equiv (α : Sort*) : (punit.{u} → α) ≃ α := ⟨λ f, f punit.star, λ a u, a, λ f, by { funext x, cases x, refl }, λ u, rfl⟩ @[simp] def empty_arrow_equiv_punit (α : Sort*) : (empty → α) ≃ punit.{u} := ⟨λ f, punit.star, λ u e, e.rec _, λ f, funext $ λ x, x.rec _, λ u, by { cases u, refl }⟩ @[simp] def pempty_arrow_equiv_punit (α : Sort*) : (pempty → α) ≃ punit.{u} := ⟨λ f, punit.star, λ u e, e.rec _, λ f, funext $ λ x, x.rec _, λ u, by { cases u, refl }⟩ @[simp] def false_arrow_equiv_punit (α : Sort*) : (false → α) ≃ punit.{u} := calc (false → α) ≃ (empty → α) : arrow_congr false_equiv_empty (equiv.refl _) ... ≃ punit : empty_arrow_equiv_punit _ end @[congr] def prod_congr {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ :β₁ ≃ β₂) : α₁ × β₁ ≃ α₂ × β₂ := ⟨λp, (e₁ p.1, e₂ p.2), λp, (e₁.symm p.1, e₂.symm p.2), λ ⟨a, b⟩, show (e₁.symm (e₁ a), e₂.symm (e₂ b)) = (a, b), by rw [symm_apply_apply, symm_apply_apply], λ ⟨a, b⟩, show (e₁ (e₁.symm a), e₂ (e₂.symm b)) = (a, b), by rw [apply_symm_apply, apply_symm_apply]⟩ @[simp] theorem prod_congr_apply {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) (a : α₁) (b : β₁) : prod_congr e₁ e₂ (a, b) = (e₁ a, e₂ b) := rfl @[simp] def prod_comm (α β : Sort*) : α × β ≃ β × α := ⟨λ p, (p.2, p.1), λ p, (p.2, p.1), λ⟨a, b⟩, rfl, λ⟨a, b⟩, rfl⟩ @[simp] def prod_assoc (α β γ : Sort*) : (α × β) × γ ≃ α × (β × γ) := ⟨λ p, ⟨p.1.1, ⟨p.1.2, p.2⟩⟩, λp, ⟨⟨p.1, p.2.1⟩, p.2.2⟩, λ ⟨⟨a, b⟩, c⟩, rfl, λ ⟨a, ⟨b, c⟩⟩, rfl⟩ @[simp] theorem prod_assoc_apply {α β γ : Sort*} (p : (α × β) × γ) : prod_assoc α β γ p = ⟨p.1.1, ⟨p.1.2, p.2⟩⟩ := rfl section @[simp] def prod_punit (α : Sort*) : α × punit.{u+1} ≃ α := ⟨λ p, p.1, λ a, (a, punit.star), λ ⟨_, punit.star⟩, rfl, λ a, rfl⟩ @[simp] theorem prod_punit_apply {α : Sort*} (a : α × punit.{u+1}) : prod_punit α a = a.1 := rfl @[simp] def punit_prod (α : Sort*) : punit.{u+1} × α ≃ α := calc punit × α ≃ α × punit : prod_comm _ _ ... ≃ α : prod_punit _ @[simp] theorem punit_prod_apply {α : Sort*} (a : punit.{u+1} × α) : punit_prod α a = a.2 := rfl @[simp] def prod_empty (α : Sort*) : α × empty ≃ empty := equiv_empty (λ ⟨_, e⟩, e.rec _) @[simp] def empty_prod (α : Sort*) : empty × α ≃ empty := equiv_empty (λ ⟨e, _⟩, e.rec _) @[simp] def prod_pempty (α : Sort*) : α × pempty ≃ pempty := equiv_pempty (λ ⟨_, e⟩, e.rec _) @[simp] def pempty_prod (α : Sort*) : pempty × α ≃ pempty := equiv_pempty (λ ⟨e, _⟩, e.rec _) end section open sum def psum_equiv_sum (α β : Sort*) : psum α β ≃ α ⊕ β := ⟨λ s, psum.cases_on s inl inr, λ s, sum.cases_on s psum.inl psum.inr, λ s, by cases s; refl, λ s, by cases s; refl⟩ def sum_congr {α₁ β₁ α₂ β₂ : Sort*} : α₁ ≃ α₂ → β₁ ≃ β₂ → α₁ ⊕ β₁ ≃ α₂ ⊕ β₂ | ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ := ⟨λ s, match s with inl a₁ := inl (f₁ a₁) | inr b₁ := inr (f₂ b₁) end, λ s, match s with inl a₂ := inl (g₁ a₂) | inr b₂ := inr (g₂ b₂) end, λ s, match s with inl a := congr_arg inl (l₁ a) | inr a := congr_arg inr (l₂ a) end, λ s, match s with inl a := congr_arg inl (r₁ a) | inr a := congr_arg inr (r₂ a) end⟩ @[simp] theorem sum_congr_apply_inl {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) (a : α₁) : sum_congr e₁ e₂ (inl a) = inl (e₁ a) := by { cases e₁, cases e₂, refl } @[simp] theorem sum_congr_apply_inr {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) (b : β₁) : sum_congr e₁ e₂ (inr b) = inr (e₂ b) := by { cases e₁, cases e₂, refl } def bool_equiv_punit_sum_punit : bool ≃ punit.{u+1} ⊕ punit.{v+1} := ⟨λ b, cond b (inr punit.star) (inl punit.star), λ s, sum.rec_on s (λ_, ff) (λ_, tt), λ b, by cases b; refl, λ s, by rcases s with ⟨⟨⟩⟩ | ⟨⟨⟩⟩; refl⟩ noncomputable def Prop_equiv_bool : Prop ≃ bool := ⟨λ p, @to_bool p (classical.prop_decidable _), λ b, b, λ p, by simp, λ b, by simp⟩ @[simp] def sum_comm (α β : Sort*) : α ⊕ β ≃ β ⊕ α := ⟨λ s, match s with inl a := inr a | inr b := inl b end, λ s, match s with inl b := inr b | inr a := inl a end, λ s, by cases s; refl, λ s, by cases s; refl⟩ @[simp] def sum_assoc (α β γ : Sort*) : (α ⊕ β) ⊕ γ ≃ α ⊕ (β ⊕ γ) := ⟨λ s, match s with inl (inl a) := inl a | inl (inr b) := inr (inl b) | inr c := inr (inr c) end, λ s, match s with inl a := inl (inl a) | inr (inl b) := inl (inr b) | inr (inr c) := inr c end, λ s, by rcases s with ⟨_ | _⟩ | _; refl, λ s, by rcases s with _ | _ | _; refl⟩ @[simp] theorem sum_assoc_apply_in1 {α β γ} (a) : sum_assoc α β γ (inl (inl a)) = inl a := rfl @[simp] theorem sum_assoc_apply_in2 {α β γ} (b) : sum_assoc α β γ (inl (inr b)) = inr (inl b) := rfl @[simp] theorem sum_assoc_apply_in3 {α β γ} (c) : sum_assoc α β γ (inr c) = inr (inr c) := rfl @[simp] def sum_empty (α : Sort*) : α ⊕ empty ≃ α := ⟨λ s, match s with inl a := a | inr e := empty.rec _ e end, inl, λ s, by { rcases s with _ | ⟨⟨⟩⟩, refl }, λ a, rfl⟩ @[simp] def empty_sum (α : Sort*) : empty ⊕ α ≃ α := (sum_comm _ _).trans $ sum_empty _ @[simp] def sum_pempty (α : Sort*) : α ⊕ pempty ≃ α := ⟨λ s, match s with inl a := a | inr e := pempty.rec _ e end, inl, λ s, by { rcases s with _ | ⟨⟨⟩⟩, refl }, λ a, rfl⟩ @[simp] def pempty_sum (α : Sort*) : pempty ⊕ α ≃ α := (sum_comm _ _).trans $ sum_pempty _ @[simp] def option_equiv_sum_punit (α : Sort*) : option α ≃ α ⊕ punit.{u+1} := ⟨λ o, match o with none := inr punit.star | some a := inl a end, λ s, match s with inr _ := none | inl a := some a end, λ o, by cases o; refl, λ s, by rcases s with _ | ⟨⟨⟩⟩; refl⟩ def sum_equiv_sigma_bool (α β : Sort*) : α ⊕ β ≃ (Σ b: bool, cond b α β) := ⟨λ s, match s with inl a := ⟨tt, a⟩ | inr b := ⟨ff, b⟩ end, λ s, match s with ⟨tt, a⟩ := inl a | ⟨ff, b⟩ := inr b end, λ s, by cases s; refl, λ s, by rcases s with ⟨_|_, _⟩; refl⟩ def equiv_fib {α β : Type*} (f : α → β) : α ≃ Σ y : β, {x // f x = y} := ⟨λ x, ⟨f x, x, rfl⟩, λ x, x.2.1, λ x, rfl, λ ⟨y, x, rfl⟩, rfl⟩ end section def Pi_congr_right {α} {β₁ β₂ : α → Sort*} (F : ∀ a, β₁ a ≃ β₂ a) : (Π a, β₁ a) ≃ (Π a, β₂ a) := ⟨λ H a, F a (H a), λ H a, (F a).symm (H a), λ H, funext $ by simp, λ H, funext $ by simp⟩ def Pi_curry {α} {β : α → Sort*} (γ : Π a, β a → Sort*) : (Π x : sigma β, γ x.1 x.2) ≃ (Π a b, γ a b) := { to_fun := λ f x y, f ⟨x,y⟩, inv_fun := λ f x, f x.1 x.2, left_inv := λ f, funext $ λ ⟨x,y⟩, rfl, right_inv := λ f, funext $ λ x, funext $ λ y, rfl } end section def psigma_equiv_sigma {α} (β : α → Sort*) : psigma β ≃ sigma β := ⟨λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, rfl, λ ⟨a, b⟩, rfl⟩ def sigma_congr_right {α} {β₁ β₂ : α → Sort*} (F : ∀ a, β₁ a ≃ β₂ a) : sigma β₁ ≃ sigma β₂ := ⟨λ ⟨a, b⟩, ⟨a, F a b⟩, λ ⟨a, b⟩, ⟨a, (F a).symm b⟩, λ ⟨a, b⟩, congr_arg (sigma.mk a) $ symm_apply_apply (F a) b, λ ⟨a, b⟩, congr_arg (sigma.mk a) $ apply_symm_apply (F a) b⟩ def sigma_congr_left {α₁ α₂} {β : α₂ → Sort*} : ∀ f : α₁ ≃ α₂, (Σ a:α₁, β (f a)) ≃ (Σ a:α₂, β a) | ⟨f, g, l, r⟩ := ⟨λ ⟨a, b⟩, ⟨f a, b⟩, λ ⟨a, b⟩, ⟨g a, @@eq.rec β b (r a).symm⟩, λ ⟨a, b⟩, match g (f a), l a : ∀ a' (h : a' = a), @sigma.mk _ (β ∘ f) _ (@@eq.rec β b (congr_arg f h.symm)) = ⟨a, b⟩ with | _, rfl := rfl end, λ ⟨a, b⟩, match f (g a), _ : ∀ a' (h : a' = a), sigma.mk a' (@@eq.rec β b h.symm) = ⟨a, b⟩ with | _, rfl := rfl end⟩ def sigma_equiv_prod (α β : Sort*) : (Σ_:α, β) ≃ α × β := ⟨λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, rfl, λ ⟨a, b⟩, rfl⟩ def sigma_equiv_prod_of_equiv {α β} {β₁ : α → Sort*} (F : ∀ a, β₁ a ≃ β) : sigma β₁ ≃ α × β := (sigma_congr_right F).trans (sigma_equiv_prod α β) end section def arrow_prod_equiv_prod_arrow (α β γ : Type*) : (γ → α × β) ≃ (γ → α) × (γ → β) := ⟨λ f, (λ c, (f c).1, λ c, (f c).2), λ p c, (p.1 c, p.2 c), λ f, funext $ λ c, prod.mk.eta, λ p, by { cases p, refl }⟩ def arrow_arrow_equiv_prod_arrow (α β γ : Sort*) : (α → β → γ) ≃ (α × β → γ) := ⟨λ f, λ p, f p.1 p.2, λ f, λ a b, f (a, b), λ f, rfl, λ f, by { funext p, cases p, refl }⟩ open sum def sum_arrow_equiv_prod_arrow (α β γ : Type*) : ((α ⊕ β) → γ) ≃ (α → γ) × (β → γ) := ⟨λ f, (f ∘ inl, f ∘ inr), λ p s, sum.rec_on s p.1 p.2, λ f, by { funext s, cases s; refl }, λ p, by { cases p, refl }⟩ def sum_prod_distrib (α β γ : Sort*) : (α ⊕ β) × γ ≃ (α × γ) ⊕ (β × γ) := ⟨λ p, match p with (inl a, c) := inl (a, c) | (inr b, c) := inr (b, c) end, λ s, match s with inl (a, c) := (inl a, c) | inr (b, c) := (inr b, c) end, λ p, by rcases p with ⟨_ | _, _⟩; refl, λ s, by rcases s with ⟨_, _⟩ | ⟨_, _⟩; refl⟩ @[simp] theorem sum_prod_distrib_apply_left {α β γ} (a : α) (c : γ) : sum_prod_distrib α β γ (sum.inl a, c) = sum.inl (a, c) := rfl @[simp] theorem sum_prod_distrib_apply_right {α β γ} (b : β) (c : γ) : sum_prod_distrib α β γ (sum.inr b, c) = sum.inr (b, c) := rfl def prod_sum_distrib (α β γ : Sort*) : α × (β ⊕ γ) ≃ (α × β) ⊕ (α × γ) := calc α × (β ⊕ γ) ≃ (β ⊕ γ) × α : prod_comm _ _ ... ≃ (β × α) ⊕ (γ × α) : sum_prod_distrib _ _ _ ... ≃ (α × β) ⊕ (α × γ) : sum_congr (prod_comm _ _) (prod_comm _ _) @[simp] theorem prod_sum_distrib_apply_left {α β γ} (a : α) (b : β) : prod_sum_distrib α β γ (a, sum.inl b) = sum.inl (a, b) := rfl @[simp] theorem prod_sum_distrib_apply_right {α β γ} (a : α) (c : γ) : prod_sum_distrib α β γ (a, sum.inr c) = sum.inr (a, c) := rfl def bool_prod_equiv_sum (α : Type u) : bool × α ≃ α ⊕ α := calc bool × α ≃ (unit ⊕ unit) × α : prod_congr bool_equiv_punit_sum_punit (equiv.refl _) ... ≃ α × (unit ⊕ unit) : prod_comm _ _ ... ≃ (α × unit) ⊕ (α × unit) : prod_sum_distrib _ _ _ ... ≃ α ⊕ α : sum_congr (prod_punit _) (prod_punit _) end section open sum nat def nat_equiv_nat_sum_punit : ℕ ≃ ℕ ⊕ punit.{u+1} := ⟨λ n, match n with zero := inr punit.star | succ a := inl a end, λ s, match s with inl n := succ n | inr punit.star := zero end, λ n, begin cases n, repeat { refl } end, λ s, begin cases s with a u, { refl }, {cases u, { refl }} end⟩ @[simp] def nat_sum_punit_equiv_nat : ℕ ⊕ punit.{u+1} ≃ ℕ := nat_equiv_nat_sum_punit.symm def int_equiv_nat_sum_nat : ℤ ≃ ℕ ⊕ ℕ := by refine ⟨_, _, _, _⟩; intro z; {cases z; [left, right]; assumption} <|> {cases z; refl} end def list_equiv_of_equiv {α β : Type*} : α ≃ β → list α ≃ list β | ⟨f, g, l, r⟩ := by refine ⟨list.map f, list.map g, λ x, _, λ x, _⟩; simp [id_of_left_inverse l, id_of_right_inverse r] def fin_equiv_subtype (n : ℕ) : fin n ≃ {m // m < n} := ⟨λ x, ⟨x.1, x.2⟩, λ x, ⟨x.1, x.2⟩, λ ⟨a, b⟩, rfl,λ ⟨a, b⟩, rfl⟩ def decidable_eq_of_equiv [decidable_eq β] (e : α ≃ β) : decidable_eq α | a₁ a₂ := decidable_of_iff (e a₁ = e a₂) e.injective.eq_iff def inhabited_of_equiv [inhabited β] (e : α ≃ β) : inhabited α := ⟨e.symm (default _)⟩ def unique_of_equiv (e : α ≃ β) (h : unique β) : unique α := unique.of_surjective e.symm.surjective def unique_congr (e : α ≃ β) : unique α ≃ unique β := { to_fun := e.symm.unique_of_equiv, inv_fun := e.unique_of_equiv, left_inv := λ _, subsingleton.elim _ _, right_inv := λ _, subsingleton.elim _ _ } section open subtype def subtype_congr {p : α → Prop} {q : β → Prop} (e : α ≃ β) (h : ∀ a, p a ↔ q (e a)) : {a : α // p a} ≃ {b : β // q b} := ⟨λ x, ⟨e x.1, (h _).1 x.2⟩, λ y, ⟨e.symm y.1, (h _).2 (by { simp, exact y.2 })⟩, λ ⟨x, h⟩, subtype.eq' $ by simp, λ ⟨y, h⟩, subtype.eq' $ by simp⟩ def subtype_congr_right {p q : α → Prop} (e : ∀x, p x ↔ q x) : subtype p ≃ subtype q := subtype_congr (equiv.refl _) e @[simp] lemma subtype_congr_right_mk {p q : α → Prop} (e : ∀x, p x ↔ q x) {x : α} (h : p x) : subtype_congr_right e ⟨x, h⟩ = ⟨x, (e x).1 h⟩ := rfl def subtype_equiv_of_subtype' {p : α → Prop} (e : α ≃ β) : {a : α // p a} ≃ {b : β // p (e.symm b)} := subtype_congr e $ by simp def subtype_congr_prop {α : Type*} {p q : α → Prop} (h : p = q) : subtype p ≃ subtype q := subtype_congr (equiv.refl α) (assume a, h ▸ iff.refl _) def set_congr {α : Type*} {s t : set α} (h : s = t) : s ≃ t := subtype_congr_prop h def subtype_subtype_equiv_subtype {α : Type u} (p : α → Prop) (q : subtype p → Prop) : subtype q ≃ {a : α // ∃h:p a, q ⟨a, h⟩ } := ⟨λ⟨⟨a, ha⟩, ha'⟩, ⟨a, ha, ha'⟩, λ⟨a, ha⟩, ⟨⟨a, ha.cases_on $ assume h _, h⟩, by { cases ha, exact ha_h }⟩, assume ⟨⟨a, ha⟩, h⟩, rfl, assume ⟨a, h₁, h₂⟩, rfl⟩ /- A subtype of a sigma-type is a sigma-type over a subtype. -/ def subtype_sigma_equiv {α : Type u} (p : α → Type v) (q : α → Prop) : { y : sigma p // q y.1 } ≃ Σ(x : subtype q), p x.1 := begin fsplit, rintro ⟨⟨x, y⟩, z⟩, exact ⟨⟨x, z⟩, y⟩, rintro ⟨⟨x, y⟩, z⟩, exact ⟨⟨x, z⟩, y⟩, rintro ⟨⟨x, y⟩, z⟩, refl, rintro ⟨⟨x, y⟩, z⟩, refl, end /-- aka coimage -/ def equiv_sigma_subtype {α : Type u} {β : Type v} (f : α → β) : α ≃ Σ b, {x : α // f x = b} := ⟨λ x, ⟨f x, x, rfl⟩, λ x, x.2.1, λ x, rfl, λ ⟨b, x, H⟩, sigma.eq H $ eq.drec_on H $ subtype.eq rfl⟩ def pi_equiv_subtype_sigma (ι : Type*) (π : ι → Type*) : (Πi, π i) ≃ {f : ι → Σi, π i | ∀i, (f i).1 = i } := ⟨ λf, ⟨λi, ⟨i, f i⟩, assume i, rfl⟩, λf i, begin rw ← f.2 i, exact (f.1 i).2 end, assume f, funext $ assume i, rfl, assume ⟨f, hf⟩, subtype.eq $ funext $ assume i, sigma.eq (hf i).symm $ eq_of_heq $ rec_heq_of_heq _ $ rec_heq_of_heq _ $ heq.refl _⟩ def subtype_pi_equiv_pi {α : Sort u} {β : α → Sort v} {p : Πa, β a → Prop} : {f : Πa, β a // ∀a, p a (f a) } ≃ Πa, { b : β a // p a b } := ⟨λf a, ⟨f.1 a, f.2 a⟩, λf, ⟨λa, (f a).1, λa, (f a).2⟩, by { rintro ⟨f, h⟩, refl }, by { rintro f, funext a, exact subtype.eq' rfl }⟩ end section local attribute [elab_with_expected_type] quot.lift def quot_equiv_of_quot' {r : α → α → Prop} {s : β → β → Prop} (e : α ≃ β) (h : ∀ a a', r a a' ↔ s (e a) (e a')) : quot r ≃ quot s := ⟨quot.lift (λ a, quot.mk _ (e a)) (λ a a' H, quot.sound ((h a a').mp H)), quot.lift (λ b, quot.mk _ (e.symm b)) (λ b b' H, quot.sound ((h _ _).mpr (by convert H; simp))), quot.ind $ by simp, quot.ind $ by simp⟩ def quot_equiv_of_quot {r : α → α → Prop} (e : α ≃ β) : quot r ≃ quot (λ b b', r (e.symm b) (e.symm b')) := quot_equiv_of_quot' e (by simp) end namespace set open set protected def univ (α) : @univ α ≃ α := ⟨subtype.val, λ a, ⟨a, trivial⟩, λ ⟨a, _⟩, rfl, λ a, rfl⟩ @[simp] lemma univ_apply {α : Type u} (x : @univ α) : equiv.set.univ α x = x := rfl @[simp] lemma univ_symm_apply {α : Type u} (x : α) : (equiv.set.univ α).symm x = ⟨x, trivial⟩ := rfl protected def empty (α) : (∅ : set α) ≃ empty := equiv_empty $ λ ⟨x, h⟩, not_mem_empty x h protected def pempty (α) : (∅ : set α) ≃ pempty := equiv_pempty $ λ ⟨x, h⟩, not_mem_empty x h protected def union' {α} {s t : set α} (p : α → Prop) [decidable_pred p] (hs : ∀ x ∈ s, p x) (ht : ∀ x ∈ t, ¬ p x) : (s ∪ t : set α) ≃ s ⊕ t := { to_fun := λ x, if hp : p x.1 then sum.inl ⟨_, x.2.resolve_right (λ xt, ht _ xt hp)⟩ else sum.inr ⟨_, x.2.resolve_left (λ xs, hp (hs _ xs))⟩, inv_fun := λ o, match o with | (sum.inl x) := ⟨x.1, or.inl x.2⟩ | (sum.inr x) := ⟨x.1, or.inr x.2⟩ end, left_inv := λ ⟨x, h'⟩, by by_cases p x; simp [union'._match_1, h]; congr, right_inv := λ o, begin rcases o with ⟨x, h⟩ | ⟨x, h⟩; dsimp [union'._match_1]; [simp [hs _ h], simp [ht _ h]] end } protected def union {α} {s t : set α} [decidable_pred s] (H : s ∩ t = ∅) : (s ∪ t : set α) ≃ s ⊕ t := set.union' s (λ _, id) (λ x xt xs, subset_empty_iff.2 H ⟨xs, xt⟩) lemma union_apply_left {α} {s t : set α} [decidable_pred s] (H : s ∩ t = ∅) {a : (s ∪ t : set α)} (ha : ↑a ∈ s) : equiv.set.union H a = sum.inl ⟨a, ha⟩ := dif_pos ha lemma union_apply_right {α} {s t : set α} [decidable_pred s] (H : s ∩ t = ∅) {a : (s ∪ t : set α)} (ha : ↑a ∈ t) : equiv.set.union H a = sum.inr ⟨a, ha⟩ := dif_neg (show ↑a ∉ s, by finish [set.ext_iff]) protected def singleton {α} (a : α) : ({a} : set α) ≃ punit.{u} := ⟨λ _, punit.star, λ _, ⟨a, mem_singleton _⟩, λ ⟨x, h⟩, by { simp at h, subst x }, λ ⟨⟩, rfl⟩ protected def of_eq {α : Type u} {s t : set α} (h : s = t) : s ≃ t := { to_fun := λ x, ⟨x.1, h ▸ x.2⟩, inv_fun := λ x, ⟨x.1, h.symm ▸ x.2⟩, left_inv := λ _, subtype.eq rfl, right_inv := λ _, subtype.eq rfl } @[simp] lemma of_eq_apply {α : Type u} {s t : set α} (h : s = t) (a : s) : equiv.set.of_eq h a = ⟨a, h ▸ a.2⟩ := rfl @[simp] lemma of_eq_symm_apply {α : Type u} {s t : set α} (h : s = t) (a : t) : (equiv.set.of_eq h).symm a = ⟨a, h.symm ▸ a.2⟩ := rfl protected def insert {α} {s : set.{u} α} [decidable_pred s] {a : α} (H : a ∉ s) : (insert a s : set α) ≃ s ⊕ punit.{u+1} := calc (insert a s : set α) ≃ ↥(s ∪ {a}) : equiv.set.of_eq (by simp) ... ≃ s ⊕ ({a} : set α) : equiv.set.union (by finish [set.ext_iff]) ... ≃ s ⊕ punit.{u+1} : sum_congr (equiv.refl _) (equiv.set.singleton _) protected def sum_compl {α} (s : set α) [decidable_pred s] : s ⊕ (-s : set α) ≃ α := calc s ⊕ (-s : set α) ≃ ↥(s ∪ -s) : (equiv.set.union (by simp [set.ext_iff])).symm ... ≃ @univ α : equiv.set.of_eq (by simp) ... ≃ α : equiv.set.univ _ @[simp] lemma sum_compl_apply_inl {α : Type u} (s : set α) [decidable_pred s] (x : s) : equiv.set.sum_compl s (sum.inl x) = x := rfl @[simp] lemma sum_compl_apply_inr {α : Type u} (s : set α) [decidable_pred s] (x : -s) : equiv.set.sum_compl s (sum.inr x) = x := rfl lemma sum_compl_symm_apply_of_mem {α : Type u} {s : set α} [decidable_pred s] {x : α} (hx : x ∈ s) : (equiv.set.sum_compl s).symm x = sum.inl ⟨x, hx⟩ := have ↑(⟨x, or.inl hx⟩ : (s ∪ -s : set α)) ∈ s, from hx, by { rw [equiv.set.sum_compl], simpa using set.union_apply_left _ this } lemma sum_compl_symm_apply_of_not_mem {α : Type u} {s : set α} [decidable_pred s] {x : α} (hx : x ∉ s) : (equiv.set.sum_compl s).symm x = sum.inr ⟨x, hx⟩ := have ↑(⟨x, or.inr hx⟩ : (s ∪ -s : set α)) ∈ -s, from hx, by { rw [equiv.set.sum_compl], simpa using set.union_apply_right _ this } protected def union_sum_inter {α : Type u} (s t : set α) [decidable_pred s] : (s ∪ t : set α) ⊕ (s ∩ t : set α) ≃ s ⊕ t := calc (s ∪ t : set α) ⊕ (s ∩ t : set α) ≃ (s ∪ t \ s : set α) ⊕ (s ∩ t : set α) : by rw [union_diff_self] ... ≃ (s ⊕ (t \ s : set α)) ⊕ (s ∩ t : set α) : sum_congr (set.union (inter_diff_self _ _)) (equiv.refl _) ... ≃ s ⊕ (t \ s : set α) ⊕ (s ∩ t : set α) : sum_assoc _ _ _ ... ≃ s ⊕ (t \ s ∪ s ∩ t : set α) : sum_congr (equiv.refl _) begin refine (set.union' (∉ s) _ _).symm, exacts [λ x hx, hx.2, λ x hx, not_not_intro hx.1] end ... ≃ s ⊕ t : by { rw (_ : t \ s ∪ s ∩ t = t), rw [union_comm, inter_comm, inter_union_diff] } protected def prod {α β} (s : set α) (t : set β) : s.prod t ≃ s × t := ⟨λp, ⟨⟨p.1.1, p.2.1⟩, ⟨p.1.2, p.2.2⟩⟩, λp, ⟨⟨p.1.1, p.2.1⟩, ⟨p.1.2, p.2.2⟩⟩, λ ⟨⟨x, y⟩, ⟨h₁, h₂⟩⟩, rfl, λ ⟨⟨x, h₁⟩, ⟨y, h₂⟩⟩, rfl⟩ protected noncomputable def image_of_inj_on {α β} (f : α → β) (s : set α) (H : inj_on f s) : s ≃ (f '' s) := ⟨λ ⟨x, h⟩, ⟨f x, mem_image_of_mem f h⟩, λ ⟨y, h⟩, ⟨classical.some h, (classical.some_spec h).1⟩, λ ⟨x, h⟩, subtype.eq (H (classical.some_spec (mem_image_of_mem f h)).1 h (classical.some_spec (mem_image_of_mem f h)).2), λ ⟨y, h⟩, subtype.eq (classical.some_spec h).2⟩ protected noncomputable def image {α β} (f : α → β) (s : set α) (H : injective f) : s ≃ (f '' s) := equiv.set.image_of_inj_on f s (λ x y hx hy hxy, H hxy) @[simp] theorem image_apply {α β} (f : α → β) (s : set α) (H : injective f) (a h) : set.image f s H ⟨a, h⟩ = ⟨f a, mem_image_of_mem _ h⟩ := rfl protected noncomputable def range {α β} (f : α → β) (H : injective f) : α ≃ range f := { to_fun := λ x, ⟨f x, mem_range_self _⟩, inv_fun := λ x, classical.some x.2, left_inv := λ x, H (classical.some_spec (show f x ∈ range f, from mem_range_self _)), right_inv := λ x, subtype.eq $ classical.some_spec x.2 } @[simp] theorem range_apply {α β} (f : α → β) (H : injective f) (a) : set.range f H a = ⟨f a, set.mem_range_self _⟩ := rfl protected def congr {α β : Type*} (e : α ≃ β) : set α ≃ set β := ⟨λ s, e '' s, λ t, e.symm '' t, symm_image_image e, symm_image_image e.symm⟩ protected def sep {α : Type u} (s : set α) (t : α → Prop) : ({ x ∈ s | t x } : set α) ≃ { x : s | t x.1 } := begin symmetry, apply (equiv.subtype_subtype_equiv_subtype _ _).trans _, simp only [mem_set_of_eq, exists_prop], refl end end set noncomputable def of_bijective {α β} {f : α → β} (hf : bijective f) : α ≃ β := ⟨f, λ x, classical.some (hf.2 x), λ x, hf.1 (classical.some_spec (hf.2 (f x))), λ x, classical.some_spec (hf.2 x)⟩ @[simp] theorem of_bijective_to_fun {α β} {f : α → β} (hf : bijective f) : (of_bijective hf : α → β) = f := rfl lemma subtype_quotient_equiv_quotient_subtype (p₁ : α → Prop) [s₁ : setoid α] [s₂ : setoid (subtype p₁)] (p₂ : quotient s₁ → Prop) (hp₂ : ∀ a, p₁ a ↔ p₂ ⟦a⟧) (h : ∀ x y : subtype p₁, @setoid.r _ s₂ x y ↔ (x : α) ≈ y) : {x // p₂ x} ≃ quotient s₂ := { to_fun := λ a, quotient.hrec_on a.1 (λ a h, ⟦⟨a, (hp₂ _).2 h⟩⟧) (λ a b hab, hfunext (by rw quotient.sound hab) (λ h₁ h₂ _, heq_of_eq (quotient.sound ((h _ _).2 hab)))) a.2, inv_fun := λ a, quotient.lift_on a (λ a, (⟨⟦a.1⟧, (hp₂ _).1 a.2⟩ : {x // p₂ x})) (λ a b hab, subtype.eq' (quotient.sound ((h _ _).1 hab))), left_inv := λ ⟨a, ha⟩, quotient.induction_on a (λ a ha, rfl) ha, right_inv := λ a, quotient.induction_on a (λ ⟨a, ha⟩, rfl) } section swap variable [decidable_eq α] open decidable def swap_core (a b r : α) : α := if r = a then b else if r = b then a else r theorem swap_core_self (r a : α) : swap_core a a r = r := by { unfold swap_core, split_ifs; cc } theorem swap_core_swap_core (r a b : α) : swap_core a b (swap_core a b r) = r := by { unfold swap_core, split_ifs; cc } theorem swap_core_comm (r a b : α) : swap_core a b r = swap_core b a r := by { unfold swap_core, split_ifs; cc } /-- `swap a b` is the permutation that swaps `a` and `b` and leaves other values as is. -/ def swap (a b : α) : perm α := ⟨swap_core a b, swap_core a b, λr, swap_core_swap_core r a b, λr, swap_core_swap_core r a b⟩ theorem swap_self (a : α) : swap a a = equiv.refl _ := eq_of_to_fun_eq $ funext $ λ r, swap_core_self r a theorem swap_comm (a b : α) : swap a b = swap b a := eq_of_to_fun_eq $ funext $ λ r, swap_core_comm r _ _ theorem swap_apply_def (a b x : α) : swap a b x = if x = a then b else if x = b then a else x := rfl @[simp] theorem swap_apply_left (a b : α) : swap a b a = b := if_pos rfl @[simp] theorem swap_apply_right (a b : α) : swap a b b = a := by { by_cases b = a; simp [swap_apply_def, *] } theorem swap_apply_of_ne_of_ne {a b x : α} : x ≠ a → x ≠ b → swap a b x = x := by simp [swap_apply_def] {contextual := tt} @[simp] theorem swap_swap (a b : α) : (swap a b).trans (swap a b) = equiv.refl _ := eq_of_to_fun_eq $ funext $ λ x, swap_core_swap_core _ _ _ theorem swap_comp_apply {a b x : α} (π : perm α) : π.trans (swap a b) x = if π x = a then b else if π x = b then a else π x := by { cases π, refl } @[simp] lemma swap_inv {α : Type*} [decidable_eq α] (x y : α) : (swap x y)⁻¹ = swap x y := rfl @[simp] lemma symm_trans_swap_trans [decidable_eq α] [decidable_eq β] (a b : α) (e : α ≃ β) : (e.symm.trans (swap a b)).trans e = swap (e a) (e b) := equiv.ext _ _ (λ x, begin have : ∀ a, e.symm x = a ↔ x = e a := λ a, by { rw @eq_comm _ (e.symm x), split; intros; simp * at * }, simp [swap_apply_def, this], split_ifs; simp end) @[simp] lemma swap_mul_self {α : Type*} [decidable_eq α] (i j : α) : swap i j * swap i j = 1 := equiv.swap_swap i j @[simp] lemma swap_apply_self {α : Type*} [decidable_eq α] (i j a : α) : swap i j (swap i j a) = a := by rw [← perm.mul_apply, swap_mul_self, perm.one_apply] /-- Augment an equivalence with a prescribed mapping `f a = b` -/ def set_value (f : α ≃ β) (a : α) (b : β) : α ≃ β := (swap a (f.symm b)).trans f @[simp] theorem set_value_eq (f : α ≃ β) (a : α) (b : β) : set_value f a b a = b := by { dsimp [set_value], simp [swap_apply_left] } end swap end equiv instance {α} [subsingleton α] : subsingleton (ulift α) := equiv.ulift.subsingleton instance {α} [subsingleton α] : subsingleton (plift α) := equiv.plift.subsingleton instance {α} [decidable_eq α] : decidable_eq (ulift α) := equiv.ulift.decidable_eq instance {α} [decidable_eq α] : decidable_eq (plift α) := equiv.plift.decidable_eq def unique_unique_equiv : unique (unique α) ≃ unique α := { to_fun := λ h, h.default, inv_fun := λ h, { default := h, uniq := λ _, subsingleton.elim _ _ }, left_inv := λ _, subsingleton.elim _ _, right_inv := λ _, subsingleton.elim _ _ } def equiv_of_unique_of_unique [unique α] [unique β] : α ≃ β := { to_fun := λ _, default β, inv_fun := λ _, default α, left_inv := λ _, subsingleton.elim _ _, right_inv := λ _, subsingleton.elim _ _ } def equiv_punit_of_unique [unique α] : α ≃ punit.{v} := equiv_of_unique_of_unique namespace quot protected def congr {α β} {ra : α → α → Prop} {rb : β → β → Prop} (e : α ≃ β) (eq : ∀a₁ a₂, ra a₁ a₂ ↔ rb (e a₁) (e a₂)) : quot ra ≃ quot rb := { to_fun := quot.map e (assume a₁ a₂, (eq a₁ a₂).1), inv_fun := quot.map e.symm (assume b₁ b₂ h, (eq (e.symm b₁) (e.symm b₂)).2 ((e.apply_symm_apply b₁).symm ▸ (e.apply_symm_apply b₂).symm ▸ h)), left_inv := by { rintros ⟨a⟩, dunfold quot.map, simp only [equiv.symm_apply_apply] }, right_inv := by { rintros ⟨a⟩, dunfold quot.map, simp only [equiv.apply_symm_apply] } } /-- Quotients are congruent on equivalences under equality of their relation. An alternative is just to use rewriting with `eq`, but then computational proofs get stuck. -/ protected def congr_right {α} {r r' : α → α → Prop} (eq : ∀a₁ a₂, r a₁ a₂ ↔ r' a₁ a₂) : quot r ≃ quot r' := quot.congr (equiv.refl α) eq end quot namespace quotient protected def congr {α β} {ra : setoid α} {rb : setoid β} (e : α ≃ β) (eq : ∀a₁ a₂, @setoid.r α ra a₁ a₂ ↔ @setoid.r β rb (e a₁) (e a₂)) : quotient ra ≃ quotient rb := quot.congr e eq protected def congr_right {α} {r r' : setoid α} (eq : ∀a₁ a₂, @setoid.r α r a₁ a₂ ↔ @setoid.r α r' a₁ a₂) : quotient r ≃ quotient r' := quot.congr_right eq end quotient
7c58d1023919bab3abffc2c2331cdf12a090d585
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/stage0/src/Lean/Meta/Basic.lean
3243c517c1948be5a26f7e85aa5bc335be74444c
[ "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
43,810
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.Data.LOption import Lean.Environment import Lean.Class import Lean.ReducibilityAttrs import Lean.Util.Trace import Lean.Util.RecDepth import Lean.Util.PPExt import Lean.Compiler.InlineAttrs import Lean.Meta.TransparencyMode import Lean.Meta.DiscrTreeTypes import Lean.Eval import Lean.CoreM /- This module provides four (mutually dependent) goodies that are needed for building the elaborator and tactic frameworks. 1- Weak head normal form computation with support for metavariables and transparency modes. 2- Definitionally equality checking with support for metavariables (aka unification modulo definitional equality). 3- Type inference. 4- Type class resolution. They are packed into the MetaM monad. -/ namespace Lean.Meta builtin_initialize isDefEqStuckExceptionId : InternalExceptionId ← registerInternalExceptionId `isDefEqStuck structure Config where foApprox : Bool := false ctxApprox : Bool := false quasiPatternApprox : Bool := false /- When `constApprox` is set to true, we solve `?m t =?= c` using `?m := fun _ => c` when `?m t` is not a higher-order pattern and `c` is not an application as -/ constApprox : Bool := false /- When the following flag is set, `isDefEq` throws the exeption `Exeption.isDefEqStuck` whenever it encounters a constraint `?m ... =?= t` where `?m` is read only. This feature is useful for type class resolution where we may want to notify the caller that the TC problem may be solveable later after it assigns `?m`. -/ isDefEqStuckEx : Bool := false transparency : TransparencyMode := TransparencyMode.default /- If zetaNonDep == false, then non dependent let-decls are not zeta expanded. -/ zetaNonDep : Bool := true /- When `trackZeta == true`, we store zetaFVarIds all free variables that have been zeta-expanded. -/ trackZeta : Bool := false unificationHints : Bool := true structure ParamInfo where implicit : Bool := false instImplicit : Bool := false hasFwdDeps : Bool := false backDeps : Array Nat := #[] deriving Inhabited def ParamInfo.isExplicit (p : ParamInfo) : Bool := !p.implicit && !p.instImplicit structure FunInfo where paramInfo : Array ParamInfo := #[] resultDeps : Array Nat := #[] structure InfoCacheKey where transparency : TransparencyMode expr : Expr nargs? : Option Nat deriving Inhabited, BEq namespace InfoCacheKey instance : Hashable InfoCacheKey := ⟨fun ⟨transparency, expr, nargs⟩ => mixHash (hash transparency) $ mixHash (hash expr) (hash nargs)⟩ end InfoCacheKey open Std (PersistentArray PersistentHashMap) abbrev SynthInstanceCache := PersistentHashMap Expr (Option Expr) structure Cache where inferType : PersistentExprStructMap Expr := {} funInfo : PersistentHashMap InfoCacheKey FunInfo := {} synthInstance : SynthInstanceCache := {} whnfDefault : PersistentExprStructMap Expr := {} -- cache for closed terms and `TransparencyMode.default` whnfAll : PersistentExprStructMap Expr := {} -- cache for closed terms and `TransparencyMode.all` deriving Inhabited structure PostponedEntry where lhs : Level rhs : Level structure State where mctx : MetavarContext := {} cache : Cache := {} /- When `trackZeta == true`, then any let-decl free variable that is zeta expansion performed by `MetaM` is stored in `zetaFVarIds`. -/ zetaFVarIds : NameSet := {} postponed : PersistentArray PostponedEntry := {} deriving Inhabited structure Context where config : Config := {} lctx : LocalContext := {} localInstances : LocalInstances := #[] abbrev MetaM := ReaderT Context $ StateRefT State CoreM instance : Inhabited (MetaM α) where default := fun _ _ => arbitrary instance : MonadLCtx MetaM where getLCtx := return (← read).lctx instance : MonadMCtx MetaM where getMCtx := return (← get).mctx modifyMCtx f := modify fun s => { s with mctx := f s.mctx } instance : AddMessageContext MetaM where addMessageContext := addMessageContextFull @[inline] def MetaM.run (x : MetaM α) (ctx : Context := {}) (s : State := {}) : CoreM (α × State) := x ctx |>.run s @[inline] def MetaM.run' (x : MetaM α) (ctx : Context := {}) (s : State := {}) : CoreM α := Prod.fst <$> x.run ctx s @[inline] def MetaM.toIO (x : MetaM α) (ctxCore : Core.Context) (sCore : Core.State) (ctx : Context := {}) (s : State := {}) : IO (α × Core.State × State) := do let ((a, s), sCore) ← (x.run ctx s).toIO ctxCore sCore pure (a, sCore, s) instance [MetaEval α] : MetaEval (MetaM α) := ⟨fun env opts x _ => MetaEval.eval env opts x.run' true⟩ protected def throwIsDefEqStuck {α} : MetaM α := throw $ Exception.internal isDefEqStuckExceptionId builtin_initialize registerTraceClass `Meta registerTraceClass `Meta.debug @[inline] def liftMetaM [MonadLiftT MetaM m] (x : MetaM α) : m α := liftM x @[inline] def mapMetaM [MonadControlT MetaM m] [Monad m] (f : forall {α}, MetaM α → MetaM α) {α} (x : m α) : m α := controlAt MetaM fun runInBase => f $ runInBase x @[inline] def map1MetaM [MonadControlT MetaM m] [Monad m] (f : forall {α}, (β → MetaM α) → MetaM α) {α} (k : β → m α) : m α := controlAt MetaM fun runInBase => f fun b => runInBase $ k b @[inline] def map2MetaM [MonadControlT MetaM m] [Monad m] (f : forall {α}, (β → γ → MetaM α) → MetaM α) {α} (k : β → γ → m α) : m α := controlAt MetaM fun runInBase => f fun b c => runInBase $ k b c section Methods variables {n : Type → Type} [MonadControlT MetaM n] [Monad n] def getLocalInstances : MetaM LocalInstances := return (← read).localInstances def getConfig : MetaM Config := return (← read).config def setMCtx (mctx : MetavarContext) : MetaM Unit := modify fun s => { s with mctx := mctx } def resetZetaFVarIds : MetaM Unit := modify fun s => { s with zetaFVarIds := {} } def getZetaFVarIds : MetaM NameSet := return (← get).zetaFVarIds def getPostponed : MetaM (PersistentArray PostponedEntry) := return (← get).postponed def setPostponed (postponed : PersistentArray PostponedEntry) : MetaM Unit := modify fun s => { s with postponed := postponed } @[inline] def modifyPostponed (f : PersistentArray PostponedEntry → PersistentArray PostponedEntry) : MetaM Unit := modify fun s => { s with postponed := f s.postponed } builtin_initialize whnfRef : IO.Ref (Expr → MetaM Expr) ← IO.mkRef fun _ => throwError "whnf implementation was not set" builtin_initialize inferTypeRef : IO.Ref (Expr → MetaM Expr) ← IO.mkRef fun _ => throwError "inferType implementation was not set" builtin_initialize isExprDefEqAuxRef : IO.Ref (Expr → Expr → MetaM Bool) ← IO.mkRef fun _ _ => throwError "isDefEq implementation was not set" builtin_initialize synthPendingRef : IO.Ref (MVarId → MetaM Bool) ← IO.mkRef fun _ => pure false def whnf (e : Expr) : MetaM Expr := withIncRecDepth do (← whnfRef.get) e def whnfForall (e : Expr) : MetaM Expr := do let e' ← whnf e if e'.isForall then pure e' else pure e def inferType (e : Expr) : MetaM Expr := withIncRecDepth do (← inferTypeRef.get) e protected def isExprDefEqAux (t s : Expr) : MetaM Bool := withIncRecDepth do (← isExprDefEqAuxRef.get) t s protected def synthPending (mvarId : MVarId) : MetaM Bool := withIncRecDepth do (← synthPendingRef.get) mvarId -- withIncRecDepth for a monad `n` such that `[MonadControlT MetaM n]` protected def withIncRecDepth {α} (x : n α) : n α := mapMetaM (withIncRecDepth (m := MetaM)) x private def mkFreshExprMVarAtCore (mvarId : MVarId) (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr) (kind : MetavarKind) (userName : Name) (numScopeArgs : Nat) : MetaM Expr := do modifyMCtx fun mctx => mctx.addExprMVarDecl mvarId userName lctx localInsts type kind numScopeArgs; pure $ mkMVar mvarId def mkFreshExprMVarAt (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr) (kind : MetavarKind := MetavarKind.natural) (userName : Name := Name.anonymous) (numScopeArgs : Nat := 0) : MetaM Expr := do let mvarId ← mkFreshId mkFreshExprMVarAtCore mvarId lctx localInsts type kind userName numScopeArgs def mkFreshLevelMVar : MetaM Level := do let mvarId ← mkFreshId modifyMCtx fun mctx => mctx.addLevelMVarDecl mvarId; return mkLevelMVar mvarId private def mkFreshExprMVarCore (type : Expr) (kind : MetavarKind) (userName : Name) : MetaM Expr := do let lctx ← getLCtx let localInsts ← getLocalInstances mkFreshExprMVarAt lctx localInsts type kind userName private def mkFreshExprMVarImpl (type? : Option Expr) (kind : MetavarKind) (userName : Name) : MetaM Expr := match type? with | some type => mkFreshExprMVarCore type kind userName | none => do let u ← mkFreshLevelMVar let type ← mkFreshExprMVarCore (mkSort u) MetavarKind.natural Name.anonymous mkFreshExprMVarCore type kind userName def mkFreshExprMVar (type? : Option Expr) (kind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr := mkFreshExprMVarImpl type? kind userName def mkFreshTypeMVar (kind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr := do let u ← mkFreshLevelMVar mkFreshExprMVar (mkSort u) kind userName /- Low-level version of `MkFreshExprMVar` which allows users to create/reserve a `mvarId` using `mkFreshId`, and then later create the metavar using this method. -/ private def mkFreshExprMVarWithIdCore (mvarId : MVarId) (type : Expr) (kind : MetavarKind := MetavarKind.natural) (userName : Name := Name.anonymous) (numScopeArgs : Nat := 0) : MetaM Expr := do let lctx ← getLCtx let localInsts ← getLocalInstances mkFreshExprMVarAtCore mvarId lctx localInsts type kind userName numScopeArgs def mkFreshExprMVarWithId (mvarId : MVarId) (type? : Option Expr := none) (kind : MetavarKind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr := match type? with | some type => mkFreshExprMVarWithIdCore mvarId type kind userName | none => do let u ← mkFreshLevelMVar let type ← mkFreshExprMVar (mkSort u) mkFreshExprMVarWithIdCore mvarId type kind userName def shouldReduceAll : MetaM Bool := return (← read).config.transparency == TransparencyMode.all def shouldReduceReducibleOnly : MetaM Bool := return (← read).config.transparency == TransparencyMode.reducible def getTransparency : MetaM TransparencyMode := return (← read).config.transparency def getMVarDecl (mvarId : MVarId) : MetaM MetavarDecl := do let mctx ← getMCtx match mctx.findDecl? mvarId with | some d => pure d | none => throwError! "unknown metavariable '{mkMVar mvarId}'" def setMVarKind (mvarId : MVarId) (kind : MetavarKind) : MetaM Unit := modifyMCtx fun mctx => mctx.setMVarKind mvarId kind /- Update the type of the given metavariable. This function assumes the new type is definitionally equal to the current one -/ def setMVarType (mvarId : MVarId) (type : Expr) : MetaM Unit := do modifyMCtx fun mctx => mctx.setMVarType mvarId type def isReadOnlyExprMVar (mvarId : MVarId) : MetaM Bool := do let mvarDecl ← getMVarDecl mvarId let mctx ← getMCtx return mvarDecl.depth != mctx.depth def isReadOnlyOrSyntheticOpaqueExprMVar (mvarId : MVarId) : MetaM Bool := do let mvarDecl ← getMVarDecl mvarId match mvarDecl.kind with | MetavarKind.syntheticOpaque => pure true | _ => let mctx ← getMCtx return mvarDecl.depth != mctx.depth def isReadOnlyLevelMVar (mvarId : MVarId) : MetaM Bool := do let mctx ← getMCtx match mctx.findLevelDepth? mvarId with | some depth => return depth != mctx.depth | _ => throwError! "unknown universe metavariable '{mkLevelMVar mvarId}'" def renameMVar (mvarId : MVarId) (newUserName : Name) : MetaM Unit := modifyMCtx fun mctx => mctx.renameMVar mvarId newUserName def isExprMVarAssigned (mvarId : MVarId) : MetaM Bool := return (← getMCtx).isExprAssigned mvarId def getExprMVarAssignment? (mvarId : MVarId) : MetaM (Option Expr) := return (← getMCtx).getExprAssignment? mvarId def assignExprMVar (mvarId : MVarId) (val : Expr) : MetaM Unit := modifyMCtx fun mctx => mctx.assignExpr mvarId val def isDelayedAssigned (mvarId : MVarId) : MetaM Bool := return (← getMCtx).isDelayedAssigned mvarId def getDelayedAssignment? (mvarId : MVarId) : MetaM (Option DelayedMetavarAssignment) := return (← getMCtx).getDelayedAssignment? mvarId def hasAssignableMVar (e : Expr) : MetaM Bool := return (← getMCtx).hasAssignableMVar e def throwUnknownFVar {α} (fvarId : FVarId) : MetaM α := throwError! "unknown free variable '{mkFVar fvarId}'" def findLocalDecl? (fvarId : FVarId) : MetaM (Option LocalDecl) := return (← getLCtx).find? fvarId def getLocalDecl (fvarId : FVarId) : MetaM LocalDecl := do match (← getLCtx).find? fvarId with | some d => pure d | none => throwUnknownFVar fvarId def getFVarLocalDecl (fvar : Expr) : MetaM LocalDecl := getLocalDecl fvar.fvarId! def getLocalDeclFromUserName (userName : Name) : MetaM LocalDecl := do match (← getLCtx).findFromUserName? userName with | some d => pure d | none => throwError! "unknown local declaration '{userName}'" def instantiateLevelMVars (u : Level) : MetaM Level := MetavarContext.instantiateLevelMVars u def instantiateMVars (e : Expr) : MetaM Expr := (MetavarContext.instantiateExprMVars e).run def instantiateLocalDeclMVars (localDecl : LocalDecl) : MetaM LocalDecl := do match localDecl with | LocalDecl.cdecl idx id n type bi => let type ← instantiateMVars type return LocalDecl.cdecl idx id n type bi | LocalDecl.ldecl idx id n type val nonDep => let type ← instantiateMVars type let val ← instantiateMVars val return LocalDecl.ldecl idx id n type val nonDep @[inline] def liftMkBindingM {α} (x : MetavarContext.MkBindingM α) : MetaM α := do match x (← getLCtx) { mctx := (← getMCtx), ngen := (← getNGen) } with | EStateM.Result.ok e newS => do setNGen newS.ngen; setMCtx newS.mctx; pure e | EStateM.Result.error (MetavarContext.MkBinding.Exception.revertFailure mctx lctx toRevert decl) newS => do setMCtx newS.mctx; setNGen newS.ngen; throwError "failed to create binder due to failure when reverting variable dependencies" def mkForallFVars (xs : Array Expr) (e : Expr) : MetaM Expr := if xs.isEmpty then pure e else liftMkBindingM <| MetavarContext.mkForall xs e def mkLambdaFVars (xs : Array Expr) (e : Expr) : MetaM Expr := if xs.isEmpty then pure e else liftMkBindingM <| MetavarContext.mkLambda xs e def mkLetFVars (xs : Array Expr) (e : Expr) : MetaM Expr := mkLambdaFVars xs e def mkArrow (d b : Expr) : MetaM Expr := do let n ← mkFreshUserName `x return Lean.mkForall n BinderInfo.default d b def mkForallUsedOnly (xs : Array Expr) (e : Expr) : MetaM (Expr × Nat) := do if xs.isEmpty then pure (e, 0) else liftMkBindingM <| MetavarContext.mkForallUsedOnly xs e def elimMVarDeps (xs : Array Expr) (e : Expr) (preserveOrder : Bool := false) : MetaM Expr := if xs.isEmpty then pure e else liftMkBindingM <| MetavarContext.elimMVarDeps xs e preserveOrder @[inline] def withConfig {α} (f : Config → Config) : n α → n α := mapMetaM <| withReader (fun ctx => { ctx with config := f ctx.config }) @[inline] def withTrackingZeta {α} (x : n α) : n α := withConfig (fun cfg => { cfg with trackZeta := true }) x @[inline] def withTransparency {α} (mode : TransparencyMode) : n α → n α := mapMetaM <| withConfig (fun config => { config with transparency := mode }) @[inline] def withDefault {α} (x : n α) : n α := withTransparency TransparencyMode.default x @[inline] def withReducible {α} (x : n α) : n α := withTransparency TransparencyMode.reducible x @[inline] def withReducibleAndInstances {α} (x : n α) : n α := withTransparency TransparencyMode.instances x @[inline] def withAtLeastTransparency {α} (mode : TransparencyMode) (x : n α) : n α := withConfig (fun config => let oldMode := config.transparency let mode := if oldMode.lt mode then mode else oldMode { config with transparency := mode }) x /-- Save cache, execute `x`, restore cache -/ @[inline] private def savingCacheImpl {α} (x : MetaM α) : MetaM α := do let s ← get let savedCache := s.cache try x finally modify fun s => { s with cache := savedCache } @[inline] def savingCache {α} : n α → n α := mapMetaM savingCacheImpl def getTheoremInfo (info : ConstantInfo) : MetaM (Option ConstantInfo) := do if (← shouldReduceAll) then return some info else return none private def getDefInfoTemp (info : ConstantInfo) : MetaM (Option ConstantInfo) := do match (← read).config.transparency with | TransparencyMode.all => return some info | TransparencyMode.default => return some info | _ => if (← isReducible info.name) then return some info else return none /- Remark: we later define `getConst?` at `GetConst.lean` after we define `Instances.lean`. This method is only used to implement `isClassQuickConst?`. It is very similar to `getConst?`, but it returns none when `TransparencyMode.instances` and `constName` is an instance. This difference should be irrelevant for `isClassQuickConst?`. -/ private def getConstTemp? (constName : Name) : MetaM (Option ConstantInfo) := do let env ← getEnv match env.find? constName with | some (info@(ConstantInfo.thmInfo _)) => getTheoremInfo info | some (info@(ConstantInfo.defnInfo _)) => getDefInfoTemp info | some info => pure (some info) | none => throwUnknownConstant constName private def isClassQuickConst? (constName : Name) : MetaM (LOption Name) := do let env ← getEnv if isClass env constName then pure (LOption.some constName) else match (← getConstTemp? constName) with | some _ => pure LOption.undef | none => pure LOption.none private partial def isClassQuick? : Expr → MetaM (LOption Name) | Expr.bvar .. => pure LOption.none | Expr.lit .. => pure LOption.none | Expr.fvar .. => pure LOption.none | Expr.sort .. => pure LOption.none | Expr.lam .. => pure LOption.none | Expr.letE .. => pure LOption.undef | Expr.proj .. => pure LOption.undef | Expr.forallE _ _ b _ => isClassQuick? b | Expr.mdata _ e _ => isClassQuick? e | Expr.const n _ _ => isClassQuickConst? n | Expr.mvar mvarId _ => do match (← getExprMVarAssignment? mvarId) with | some val => isClassQuick? val | none => pure LOption.none | Expr.app f _ _ => match f.getAppFn with | Expr.const n .. => isClassQuickConst? n | Expr.lam .. => pure LOption.undef | _ => pure LOption.none def saveAndResetSynthInstanceCache : MetaM SynthInstanceCache := do let s ← get let savedSythInstance := s.cache.synthInstance modify fun s => { s with cache := { s.cache with synthInstance := {} } } pure savedSythInstance def restoreSynthInstanceCache (cache : SynthInstanceCache) : MetaM Unit := modify fun s => { s with cache := { s.cache with synthInstance := cache } } @[inline] private def resettingSynthInstanceCacheImpl {α} (x : MetaM α) : MetaM α := do let savedSythInstance ← saveAndResetSynthInstanceCache try x finally restoreSynthInstanceCache savedSythInstance /-- Reset `synthInstance` cache, execute `x`, and restore cache -/ @[inline] def resettingSynthInstanceCache {α} : n α → n α := mapMetaM resettingSynthInstanceCacheImpl @[inline] def resettingSynthInstanceCacheWhen {α} (b : Bool) (x : n α) : n α := if b then resettingSynthInstanceCache x else x private def withNewLocalInstanceImp {α} (className : Name) (fvar : Expr) (k : MetaM α) : MetaM α := do let localDecl ← getFVarLocalDecl fvar /- Recall that we use `auxDecl` binderInfo when compiling recursive declarations. -/ match localDecl.binderInfo with | BinderInfo.auxDecl => k | _ => resettingSynthInstanceCache $ withReader (fun ctx => { ctx with localInstances := ctx.localInstances.push { className := className, fvar := fvar } }) k /-- Add entry `{ className := className, fvar := fvar }` to localInstances, and then execute continuation `k`. It resets the type class cache using `resettingSynthInstanceCache`. -/ def withNewLocalInstance {α} (className : Name) (fvar : Expr) : n α → n α := mapMetaM $ withNewLocalInstanceImp className fvar private def fvarsSizeLtMaxFVars (fvars : Array Expr) (maxFVars? : Option Nat) : Bool := match maxFVars? with | some maxFVars => fvars.size < maxFVars | none => true mutual /-- `withNewLocalInstances isClassExpensive fvars j k` updates the vector or local instances using free variables `fvars[j] ... fvars.back`, and execute `k`. - `isClassExpensive` is defined later. - The type class chache is reset whenever a new local instance is found. - `isClassExpensive` uses `whnf` which depends (indirectly) on the set of local instances. Thus, each new local instance requires a new `resettingSynthInstanceCache`. -/ private partial def withNewLocalInstancesImp {α} (fvars : Array Expr) (i : Nat) (k : MetaM α) : MetaM α := do if h : i < fvars.size then let fvar := fvars.get ⟨i, h⟩ let decl ← getFVarLocalDecl fvar match (← isClassQuick? decl.type) with | LOption.none => withNewLocalInstancesImp fvars (i+1) k | LOption.undef => match (← isClassExpensive? decl.type) with | none => withNewLocalInstancesImp fvars (i+1) k | some c => withNewLocalInstance c fvar $ withNewLocalInstancesImp fvars (i+1) k | LOption.some c => withNewLocalInstance c fvar $ withNewLocalInstancesImp fvars (i+1) k else k /-- `forallTelescopeAuxAux lctx fvars j type` Remarks: - `lctx` is the `MetaM` local context extended with declarations for `fvars`. - `type` is the type we are computing the telescope for. It contains only dangling bound variables in the range `[j, fvars.size)` - if `reducing? == true` and `type` is not `forallE`, we use `whnf`. - when `type` is not a `forallE` nor it can't be reduced to one, we excute the continuation `k`. Here is an example that demonstrates the `reducing?`. Suppose we have ``` abbrev StateM s a := s -> Prod a s ``` Now, assume we are trying to build the telescope for ``` forall (x : Nat), StateM Int Bool ``` if `reducing == true`, the function executes `k #[(x : Nat) (s : Int)] Bool`. if `reducing == false`, the function executes `k #[(x : Nat)] (StateM Int Bool)` if `maxFVars?` is `some max`, then we interrupt the telescope construction when `fvars.size == max` -/ private partial def forallTelescopeReducingAuxAux {α} (reducing : Bool) (maxFVars? : Option Nat) (type : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α := do let rec process (lctx : LocalContext) (fvars : Array Expr) (j : Nat) (type : Expr) : MetaM α := do match type with | Expr.forallE n d b c => if fvarsSizeLtMaxFVars fvars maxFVars? then let d := d.instantiateRevRange j fvars.size fvars let fvarId ← mkFreshId let lctx := lctx.mkLocalDecl fvarId n d c.binderInfo let fvar := mkFVar fvarId let fvars := fvars.push fvar process lctx fvars j b else let type := type.instantiateRevRange j fvars.size fvars; withReader (fun ctx => { ctx with lctx := lctx }) do withNewLocalInstancesImp fvars j do k fvars type | _ => let type := type.instantiateRevRange j fvars.size fvars; withReader (fun ctx => { ctx with lctx := lctx }) do withNewLocalInstancesImp fvars j do if reducing && fvarsSizeLtMaxFVars fvars maxFVars? then let newType ← whnf type if newType.isForall then process lctx fvars fvars.size newType else k fvars type else k fvars type process (← getLCtx) #[] 0 type private partial def forallTelescopeReducingAux {α} (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → MetaM α) : MetaM α := do match maxFVars? with | some 0 => k #[] type | _ => do let newType ← whnf type if newType.isForall then forallTelescopeReducingAuxAux true maxFVars? newType k else k #[] type private partial def isClassExpensive? : Expr → MetaM (Option Name) | type => withReducible <| -- when testing whether a type is a type class, we only unfold reducible constants. forallTelescopeReducingAux type none fun xs type => do let env ← getEnv match type.getAppFn with | Expr.const c _ _ => do if isClass env c then return some c else -- make sure abbreviations are unfolded match (← whnf type).getAppFn with | Expr.const c _ _ => return if isClass env c then some c else none | _ => return none | _ => return none private partial def isClassImp? (type : Expr) : MetaM (Option Name) := do match (← isClassQuick? type) with | LOption.none => pure none | LOption.some c => pure (some c) | LOption.undef => isClassExpensive? type end def isClass? (type : Expr) : MetaM (Option Name) := try isClassImp? type catch _ => pure none private def withNewLocalInstancesImpAux {α} (fvars : Array Expr) (j : Nat) : n α → n α := mapMetaM $ withNewLocalInstancesImp fvars j partial def withNewLocalInstances {α} (fvars : Array Expr) (j : Nat) : n α → n α := mapMetaM $ withNewLocalInstancesImpAux fvars j @[inline] private def forallTelescopeImp {α} (type : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α := do forallTelescopeReducingAuxAux (reducing := false) (maxFVars? := none) type k /-- Given `type` of the form `forall xs, A`, execute `k xs A`. This combinator will declare local declarations, create free variables for them, execute `k` with updated local context, and make sure the cache is restored after executing `k`. -/ def forallTelescope {α} (type : Expr) (k : Array Expr → Expr → n α) : n α := map2MetaM (fun k => forallTelescopeImp type k) k private def forallTelescopeReducingImp {α} (type : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α := forallTelescopeReducingAux type (maxFVars? := none) k /-- Similar to `forallTelescope`, but given `type` of the form `forall xs, A`, it reduces `A` and continues bulding the telescope if it is a `forall`. -/ def forallTelescopeReducing {α} (type : Expr) (k : Array Expr → Expr → n α) : n α := map2MetaM (fun k => forallTelescopeReducingImp type k) k private def forallBoundedTelescopeImp {α} (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → MetaM α) : MetaM α := forallTelescopeReducingAux type maxFVars? k /-- Similar to `forallTelescopeReducing`, stops constructing the telescope when it reaches size `maxFVars`. -/ def forallBoundedTelescope {α} (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → n α) : n α := map2MetaM (fun k => forallBoundedTelescopeImp type maxFVars? k) k /-- Similar to `forallTelescopeAuxAux` but for lambda and let expressions. -/ private partial def lambdaTelescopeAux {α} (k : Array Expr → Expr → MetaM α) : Bool → LocalContext → Array Expr → Nat → Expr → MetaM α | consumeLet, lctx, fvars, j, Expr.lam n d b c => do let d := d.instantiateRevRange j fvars.size fvars let fvarId ← mkFreshId let lctx := lctx.mkLocalDecl fvarId n d c.binderInfo let fvar := mkFVar fvarId lambdaTelescopeAux k consumeLet lctx (fvars.push fvar) j b | true, lctx, fvars, j, Expr.letE n t v b _ => do let t := t.instantiateRevRange j fvars.size fvars let v := v.instantiateRevRange j fvars.size fvars let fvarId ← mkFreshId let lctx := lctx.mkLetDecl fvarId n t v let fvar := mkFVar fvarId lambdaTelescopeAux k true lctx (fvars.push fvar) j b | _, lctx, fvars, j, e => let e := e.instantiateRevRange j fvars.size fvars; withReader (fun ctx => { ctx with lctx := lctx }) do withNewLocalInstancesImp fvars j do k fvars e private partial def lambdaTelescopeImp {α} (e : Expr) (consumeLet : Bool) (k : Array Expr → Expr → MetaM α) : MetaM α := do let rec process (consumeLet : Bool) (lctx : LocalContext) (fvars : Array Expr) (j : Nat) (e : Expr) : MetaM α := do match consumeLet, e with | _, Expr.lam n d b c => let d := d.instantiateRevRange j fvars.size fvars let fvarId ← mkFreshId let lctx := lctx.mkLocalDecl fvarId n d c.binderInfo let fvar := mkFVar fvarId process consumeLet lctx (fvars.push fvar) j b | true, Expr.letE n t v b _ => do let t := t.instantiateRevRange j fvars.size fvars let v := v.instantiateRevRange j fvars.size fvars let fvarId ← mkFreshId let lctx := lctx.mkLetDecl fvarId n t v let fvar := mkFVar fvarId process true lctx (fvars.push fvar) j b | _, e => let e := e.instantiateRevRange j fvars.size fvars withReader (fun ctx => { ctx with lctx := lctx }) do withNewLocalInstancesImp fvars j do k fvars e process consumeLet (← getLCtx) #[] 0 e /-- Similar to `forallTelescope` but for lambda and let expressions. -/ def lambdaLetTelescope {α} (type : Expr) (k : Array Expr → Expr → n α) : n α := map2MetaM (fun k => lambdaTelescopeImp type true k) k /-- Similar to `forallTelescope` but for lambda expressions. -/ def lambdaTelescope {α} (type : Expr) (k : Array Expr → Expr → n α) : n α := map2MetaM (fun k => lambdaTelescopeImp type false k) k /-- Return the parameter names for the givel global declaration. -/ def getParamNames (declName : Name) : MetaM (Array Name) := do let cinfo ← getConstInfo declName forallTelescopeReducing cinfo.type fun xs _ => do xs.mapM fun x => do let localDecl ← getLocalDecl x.fvarId! pure localDecl.userName -- `kind` specifies the metavariable kind for metavariables not corresponding to instance implicit `[ ... ]` arguments. private partial def forallMetaTelescopeReducingAux (e : Expr) (reducing : Bool) (maxMVars? : Option Nat) (kind : MetavarKind) : MetaM (Array Expr × Array BinderInfo × Expr) := let rec process (mvars : Array Expr) (bis : Array BinderInfo) (j : Nat) (type : Expr) : MetaM (Array Expr × Array BinderInfo × Expr) := do match type with | Expr.forallE n d b c => let cont : Unit → MetaM (Array Expr × Array BinderInfo × Expr) := fun _ => do let d := d.instantiateRevRange j mvars.size mvars let k := if c.binderInfo.isInstImplicit then MetavarKind.synthetic else kind let mvar ← mkFreshExprMVar d k n let mvars := mvars.push mvar let bis := bis.push c.binderInfo process mvars bis j b match maxMVars? with | none => cont () | some maxMVars => if mvars.size < maxMVars then cont () else let type := type.instantiateRevRange j mvars.size mvars; pure (mvars, bis, type) | _ => let type := type.instantiateRevRange j mvars.size mvars; if reducing then do let newType ← whnf type; if newType.isForall then process mvars bis mvars.size newType else pure (mvars, bis, type) else pure (mvars, bis, type) process #[] #[] 0 e /-- Similar to `forallTelescope`, but creates metavariables instead of free variables. -/ def forallMetaTelescope (e : Expr) (kind := MetavarKind.natural) : MetaM (Array Expr × Array BinderInfo × Expr) := forallMetaTelescopeReducingAux e (reducing := false) (maxMVars? := none) kind /-- Similar to `forallTelescopeReducing`, but creates metavariables instead of free variables. -/ def forallMetaTelescopeReducing (e : Expr) (maxMVars? : Option Nat := none) (kind := MetavarKind.natural) : MetaM (Array Expr × Array BinderInfo × Expr) := forallMetaTelescopeReducingAux e (reducing := true) maxMVars? kind /-- Similar to `forallMetaTelescopeReducingAux` but for lambda expressions. -/ partial def lambdaMetaTelescope (e : Expr) (maxMVars? : Option Nat := none) : MetaM (Array Expr × Array BinderInfo × Expr) := let rec process (mvars : Array Expr) (bis : Array BinderInfo) (j : Nat) (type : Expr) : MetaM (Array Expr × Array BinderInfo × Expr) := do let finalize : Unit → MetaM (Array Expr × Array BinderInfo × Expr) := fun _ => do let type := type.instantiateRevRange j mvars.size mvars pure (mvars, bis, type) let cont : Unit → MetaM (Array Expr × Array BinderInfo × Expr) := fun _ => do match type with | Expr.lam n d b c => let d := d.instantiateRevRange j mvars.size mvars let mvar ← mkFreshExprMVar d let mvars := mvars.push mvar let bis := bis.push c.binderInfo process mvars bis j b | _ => finalize () match maxMVars? with | none => cont () | some maxMVars => if mvars.size < maxMVars then cont () else finalize () process #[] #[] 0 e private def withNewFVar {α} (fvar fvarType : Expr) (k : Expr → MetaM α) : MetaM α := do match (← isClass? fvarType) with | none => k fvar | some c => withNewLocalInstance c fvar $ k fvar private def withLocalDeclImp {α} (n : Name) (bi : BinderInfo) (type : Expr) (k : Expr → MetaM α) : MetaM α := do let fvarId ← mkFreshId let ctx ← read let lctx := ctx.lctx.mkLocalDecl fvarId n type bi let fvar := mkFVar fvarId withReader (fun ctx => { ctx with lctx := lctx }) do withNewFVar fvar type k def withLocalDecl {α} (name : Name) (bi : BinderInfo) (type : Expr) (k : Expr → n α) : n α := map1MetaM (fun k => withLocalDeclImp name bi type k) k def withLocalDeclD {α} (name : Name) (type : Expr) (k : Expr → n α) : n α := withLocalDecl name BinderInfo.default type k private def withLetDeclImp {α} (n : Name) (type : Expr) (val : Expr) (k : Expr → MetaM α) : MetaM α := do let fvarId ← mkFreshId let ctx ← read let lctx := ctx.lctx.mkLetDecl fvarId n type val let fvar := mkFVar fvarId withReader (fun ctx => { ctx with lctx := lctx }) do withNewFVar fvar type k def withLetDecl {α} (name : Name) (type : Expr) (val : Expr) (k : Expr → n α) : n α := map1MetaM (fun k => withLetDeclImp name type val k) k private def withExistingLocalDeclsImp {α} (decls : List LocalDecl) (k : MetaM α) : MetaM α := do let ctx ← read let numLocalInstances := ctx.localInstances.size let lctx := decls.foldl (fun (lctx : LocalContext) decl => lctx.addDecl decl) ctx.lctx withReader (fun ctx => { ctx with lctx := lctx }) do let newLocalInsts ← decls.foldlM (fun (newlocalInsts : Array LocalInstance) (decl : LocalDecl) => (do { match (← isClass? decl.type) with | none => pure newlocalInsts | some c => pure $ newlocalInsts.push { className := c, fvar := decl.toExpr } } : MetaM _)) ctx.localInstances; if newLocalInsts.size == numLocalInstances then k else resettingSynthInstanceCache $ withReader (fun ctx => { ctx with localInstances := newLocalInsts }) k def withExistingLocalDecls {α} (decls : List LocalDecl) : n α → n α := mapMetaM $ withExistingLocalDeclsImp decls private def withNewMCtxDepthImp {α} (x : MetaM α) : MetaM α := do let s ← get let savedMCtx := s.mctx modifyMCtx fun mctx => mctx.incDepth try x finally setMCtx savedMCtx /-- Save cache and `MetavarContext`, bump the `MetavarContext` depth, execute `x`, and restore saved data. -/ def withNewMCtxDepth {α} : n α → n α := mapMetaM withNewMCtxDepthImp private def withLocalContextImp {α} (lctx : LocalContext) (localInsts : LocalInstances) (x : MetaM α) : MetaM α := do let localInstsCurr ← getLocalInstances withReader (fun ctx => { ctx with lctx := lctx, localInstances := localInsts }) do if localInsts == localInstsCurr then x else resettingSynthInstanceCache x def withLCtx {α} (lctx : LocalContext) (localInsts : LocalInstances) : n α → n α := mapMetaM $ withLocalContextImp lctx localInsts private def withMVarContextImp {α} (mvarId : MVarId) (x : MetaM α) : MetaM α := do let mvarDecl ← getMVarDecl mvarId withLocalContextImp mvarDecl.lctx mvarDecl.localInstances x /-- Execute `x` using the given metavariable `LocalContext` and `LocalInstances`. The type class resolution cache is flushed when executing `x` if its `LocalInstances` are different from the current ones. -/ def withMVarContext {α} (mvarId : MVarId) : n α → n α := mapMetaM $ withMVarContextImp mvarId private def withMCtxImp {α} (mctx : MetavarContext) (x : MetaM α) : MetaM α := do let mctx' ← getMCtx setMCtx mctx try x finally setMCtx mctx' def withMCtx {α} (mctx : MetavarContext) : n α → n α := mapMetaM $ withMCtxImp mctx @[inline] private def approxDefEqImp {α} (x : MetaM α) : MetaM α := withConfig (fun config => { config with foApprox := true, ctxApprox := true, quasiPatternApprox := true}) x /-- Execute `x` using approximate unification: `foApprox`, `ctxApprox` and `quasiPatternApprox`. -/ @[inline] def approxDefEq {α} : n α → n α := mapMetaM approxDefEqImp @[inline] private def fullApproxDefEqImp {α} (x : MetaM α) : MetaM α := withConfig (fun config => { config with foApprox := true, ctxApprox := true, quasiPatternApprox := true, constApprox := true }) x /-- Similar to `approxDefEq`, but uses all available approximations. We don't use `constApprox` by default at `approxDefEq` because it often produces undesirable solution for monadic code. For example, suppose we have `pure (x > 0)` which has type `?m Prop`. We also have the goal `[Pure ?m]`. Now, assume the expected type is `IO Bool`. Then, the unification constraint `?m Prop =?= IO Bool` could be solved as `?m := fun _ => IO Bool` using `constApprox`, but this spurious solution would generate a failure when we try to solve `[Pure (fun _ => IO Bool)]` -/ @[inline] def fullApproxDefEq {α} : n α → n α := mapMetaM fullApproxDefEqImp def normalizeLevel (u : Level) : MetaM Level := do let u ← instantiateLevelMVars u pure u.normalize def assignLevelMVar (mvarId : MVarId) (u : Level) : MetaM Unit := do modifyMCtx fun mctx => mctx.assignLevel mvarId u def whnfD [MonadLiftT MetaM n] (e : Expr) : n Expr := withTransparency TransparencyMode.default <| whnf e def setInlineAttribute (declName : Name) (kind := Compiler.InlineAttributeKind.inline): MetaM Unit := do let env ← getEnv match Compiler.setInlineAttribute env declName kind with | Except.ok env => setEnv env | Except.error msg => throwError msg private partial def instantiateForallAux (ps : Array Expr) (i : Nat) (e : Expr) : MetaM Expr := do if h : i < ps.size then let p := ps.get ⟨i, h⟩ let e ← whnf e match e with | Expr.forallE _ _ b _ => instantiateForallAux ps (i+1) (b.instantiate1 p) | _ => throwError "invalid instantiateForall, too many parameters" else pure e /- Given `e` of the form `forall (a_1 : A_1) ... (a_n : A_n), B[a_1, ..., a_n]` and `p_1 : A_1, ... p_n : A_n`, return `B[p_1, ..., p_n]`. -/ def instantiateForall (e : Expr) (ps : Array Expr) : MetaM Expr := instantiateForallAux ps 0 e private partial def instantiateLambdaAux (ps : Array Expr) (i : Nat) (e : Expr) : MetaM Expr := do if h : i < ps.size then let p := ps.get ⟨i, h⟩ let e ← whnf e match e with | Expr.lam _ _ b _ => instantiateLambdaAux ps (i+1) (b.instantiate1 p) | _ => throwError "invalid instantiateLambda, too many parameters" else pure e /- Given `e` of the form `fun (a_1 : A_1) ... (a_n : A_n) => t[a_1, ..., a_n]` and `p_1 : A_1, ... p_n : A_n`, return `t[p_1, ..., p_n]`. It uses `whnf` to reduce `e` if it is not a lambda -/ def instantiateLambda (e : Expr) (ps : Array Expr) : MetaM Expr := instantiateLambdaAux ps 0 e /-- Return true iff `e` depends on the free variable `fvarId` -/ def dependsOn (e : Expr) (fvarId : FVarId) : MetaM Bool := return (← getMCtx).exprDependsOn e fvarId def ppExpr (e : Expr) : MetaM Format := do let env ← getEnv let mctx ← getMCtx let lctx ← getLCtx let opts ← getOptions let ctxCore ← readThe Core.Context Lean.ppExpr { env := env, mctx := mctx, lctx := lctx, opts := opts, currNamespace := ctxCore.currNamespace, openDecls := ctxCore.openDecls } e @[inline] protected def orelse {α} (x y : MetaM α) : MetaM α := do let env ← getEnv let mctx ← getMCtx try x catch _ => setEnv env; setMCtx mctx; y instance {α} : OrElse (MetaM α) := ⟨Meta.orelse⟩ @[inline] private def orelseMergeErrorsImp {α} (x y : MetaM α) (mergeRef : Syntax → Syntax → Syntax := fun r₁ r₂ => r₁) (mergeMsg : MessageData → MessageData → MessageData := fun m₁ m₂ => m₁ ++ Format.line ++ m₂) : MetaM α := do let env ← getEnv let mctx ← getMCtx try x catch ex => setEnv env setMCtx mctx match ex with | Exception.error ref₁ m₁ => try y catch | Exception.error ref₂ m₂ => throw $ Exception.error (mergeRef ref₁ ref₂) (mergeMsg m₁ m₂) | ex => throw ex | ex => throw ex /-- Similar to `orelse`, but merge errors. Note that internal errors are not caught. The default `mergeRef` uses the `ref` (position information) for the first message. The default `mergeMsg` combines error messages using `Format.line ++ Format.line` as a separator. -/ @[inline] def orelseMergeErrors {α m} [MonadControlT MetaM m] [Monad m] (x y : m α) (mergeRef : Syntax → Syntax → Syntax := fun r₁ r₂ => r₁) (mergeMsg : MessageData → MessageData → MessageData := fun m₁ m₂ => m₁ ++ Format.line ++ Format.line ++ m₂) : m α := do controlAt MetaM fun runInBase => orelseMergeErrorsImp (runInBase x) (runInBase y) mergeRef mergeMsg /-- Execute `x`, and apply `f` to the produced error message -/ def mapErrorImp {α} (x : MetaM α) (f : MessageData → MessageData) : MetaM α := do try x catch | Exception.error ref msg => throw $ Exception.error ref $ f msg | ex => throw ex @[inline] def mapError {α m} [MonadControlT MetaM m] [Monad m] (x : m α) (f : MessageData → MessageData) : m α := controlAt MetaM fun runInBase => mapErrorImp (runInBase x) f /-- `commitWhenSome? x` executes `x` and keep modifications when it returns `some a`. -/ @[specialize] def commitWhenSome? {α} (x? : MetaM (Option α)) : MetaM (Option α) := do let env ← getEnv let mctx ← getMCtx try match (← x?) with | some a => pure (some a) | none => setEnv env setMCtx mctx pure none catch ex => setEnv env setMCtx mctx throw ex end Methods end Meta export Meta (MetaM) end Lean
b666507e6623f0df39f7974a4ec265aefd540e98
9dc8cecdf3c4634764a18254e94d43da07142918
/src/algebra/category/Module/basic.lean
f331e9d117c94c4286ee3f4226ec653f26923490
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
11,111
lean
/- Copyright (c) 2019 Robert A. Spencer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert A. Spencer, Markus Himmel -/ import algebra.category.Group.preadditive import category_theory.limits.shapes.kernels import category_theory.linear import category_theory.elementwise import linear_algebra.basic import category_theory.conj import category_theory.preadditive.additive_functor /-! # The category of `R`-modules `Module.{v} R` is the category of bundled `R`-modules with carrier in the universe `v`. We show that it is preadditive and show that being an isomorphism, monomorphism and epimorphism is equivalent to being a linear equivalence, an injective linear map and a surjective linear map, respectively. ## Implementation details To construct an object in the category of `R`-modules from a type `M` with an instance of the `module` typeclass, write `of R M`. There is a coercion in the other direction. Similarly, there is a coercion from morphisms in `Module R` to linear maps. Unfortunately, Lean is not smart enough to see that, given an object `M : Module R`, the expression `of R M`, where we coerce `M` to the carrier type, is definitionally equal to `M` itself. This means that to go the other direction, i.e., from linear maps/equivalences to (iso)morphisms in the category of `R`-modules, we have to take care not to inadvertently end up with an `of R M` where `M` is already an object. Hence, given `f : M →ₗ[R] N`, * if `M N : Module R`, simply use `f`; * if `M : Module R` and `N` is an unbundled `R`-module, use `↿f` or `as_hom_left f`; * if `M` is an unbundled `R`-module and `N : Module R`, use `↾f` or `as_hom_right f`; * if `M` and `N` are unbundled `R`-modules, use `↟f` or `as_hom f`. Similarly, given `f : M ≃ₗ[R] N`, use `to_Module_iso`, `to_Module_iso'_left`, `to_Module_iso'_right` or `to_Module_iso'`, respectively. The arrow notations are localized, so you may have to `open_locale Module` to use them. Note that the notation for `as_hom_left` clashes with the notation used to promote functions between types to morphisms in the category `Type`, so to avoid confusion, it is probably a good idea to avoid having the locales `Module` and `category_theory.Type` open at the same time. If you get an error when trying to apply a theorem and the `convert` tactic produces goals of the form `M = of R M`, then you probably used an incorrect variant of `as_hom` or `to_Module_iso`. -/ open category_theory open category_theory.limits open category_theory.limits.walking_parallel_pair universes v u variables (R : Type u) [ring R] /-- The category of R-modules and their morphisms. Note that in the case of `R = ℤ`, we can not impose here that the `ℤ`-multiplication field from the module structure is defeq to the one coming from the `is_add_comm_group` structure (contrary to what we do for all module structures in mathlib), which creates some difficulties down the road. -/ structure Module := (carrier : Type v) [is_add_comm_group : add_comm_group carrier] [is_module : module R carrier] attribute [instance] Module.is_add_comm_group Module.is_module namespace Module instance : has_coe_to_sort (Module.{v} R) (Type v) := ⟨Module.carrier⟩ instance Module_category : category (Module.{v} R) := { hom := λ M N, M →ₗ[R] N, id := λ M, 1, comp := λ A B C f g, g.comp f, id_comp' := λ X Y f, linear_map.id_comp _, comp_id' := λ X Y f, linear_map.comp_id _, assoc' := λ W X Y Z f g h, linear_map.comp_assoc _ _ _ } instance Module_concrete_category : concrete_category.{v} (Module.{v} R) := { forget := { obj := λ R, R, map := λ R S f, (f : R → S) }, forget_faithful := { } } instance has_forget_to_AddCommGroup : has_forget₂ (Module R) AddCommGroup := { forget₂ := { obj := λ M, AddCommGroup.of M, map := λ M₁ M₂ f, linear_map.to_add_monoid_hom f } } instance (M N : Module R) : linear_map_class (M ⟶ N) R M N := { coe := λ f, f, .. linear_map.semilinear_map_class } /-- The object in the category of R-modules associated to an R-module -/ def of (X : Type v) [add_comm_group X] [module R X] : Module R := ⟨X⟩ @[simp] lemma forget₂_obj (X : Module R) : (forget₂ (Module R) AddCommGroup).obj X = AddCommGroup.of X := rfl @[simp] lemma forget₂_obj_Module_of (X : Type v) [add_comm_group X] [module R X] : (forget₂ (Module R) AddCommGroup).obj (of R X) = AddCommGroup.of X := rfl @[simp] lemma forget₂_map (X Y : Module R) (f : X ⟶ Y) : (forget₂ (Module R) AddCommGroup).map f = linear_map.to_add_monoid_hom f := rfl /-- Typecheck a `linear_map` as a morphism in `Module R`. -/ def of_hom {R : Type u} [ring R] {X Y : Type v} [add_comm_group X] [module R X] [add_comm_group Y] [module R Y] (f : X →ₗ[R] Y) : of R X ⟶ of R Y := f @[simp] lemma of_hom_apply {R : Type u} [ring R] {X Y : Type v} [add_comm_group X] [module R X] [add_comm_group Y] [module R Y] (f : X →ₗ[R] Y) (x : X) : of_hom f x = f x := rfl instance : inhabited (Module R) := ⟨of R punit⟩ instance of_unique {X : Type v} [add_comm_group X] [module R X] [i : unique X] : unique (of R X) := i @[simp] lemma coe_of (X : Type v) [add_comm_group X] [module R X] : (of R X : Type v) = X := rfl variables {R} /-- Forgetting to the underlying type and then building the bundled object returns the original module. -/ @[simps] def of_self_iso (M : Module R) : Module.of R M ≅ M := { hom := 𝟙 M, inv := 𝟙 M } lemma is_zero_of_subsingleton (M : Module R) [subsingleton M] : is_zero M := begin refine ⟨λ X, ⟨⟨⟨0⟩, λ f, _⟩⟩, λ X, ⟨⟨⟨0⟩, λ f, _⟩⟩⟩, { ext, have : x = 0 := subsingleton.elim _ _, rw [this, map_zero, map_zero], }, { ext, apply subsingleton.elim } end instance : has_zero_object (Module.{v} R) := ⟨⟨of R punit, is_zero_of_subsingleton _⟩⟩ variables {R} {M N U : Module.{v} R} @[simp] lemma id_apply (m : M) : (𝟙 M : M → M) m = m := rfl @[simp] lemma coe_comp (f : M ⟶ N) (g : N ⟶ U) : ((f ≫ g) : M → U) = g ∘ f := rfl lemma comp_def (f : M ⟶ N) (g : N ⟶ U) : f ≫ g = g.comp f := rfl end Module variables {R} variables {X₁ X₂ : Type v} /-- Reinterpreting a linear map in the category of `R`-modules. -/ def Module.as_hom [add_comm_group X₁] [module R X₁] [add_comm_group X₂] [module R X₂] : (X₁ →ₗ[R] X₂) → (Module.of R X₁ ⟶ Module.of R X₂) := id localized "notation (name := Module.as_hom) `↟` f : 1024 := Module.as_hom f" in Module /-- Reinterpreting a linear map in the category of `R`-modules. -/ def Module.as_hom_right [add_comm_group X₁] [module R X₁] {X₂ : Module.{v} R} : (X₁ →ₗ[R] X₂) → (Module.of R X₁ ⟶ X₂) := id localized "notation (name := Module.as_hom_right) `↾` f : 1024 := Module.as_hom_right f" in Module /-- Reinterpreting a linear map in the category of `R`-modules. -/ def Module.as_hom_left {X₁ : Module.{v} R} [add_comm_group X₂] [module R X₂] : (X₁ →ₗ[R] X₂) → (X₁ ⟶ Module.of R X₂) := id localized "notation (name := Module.as_hom_left) `↿` f : 1024 := Module.as_hom_left f" in Module /-- Build an isomorphism in the category `Module R` from a `linear_equiv` between `module`s. -/ @[simps] def linear_equiv.to_Module_iso {g₁ : add_comm_group X₁} {g₂ : add_comm_group X₂} {m₁ : module R X₁} {m₂ : module R X₂} (e : X₁ ≃ₗ[R] X₂) : Module.of R X₁ ≅ Module.of R X₂ := { hom := (e : X₁ →ₗ[R] X₂), inv := (e.symm : X₂ →ₗ[R] X₁), hom_inv_id' := begin ext, exact e.left_inv x, end, inv_hom_id' := begin ext, exact e.right_inv x, end, } /-- Build an isomorphism in the category `Module R` from a `linear_equiv` between `module`s. This version is better than `linear_equiv_to_Module_iso` when applicable, because Lean can't see `Module.of R M` is defeq to `M` when `M : Module R`. -/ @[simps] def linear_equiv.to_Module_iso' {M N : Module.{v} R} (i : M ≃ₗ[R] N) : M ≅ N := { hom := i, inv := i.symm, hom_inv_id' := linear_map.ext $ λ x, by simp, inv_hom_id' := linear_map.ext $ λ x, by simp } /-- Build an isomorphism in the category `Module R` from a `linear_equiv` between `module`s. This version is better than `linear_equiv_to_Module_iso` when applicable, because Lean can't see `Module.of R M` is defeq to `M` when `M : Module R`. -/ @[simps] def linear_equiv.to_Module_iso'_left {X₁ : Module.{v} R} {g₂ : add_comm_group X₂} {m₂ : module R X₂} (e : X₁ ≃ₗ[R] X₂) : X₁ ≅ Module.of R X₂ := { hom := (e : X₁ →ₗ[R] X₂), inv := (e.symm : X₂ →ₗ[R] X₁), hom_inv_id' := linear_map.ext $ λ x, by simp, inv_hom_id' := linear_map.ext $ λ x, by simp } /-- Build an isomorphism in the category `Module R` from a `linear_equiv` between `module`s. This version is better than `linear_equiv_to_Module_iso` when applicable, because Lean can't see `Module.of R M` is defeq to `M` when `M : Module R`. -/ @[simps] def linear_equiv.to_Module_iso'_right {g₁ : add_comm_group X₁} {m₁ : module R X₁} {X₂ : Module.{v} R} (e : X₁ ≃ₗ[R] X₂) : Module.of R X₁ ≅ X₂ := { hom := (e : X₁ →ₗ[R] X₂), inv := (e.symm : X₂ →ₗ[R] X₁), hom_inv_id' := linear_map.ext $ λ x, by simp, inv_hom_id' := linear_map.ext $ λ x, by simp } namespace category_theory.iso /-- Build a `linear_equiv` from an isomorphism in the category `Module R`. -/ @[simps] def to_linear_equiv {X Y : Module R} (i : X ≅ Y) : X ≃ₗ[R] Y := { to_fun := i.hom, inv_fun := i.inv, left_inv := by tidy, right_inv := by tidy, map_add' := by tidy, map_smul' := by tidy, }. end category_theory.iso /-- linear equivalences between `module`s are the same as (isomorphic to) isomorphisms in `Module` -/ @[simps] def linear_equiv_iso_Module_iso {X Y : Type u} [add_comm_group X] [add_comm_group Y] [module R X] [module R Y] : (X ≃ₗ[R] Y) ≅ (Module.of R X ≅ Module.of R Y) := { hom := λ e, e.to_Module_iso, inv := λ i, i.to_linear_equiv, } namespace Module instance : preadditive (Module.{v} R) := { add_comp' := λ P Q R f f' g, show (f + f') ≫ g = f ≫ g + f' ≫ g, by { ext, simp }, comp_add' := λ P Q R f g g', show f ≫ (g + g') = f ≫ g + f ≫ g', by { ext, simp } } instance forget₂_AddCommGroup_additive : (forget₂ (Module.{v} R) AddCommGroup).additive := {} section variables {S : Type u} [comm_ring S] instance : linear S (Module.{v} S) := { hom_module := λ X Y, linear_map.module, smul_comp' := by { intros, ext, simp }, comp_smul' := by { intros, ext, simp }, } variables {X Y X' Y' : Module.{v} S} lemma iso.hom_congr_eq_arrow_congr (i : X ≅ X') (j : Y ≅ Y') (f : X ⟶ Y) : iso.hom_congr i j f = linear_equiv.arrow_congr i.to_linear_equiv j.to_linear_equiv f := rfl lemma iso.conj_eq_conj (i : X ≅ X') (f : End X) : iso.conj i f = linear_equiv.conj i.to_linear_equiv f := rfl end end Module instance (M : Type u) [add_comm_group M] [module R M] : has_coe (submodule R M) (Module R) := ⟨ λ N, Module.of R N ⟩
0909f68b5ae4977acc34db9a8b10afac0fb6194c
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/macro.lean
1f1f9c2f259b50380cf11f72dabf297c1190fae4
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,225
lean
abbrev Set (α : Type) := α → Prop axiom setOf {α : Type} : (α → Prop) → Set α axiom mem {α : Type} : α → Set α → Prop axiom univ {α : Type} : Set α axiom Union {α : Type} : Set (Set α) → Set α syntax:100 (priority := high) term " ∈ " term:99 : term macro_rules | `($x ∈ $s) => `(mem $x $s) declare_syntax_cat index syntax term : index -- `≤` has precedence 50 syntax term:51 "≤" ident "<" term:51 : index syntax ident ":" term : index syntax "{" index " | " term "}" : term macro_rules | `({$l:term ≤ $x < $u | $p}) => `(setOf (fun $x => $l ≤ $x ∧ $x < $u ∧ $p)) | `({$x:ident : $t | $p}) => `(setOf (fun ($x : $t) => $p)) | `({$x:term ∈ $s | $p}) => `(setOf (fun $x => $x ∈ $s ∧ $p)) | `({$x:term ≤ $e | $p}) => `(setOf (fun $x => $x ≤ $e ∧ $p)) | `({$b:term | $r}) => `(setOf (fun $b => $r)) #check { 1 ≤ x < 10 | x ≠ 5 } #check { f : Nat → Nat | f 1 > 0 } syntax "⋃ " term ", " term : term macro_rules | `(⋃ $b, $r) => `(Union {$b:term | $r}) #check ⋃ x, x = x #check ⋃ (x : Set Unit), x = x #check ⋃ x ∈ univ, x = x syntax "#check2" term : command macro_rules | `(#check2 $e) => `(#check $e #check $e) #check2 1
0d52fac6e5c4499fe1c887f7e711a09d701941f9
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/homology/homological_complex.lean
7bbcf28f61770b698d739c3fb53d4726306a9b82
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
31,853
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Scott Morrison -/ import algebra.homology.complex_shape import category_theory.subobject.limits import category_theory.graded_object /-! # Homological complexes. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. A `homological_complex V c` with a "shape" controlled by `c : complex_shape ι` has chain groups `X i` (objects in `V`) indexed by `i : ι`, and a differential `d i j` whenever `c.rel i j`. We in fact ask for differentials `d i j` for all `i j : ι`, but have a field `shape'` requiring that these are zero when not allowed by `c`. This avoids a lot of dependent type theory hell! The composite of any two differentials `d i j ≫ d j k` must be zero. We provide `chain_complex V α` for `α`-indexed chain complexes in which `d i j ≠ 0` only if `j + 1 = i`, and similarly `cochain_complex V α`, with `i = j + 1`. There is a category structure, where morphisms are chain maps. For `C : homological_complex V c`, we define `C.X_next i`, which is either `C.X j` for some arbitrarily chosen `j` such that `c.r i j`, or `C.X i` if there is no such `j`. Similarly we have `C.X_prev j`. Defined in terms of these we have `C.d_from i : C.X i ⟶ C.X_next i` and `C.d_to j : C.X_prev j ⟶ C.X j`, which are either defined as `C.d i j`, or zero, as needed. -/ universes v u open category_theory category_theory.category category_theory.limits variables {ι : Type*} variables (V : Type u) [category.{v} V] [has_zero_morphisms V] /-- A `homological_complex V c` with a "shape" controlled by `c : complex_shape ι` has chain groups `X i` (objects in `V`) indexed by `i : ι`, and a differential `d i j` whenever `c.rel i j`. We in fact ask for differentials `d i j` for all `i j : ι`, but have a field `shape'` requiring that these are zero when not allowed by `c`. This avoids a lot of dependent type theory hell! The composite of any two differentials `d i j ≫ d j k` must be zero. -/ structure homological_complex (c : complex_shape ι) := (X : ι → V) (d : Π i j, X i ⟶ X j) (shape' : ∀ i j, ¬ c.rel i j → d i j = 0 . obviously) (d_comp_d' : ∀ i j k, c.rel i j → c.rel j k → d i j ≫ d j k = 0 . obviously) namespace homological_complex restate_axiom shape' attribute [simp] shape variables {V} {c : complex_shape ι} @[simp, reassoc] lemma d_comp_d (C : homological_complex V c) (i j k : ι) : C.d i j ≫ C.d j k = 0 := begin by_cases hij : c.rel i j, { by_cases hjk : c.rel j k, { exact C.d_comp_d' i j k hij hjk }, { rw [C.shape j k hjk, comp_zero] } }, { rw [C.shape i j hij, zero_comp] } end lemma ext {C₁ C₂ : homological_complex V c} (h_X : C₁.X = C₂.X) (h_d : ∀ (i j : ι), c.rel i j → C₁.d i j ≫ eq_to_hom (congr_fun h_X j) = eq_to_hom (congr_fun h_X i) ≫ C₂.d i j) : C₁ = C₂ := begin cases C₁, cases C₂, dsimp at h_X, subst h_X, simp only [true_and, eq_self_iff_true, heq_iff_eq], ext i j, by_cases hij : c.rel i j, { simpa only [id_comp, eq_to_hom_refl, comp_id] using h_d i j hij, }, { rw [C₁_shape' i j hij, C₂_shape' i j hij], } end end homological_complex /-- An `α`-indexed chain complex is a `homological_complex` in which `d i j ≠ 0` only if `j + 1 = i`. -/ abbreviation chain_complex (α : Type*) [add_right_cancel_semigroup α] [has_one α] : Type* := homological_complex V (complex_shape.down α) /-- An `α`-indexed cochain complex is a `homological_complex` in which `d i j ≠ 0` only if `i + 1 = j`. -/ abbreviation cochain_complex (α : Type*) [add_right_cancel_semigroup α] [has_one α] : Type* := homological_complex V (complex_shape.up α) namespace chain_complex @[simp] lemma prev (α : Type*) [add_right_cancel_semigroup α] [has_one α] (i : α) : (complex_shape.down α).prev i = i+1 := (complex_shape.down α).prev_eq' rfl @[simp] lemma next (α : Type*) [add_group α] [has_one α] (i : α) : (complex_shape.down α).next i = i-1 := (complex_shape.down α).next_eq' $ sub_add_cancel _ _ @[simp] lemma next_nat_zero : (complex_shape.down ℕ).next 0 = 0 := by { classical, refine dif_neg _, push_neg, intro, apply nat.no_confusion } @[simp] lemma next_nat_succ (i : ℕ) : (complex_shape.down ℕ).next (i+1) = i := (complex_shape.down ℕ).next_eq' rfl end chain_complex namespace cochain_complex @[simp] lemma prev (α : Type*) [add_group α] [has_one α] (i : α) : (complex_shape.up α).prev i = i-1 := (complex_shape.up α).prev_eq' $ sub_add_cancel _ _ @[simp] lemma next (α : Type*) [add_right_cancel_semigroup α] [has_one α] (i : α) : (complex_shape.up α).next i = i+1 := (complex_shape.up α).next_eq' rfl @[simp] lemma prev_nat_zero : (complex_shape.up ℕ).prev 0 = 0 := by { classical, refine dif_neg _, push_neg, intro, apply nat.no_confusion } @[simp] lemma prev_nat_succ (i : ℕ) : (complex_shape.up ℕ).prev (i+1) = i := (complex_shape.up ℕ).prev_eq' rfl end cochain_complex namespace homological_complex variables {V} {c : complex_shape ι} (C : homological_complex V c) /-- A morphism of homological complexes consists of maps between the chain groups, commuting with the differentials. -/ @[ext] structure hom (A B : homological_complex V c) := (f : ∀ i, A.X i ⟶ B.X i) (comm' : ∀ i j, c.rel i j → f i ≫ B.d i j = A.d i j ≫ f j . obviously) @[simp, reassoc] lemma hom.comm {A B : homological_complex V c} (f : A.hom B) (i j : ι) : f.f i ≫ B.d i j = A.d i j ≫ f.f j := begin by_cases hij : c.rel i j, { exact f.comm' i j hij }, rw [A.shape i j hij, B.shape i j hij, comp_zero, zero_comp], end instance (A B : homological_complex V c) : inhabited (hom A B) := ⟨{ f := λ i, 0 }⟩ /-- Identity chain map. -/ def id (A : homological_complex V c) : hom A A := { f := λ _, 𝟙 _ } /-- Composition of chain maps. -/ def comp (A B C : homological_complex V c) (φ : hom A B) (ψ : hom B C) : hom A C := { f := λ i, φ.f i ≫ ψ.f i } section local attribute [simp] id comp instance : category (homological_complex V c) := { hom := hom, id := id, comp := comp } end @[simp] lemma id_f (C : homological_complex V c) (i : ι) : hom.f (𝟙 C) i = 𝟙 (C.X i) := rfl @[simp] lemma comp_f {C₁ C₂ C₃ : homological_complex V c} (f : C₁ ⟶ C₂) (g : C₂ ⟶ C₃) (i : ι) : (f ≫ g).f i = f.f i ≫ g.f i := rfl @[simp] lemma eq_to_hom_f {C₁ C₂ : homological_complex V c} (h : C₁ = C₂) (n : ι) : homological_complex.hom.f (eq_to_hom h) n = eq_to_hom (congr_fun (congr_arg homological_complex.X h) n) := by { subst h, refl, } -- We'll use this later to show that `homological_complex V c` is preadditive when `V` is. lemma hom_f_injective {C₁ C₂ : homological_complex V c} : function.injective (λ f : hom C₁ C₂, f.f) := by tidy instance : has_zero_morphisms (homological_complex V c) := { has_zero := λ C D, ⟨{ f := λ i, 0 }⟩ } @[simp] lemma zero_apply (C D : homological_complex V c) (i : ι) : (0 : C ⟶ D).f i = 0 := rfl open_locale zero_object /-- The zero complex -/ noncomputable def zero [has_zero_object V] : homological_complex V c := { X := λ i, 0, d := λ i j, 0 } lemma is_zero_zero [has_zero_object V] : is_zero (zero : homological_complex V c) := by { refine ⟨λ X, ⟨⟨⟨0⟩, λ f, _⟩⟩, λ X, ⟨⟨⟨0⟩, λ f, _⟩⟩⟩; ext, } instance [has_zero_object V] : has_zero_object (homological_complex V c) := ⟨⟨zero, is_zero_zero⟩⟩ noncomputable instance [has_zero_object V] : inhabited (homological_complex V c) := ⟨zero⟩ lemma congr_hom {C D : homological_complex V c} {f g : C ⟶ D} (w : f = g) (i : ι) : f.f i = g.f i := congr_fun (congr_arg hom.f w) i section variables (V c) /-- The functor picking out the `i`-th object of a complex. -/ @[simps] def eval (i : ι) : homological_complex V c ⥤ V := { obj := λ C, C.X i, map := λ C D f, f.f i, } /-- The functor forgetting the differential in a complex, obtaining a graded object. -/ @[simps] def forget : homological_complex V c ⥤ graded_object ι V := { obj := λ C, C.X, map := λ _ _ f, f.f } /-- Forgetting the differentials than picking out the `i`-th object is the same as just picking out the `i`-th object. -/ @[simps] def forget_eval (i : ι) : forget V c ⋙ graded_object.eval i ≅ eval V c i := nat_iso.of_components (λ X, iso.refl _) (by tidy) end open_locale classical noncomputable theory /-- If `C.d i j` and `C.d i j'` are both allowed, then we must have `j = j'`, and so the differentials only differ by an `eq_to_hom`. -/ @[simp] lemma d_comp_eq_to_hom {i j j' : ι} (rij : c.rel i j) (rij' : c.rel i j') : C.d i j' ≫ eq_to_hom (congr_arg C.X (c.next_eq rij' rij)) = C.d i j := begin have P : ∀ h : j' = j, C.d i j' ≫ eq_to_hom (congr_arg C.X h) = C.d i j, { rintro rfl, simp }, apply P, end /-- If `C.d i j` and `C.d i' j` are both allowed, then we must have `i = i'`, and so the differentials only differ by an `eq_to_hom`. -/ @[simp] lemma eq_to_hom_comp_d {i i' j : ι} (rij : c.rel i j) (rij' : c.rel i' j) : eq_to_hom (congr_arg C.X (c.prev_eq rij rij')) ≫ C.d i' j = C.d i j := begin have P : ∀ h : i = i', eq_to_hom (congr_arg C.X h) ≫ C.d i' j = C.d i j, { rintro rfl, simp }, apply P, end lemma kernel_eq_kernel [has_kernels V] {i j j' : ι} (r : c.rel i j) (r' : c.rel i j') : kernel_subobject (C.d i j) = kernel_subobject (C.d i j') := begin rw ←d_comp_eq_to_hom C r r', apply kernel_subobject_comp_mono, end lemma image_eq_image [has_images V] [has_equalizers V] {i i' j : ι} (r : c.rel i j) (r' : c.rel i' j) : image_subobject (C.d i j) = image_subobject (C.d i' j) := begin rw ←eq_to_hom_comp_d C r r', apply image_subobject_iso_comp, end section /-- Either `C.X i`, if there is some `i` with `c.rel i j`, or `C.X j`. -/ abbreviation X_prev (j : ι) : V := C.X (c.prev j) /-- If `c.rel i j`, then `C.X_prev j` is isomorphic to `C.X i`. -/ def X_prev_iso {i j : ι} (r : c.rel i j) : C.X_prev j ≅ C.X i := eq_to_iso $ by rw ← c.prev_eq' r /-- If there is no `i` so `c.rel i j`, then `C.X_prev j` is isomorphic to `C.X j`. -/ def X_prev_iso_self {j : ι} (h : ¬c.rel (c.prev j) j) : C.X_prev j ≅ C.X j := eq_to_iso $ congr_arg C.X begin dsimp [complex_shape.prev], rw dif_neg, push_neg, intros i hi, have : c.prev j = i := c.prev_eq' hi, rw this at h, contradiction, end /-- Either `C.X j`, if there is some `j` with `c.rel i j`, or `C.X i`. -/ abbreviation X_next (i : ι) : V := C.X (c.next i) /-- If `c.rel i j`, then `C.X_next i` is isomorphic to `C.X j`. -/ def X_next_iso {i j : ι} (r : c.rel i j) : C.X_next i ≅ C.X j := eq_to_iso $ by rw ← c.next_eq' r /-- If there is no `j` so `c.rel i j`, then `C.X_next i` is isomorphic to `C.X i`. -/ def X_next_iso_self {i : ι} (h : ¬c.rel i (c.next i)) : C.X_next i ≅ C.X i := eq_to_iso $ congr_arg C.X begin dsimp [complex_shape.next], rw dif_neg, rintro ⟨j, hj⟩, have : c.next i = j := c.next_eq' hj, rw this at h, contradiction, end /-- The differential mapping into `C.X j`, or zero if there isn't one. -/ abbreviation d_to (j : ι) : C.X_prev j ⟶ C.X j := C.d (c.prev j) j /-- The differential mapping out of `C.X i`, or zero if there isn't one. -/ abbreviation d_from (i : ι) : C.X i ⟶ C.X_next i := C.d i (c.next i) lemma d_to_eq {i j : ι} (r : c.rel i j) : C.d_to j = (C.X_prev_iso r).hom ≫ C.d i j := begin obtain rfl := c.prev_eq' r, exact (category.id_comp _).symm, end @[simp] lemma d_to_eq_zero {j : ι} (h : ¬c.rel (c.prev j) j) : C.d_to j = 0 := C.shape _ _ h lemma d_from_eq {i j : ι} (r : c.rel i j) : C.d_from i = C.d i j ≫ (C.X_next_iso r).inv := begin obtain rfl := c.next_eq' r, exact (category.comp_id _).symm, end @[simp] lemma d_from_eq_zero {i : ι} (h : ¬c.rel i (c.next i)) : C.d_from i = 0 := C.shape _ _ h @[simp, reassoc] lemma X_prev_iso_comp_d_to {i j : ι} (r : c.rel i j) : (C.X_prev_iso r).inv ≫ C.d_to j = C.d i j := by simp [C.d_to_eq r] @[simp, reassoc] lemma X_prev_iso_self_comp_d_to {j : ι} (h : ¬c.rel (c.prev j) j) : (C.X_prev_iso_self h).inv ≫ C.d_to j = 0 := by simp [h] @[simp, reassoc] lemma d_from_comp_X_next_iso {i j : ι} (r : c.rel i j) : C.d_from i ≫ (C.X_next_iso r).hom = C.d i j := by simp [C.d_from_eq r] @[simp, reassoc] lemma d_from_comp_X_next_iso_self {i : ι} (h : ¬c.rel i (c.next i)) : C.d_from i ≫ (C.X_next_iso_self h).hom = 0 := by simp [h] @[simp] lemma d_to_comp_d_from (j : ι) : C.d_to j ≫ C.d_from j = 0 := C.d_comp_d _ _ _ lemma kernel_from_eq_kernel [has_kernels V] {i j : ι} (r : c.rel i j) : kernel_subobject (C.d_from i) = kernel_subobject (C.d i j) := begin rw C.d_from_eq r, apply kernel_subobject_comp_mono, end lemma image_to_eq_image [has_images V] [has_equalizers V] {i j : ι} (r : c.rel i j) : image_subobject (C.d_to j) = image_subobject (C.d i j) := begin rw C.d_to_eq r, apply image_subobject_iso_comp, end end namespace hom variables {C₁ C₂ C₃ : homological_complex V c} /-- The `i`-th component of an isomorphism of chain complexes. -/ @[simps] def iso_app (f : C₁ ≅ C₂) (i : ι) : C₁.X i ≅ C₂.X i := (eval V c i).map_iso f /-- Construct an isomorphism of chain complexes from isomorphism of the objects which commute with the differentials. -/ @[simps] def iso_of_components (f : Π i, C₁.X i ≅ C₂.X i) (hf : ∀ i j, c.rel i j → (f i).hom ≫ C₂.d i j = C₁.d i j ≫ (f j).hom) : C₁ ≅ C₂ := { hom := { f := λ i, (f i).hom, comm' := hf }, inv := { f := λ i, (f i).inv, comm' := λ i j hij, calc (f i).inv ≫ C₁.d i j = (f i).inv ≫ (C₁.d i j ≫ (f j).hom) ≫ (f j).inv : by simp ... = (f i).inv ≫ ((f i).hom ≫ C₂.d i j) ≫ (f j).inv : by rw hf i j hij ... = C₂.d i j ≫ (f j).inv : by simp }, hom_inv_id' := by { ext i, exact (f i).hom_inv_id }, inv_hom_id' := by { ext i, exact (f i).inv_hom_id } } @[simp] lemma iso_of_components_app (f : Π i, C₁.X i ≅ C₂.X i) (hf : ∀ i j, c.rel i j → (f i).hom ≫ C₂.d i j = C₁.d i j ≫ (f j).hom) (i : ι) : iso_app (iso_of_components f hf) i = f i := by { ext, simp, } lemma is_iso_of_components (f : C₁ ⟶ C₂) [∀ (n : ι), is_iso (f.f n)] : is_iso f := begin convert is_iso.of_iso (homological_complex.hom.iso_of_components (λ n, as_iso (f.f n)) (by tidy)), ext n, refl, end /-! Lemmas relating chain maps and `d_to`/`d_from`. -/ /-- `f.prev j` is `f.f i` if there is some `r i j`, and `f.f j` otherwise. -/ abbreviation prev (f : hom C₁ C₂) (j : ι) : C₁.X_prev j ⟶ C₂.X_prev j := f.f _ lemma prev_eq (f : hom C₁ C₂) {i j : ι} (w : c.rel i j) : f.prev j = (C₁.X_prev_iso w).hom ≫ f.f i ≫ (C₂.X_prev_iso w).inv := begin obtain rfl := c.prev_eq' w, simp only [X_prev_iso, eq_to_iso_refl, iso.refl_hom, iso.refl_inv, id_comp, comp_id], end /-- `f.next i` is `f.f j` if there is some `r i j`, and `f.f j` otherwise. -/ abbreviation next (f : hom C₁ C₂) (i : ι) : C₁.X_next i ⟶ C₂.X_next i := f.f _ lemma next_eq (f : hom C₁ C₂) {i j : ι} (w : c.rel i j) : f.next i = (C₁.X_next_iso w).hom ≫ f.f j ≫ (C₂.X_next_iso w).inv := begin obtain rfl := c.next_eq' w, simp only [X_next_iso, eq_to_iso_refl, iso.refl_hom, iso.refl_inv, id_comp, comp_id], end @[simp, reassoc, elementwise] lemma comm_from (f : hom C₁ C₂) (i : ι) : f.f i ≫ C₂.d_from i = C₁.d_from i ≫ f.next i := f.comm _ _ @[simp, reassoc, elementwise] lemma comm_to (f : hom C₁ C₂) (j : ι) : f.prev j ≫ C₂.d_to j = C₁.d_to j ≫ f.f j := f.comm _ _ /-- A morphism of chain complexes induces a morphism of arrows of the differentials out of each object. -/ def sq_from (f : hom C₁ C₂) (i : ι) : arrow.mk (C₁.d_from i) ⟶ arrow.mk (C₂.d_from i) := arrow.hom_mk (f.comm_from i) @[simp] lemma sq_from_left (f : hom C₁ C₂) (i : ι) : (f.sq_from i).left = f.f i := rfl @[simp] lemma sq_from_right (f : hom C₁ C₂) (i : ι) : (f.sq_from i).right = f.next i := rfl @[simp] lemma sq_from_id (C₁ : homological_complex V c) (i : ι) : sq_from (𝟙 C₁) i = 𝟙 _ := rfl @[simp] lemma sq_from_comp (f : C₁ ⟶ C₂) (g : C₂ ⟶ C₃) (i : ι) : sq_from (f ≫ g) i = sq_from f i ≫ sq_from g i := rfl /-- A morphism of chain complexes induces a morphism of arrows of the differentials into each object. -/ def sq_to (f : hom C₁ C₂) (j : ι) : arrow.mk (C₁.d_to j) ⟶ arrow.mk (C₂.d_to j) := arrow.hom_mk (f.comm_to j) @[simp] lemma sq_to_left (f : hom C₁ C₂) (j : ι) : (f.sq_to j).left = f.prev j := rfl @[simp] lemma sq_to_right (f : hom C₁ C₂) (j : ι) : (f.sq_to j).right = f.f j := rfl end hom end homological_complex namespace chain_complex section of variables {V} {α : Type*} [add_right_cancel_semigroup α] [has_one α] [decidable_eq α] /-- Construct an `α`-indexed chain complex from a dependently-typed differential. -/ def of (X : α → V) (d : Π n, X (n+1) ⟶ X n) (sq : ∀ n, d (n+1) ≫ d n = 0) : chain_complex V α := { X := X, d := λ i j, if h : i = j + 1 then eq_to_hom (by subst h) ≫ d j else 0, shape' := λ i j w, by rw dif_neg (ne.symm w), d_comp_d' := λ i j k hij hjk, begin dsimp at hij hjk, substs hij hjk, simp only [category.id_comp, dif_pos rfl, eq_to_hom_refl], exact sq k, end } variables (X : α → V) (d : Π n, X (n+1) ⟶ X n) (sq : ∀ n, d (n+1) ≫ d n = 0) @[simp] lemma of_X (n : α) : (of X d sq).X n = X n := rfl @[simp] lemma of_d (j : α) : (of X d sq).d (j+1) j = d j := by { dsimp [of], rw [if_pos rfl, category.id_comp] } lemma of_d_ne {i j : α} (h : i ≠ j + 1) : (of X d sq).d i j = 0 := by { dsimp [of], rw [dif_neg h], } end of section of_hom variables {V} {α : Type*} [add_right_cancel_semigroup α] [has_one α] [decidable_eq α] variables (X : α → V) (d_X : Π n, X (n+1) ⟶ X n) (sq_X : ∀ n, d_X (n+1) ≫ d_X n = 0) (Y : α → V) (d_Y : Π n, Y (n+1) ⟶ Y n) (sq_Y : ∀ n, d_Y (n+1) ≫ d_Y n = 0) /-- A constructor for chain maps between `α`-indexed chain complexes built using `chain_complex.of`, from a dependently typed collection of morphisms. -/ @[simps] def of_hom (f : Π i : α, X i ⟶ Y i) (comm : ∀ i : α, f (i+1) ≫ d_Y i = d_X i ≫ f i) : of X d_X sq_X ⟶ of Y d_Y sq_Y := { f := f, comm' := λ n m, begin by_cases h : n = m + 1, { subst h, simpa using comm m, }, { rw [of_d_ne X _ _ h, of_d_ne Y _ _ h], simp } end } end of_hom section mk /-- Auxiliary structure for setting up the recursion in `mk`. This is purely an implementation detail: for some reason just using the dependent 6-tuple directly results in `mk_aux` taking much longer (well over the `-T100000` limit) to elaborate. -/ @[nolint has_nonempty_instance] structure mk_struct := (X₀ X₁ X₂ : V) (d₀ : X₁ ⟶ X₀) (d₁ : X₂ ⟶ X₁) (s : d₁ ≫ d₀ = 0) variables {V} /-- Flatten to a tuple. -/ def mk_struct.flat (t : mk_struct V) : Σ' (X₀ X₁ X₂ : V) (d₀ : X₁ ⟶ X₀) (d₁ : X₂ ⟶ X₁), d₁ ≫ d₀ = 0 := ⟨t.X₀, t.X₁, t.X₂, t.d₀, t.d₁, t.s⟩ variables (X₀ X₁ X₂ : V) (d₀ : X₁ ⟶ X₀) (d₁ : X₂ ⟶ X₁) (s : d₁ ≫ d₀ = 0) (succ : Π (t : Σ' (X₀ X₁ X₂ : V) (d₀ : X₁ ⟶ X₀) (d₁ : X₂ ⟶ X₁), d₁ ≫ d₀ = 0), Σ' (X₃ : V) (d₂ : X₃ ⟶ t.2.2.1), d₂ ≫ t.2.2.2.2.1 = 0) /-- Auxiliary definition for `mk`. -/ def mk_aux : Π n : ℕ, mk_struct V | 0 := ⟨X₀, X₁, X₂, d₀, d₁, s⟩ | (n+1) := let p := mk_aux n in ⟨p.X₁, p.X₂, (succ p.flat).1, p.d₁, (succ p.flat).2.1, (succ p.flat).2.2⟩ /-- A inductive constructor for `ℕ`-indexed chain complexes. You provide explicitly the first two differentials, then a function which takes two differentials and the fact they compose to zero, and returns the next object, its differential, and the fact it composes appropiately to zero. See also `mk'`, which only sees the previous differential in the inductive step. -/ def mk : chain_complex V ℕ := of (λ n, (mk_aux X₀ X₁ X₂ d₀ d₁ s succ n).X₀) (λ n, (mk_aux X₀ X₁ X₂ d₀ d₁ s succ n).d₀) (λ n, (mk_aux X₀ X₁ X₂ d₀ d₁ s succ n).s) @[simp] lemma mk_X_0 : (mk X₀ X₁ X₂ d₀ d₁ s succ).X 0 = X₀ := rfl @[simp] lemma mk_X_1 : (mk X₀ X₁ X₂ d₀ d₁ s succ).X 1 = X₁ := rfl @[simp] lemma mk_X_2 : (mk X₀ X₁ X₂ d₀ d₁ s succ).X 2 = X₂ := rfl @[simp] lemma mk_d_1_0 : (mk X₀ X₁ X₂ d₀ d₁ s succ).d 1 0 = d₀ := by { change ite (1 = 0 + 1) (𝟙 X₁ ≫ d₀) 0 = d₀, rw [if_pos rfl, category.id_comp] } @[simp] lemma mk_d_2_0 : (mk X₀ X₁ X₂ d₀ d₁ s succ).d 2 1 = d₁ := by { change ite (2 = 1 + 1) (𝟙 X₂ ≫ d₁) 0 = d₁, rw [if_pos rfl, category.id_comp] } -- TODO simp lemmas for the inductive steps? It's not entirely clear that they are needed. /-- A simpler inductive constructor for `ℕ`-indexed chain complexes. You provide explicitly the first differential, then a function which takes a differential, and returns the next object, its differential, and the fact it composes appropriately to zero. -/ def mk' (X₀ X₁ : V) (d : X₁ ⟶ X₀) (succ' : Π (t : Σ (X₀ X₁ : V), X₁ ⟶ X₀), Σ' (X₂ : V) (d : X₂ ⟶ t.2.1), d ≫ t.2.2 = 0) : chain_complex V ℕ := mk X₀ X₁ (succ' ⟨X₀, X₁, d⟩).1 d (succ' ⟨X₀, X₁, d⟩).2.1 (succ' ⟨X₀, X₁, d⟩).2.2 (λ t, succ' ⟨t.2.1, t.2.2.1, t.2.2.2.2.1⟩) variables (succ' : Π (t : Σ (X₀ X₁ : V), X₁ ⟶ X₀), Σ' (X₂ : V) (d : X₂ ⟶ t.2.1), d ≫ t.2.2 = 0) @[simp] lemma mk'_X_0 : (mk' X₀ X₁ d₀ succ').X 0 = X₀ := rfl @[simp] lemma mk'_X_1 : (mk' X₀ X₁ d₀ succ').X 1 = X₁ := rfl @[simp] lemma mk'_d_1_0 : (mk' X₀ X₁ d₀ succ').d 1 0 = d₀ := by { change ite (1 = 0 + 1) (𝟙 X₁ ≫ d₀) 0 = d₀, rw [if_pos rfl, category.id_comp] } -- TODO simp lemmas for the inductive steps? It's not entirely clear that they are needed. end mk section mk_hom variables {V} (P Q : chain_complex V ℕ) (zero : P.X 0 ⟶ Q.X 0) (one : P.X 1 ⟶ Q.X 1) (one_zero_comm : one ≫ Q.d 1 0 = P.d 1 0 ≫ zero) (succ : ∀ (n : ℕ) (p : Σ' (f : P.X n ⟶ Q.X n) (f' : P.X (n+1) ⟶ Q.X (n+1)), f' ≫ Q.d (n+1) n = P.d (n+1) n ≫ f), Σ' f'' : P.X (n+2) ⟶ Q.X (n+2), f'' ≫ Q.d (n+2) (n+1) = P.d (n+2) (n+1) ≫ p.2.1) /-- An auxiliary construction for `mk_hom`. Here we build by induction a family of commutative squares, but don't require at the type level that these successive commutative squares actually agree. They do in fact agree, and we then capture that at the type level (i.e. by constructing a chain map) in `mk_hom`. -/ def mk_hom_aux : Π n, Σ' (f : P.X n ⟶ Q.X n) (f' : P.X (n+1) ⟶ Q.X (n+1)), f' ≫ Q.d (n+1) n = P.d (n+1) n ≫ f | 0 := ⟨zero, one, one_zero_comm⟩ | (n+1) := ⟨(mk_hom_aux n).2.1, (succ n (mk_hom_aux n)).1, (succ n (mk_hom_aux n)).2⟩ /-- A constructor for chain maps between `ℕ`-indexed chain complexes, working by induction on commutative squares. You need to provide the components of the chain map in degrees 0 and 1, show that these form a commutative square, and then give a construction of each component, and the fact that it forms a commutative square with the previous component, using as an inductive hypothesis the data (and commutativity) of the previous two components. -/ def mk_hom : P ⟶ Q := { f := λ n, (mk_hom_aux P Q zero one one_zero_comm succ n).1, comm' := λ n m, begin rintro (rfl : m + 1 = n), exact (mk_hom_aux P Q zero one one_zero_comm succ m).2.2, end } @[simp] lemma mk_hom_f_0 : (mk_hom P Q zero one one_zero_comm succ).f 0 = zero := rfl @[simp] lemma mk_hom_f_1 : (mk_hom P Q zero one one_zero_comm succ).f 1 = one := rfl @[simp] lemma mk_hom_f_succ_succ (n : ℕ) : (mk_hom P Q zero one one_zero_comm succ).f (n+2) = (succ n ⟨(mk_hom P Q zero one one_zero_comm succ).f n, (mk_hom P Q zero one one_zero_comm succ).f (n+1), (mk_hom P Q zero one one_zero_comm succ).comm (n+1) n⟩).1 := begin dsimp [mk_hom, mk_hom_aux], induction n; congr, end end mk_hom end chain_complex namespace cochain_complex section of variables {V} {α : Type*} [add_right_cancel_semigroup α] [has_one α] [decidable_eq α] /-- Construct an `α`-indexed cochain complex from a dependently-typed differential. -/ def of (X : α → V) (d : Π n, X n ⟶ X (n+1)) (sq : ∀ n, d n ≫ d (n+1) = 0) : cochain_complex V α := { X := X, d := λ i j, if h : i + 1 = j then d _ ≫ eq_to_hom (by subst h) else 0, shape' := λ i j w, by {rw dif_neg, exact w}, d_comp_d' := λ i j k, begin split_ifs with h h' h', { substs h h', simp [sq] }, all_goals { simp }, end } variables (X : α → V) (d : Π n, X n ⟶ X (n+1)) (sq : ∀ n, d n ≫ d (n+1) = 0) @[simp] lemma of_X (n : α) : (of X d sq).X n = X n := rfl @[simp] lemma of_d (j : α) : (of X d sq).d j (j+1) = d j := by { dsimp [of], rw [if_pos rfl, category.comp_id] } lemma of_d_ne {i j : α} (h : i + 1 ≠ j) : (of X d sq).d i j = 0 := by { dsimp [of], rw [dif_neg h] } end of section of_hom variables {V} {α : Type*} [add_right_cancel_semigroup α] [has_one α] [decidable_eq α] variables (X : α → V) (d_X : Π n, X n ⟶ X (n+1)) (sq_X : ∀ n, d_X n ≫ d_X (n+1) = 0) (Y : α → V) (d_Y : Π n, Y n ⟶ Y (n+1)) (sq_Y : ∀ n, d_Y n ≫ d_Y (n+1) = 0) /-- A constructor for chain maps between `α`-indexed cochain complexes built using `cochain_complex.of`, from a dependently typed collection of morphisms. -/ @[simps] def of_hom (f : Π i : α, X i ⟶ Y i) (comm : ∀ i : α, f i ≫ d_Y i = d_X i ≫ f (i+1)) : of X d_X sq_X ⟶ of Y d_Y sq_Y := { f := f, comm' := λ n m, begin by_cases h : n + 1 = m, { subst h, simpa using comm n }, { rw [of_d_ne X _ _ h, of_d_ne Y _ _ h], simp } end } end of_hom section mk /-- Auxiliary structure for setting up the recursion in `mk`. This is purely an implementation detail: for some reason just using the dependent 6-tuple directly results in `mk_aux` taking much longer (well over the `-T100000` limit) to elaborate. -/ @[nolint has_nonempty_instance] structure mk_struct := (X₀ X₁ X₂ : V) (d₀ : X₀ ⟶ X₁) (d₁ : X₁ ⟶ X₂) (s : d₀ ≫ d₁ = 0) variables {V} /-- Flatten to a tuple. -/ def mk_struct.flat (t : mk_struct V) : Σ' (X₀ X₁ X₂ : V) (d₀ : X₀ ⟶ X₁) (d₁ : X₁ ⟶ X₂), d₀ ≫ d₁ = 0 := ⟨t.X₀, t.X₁, t.X₂, t.d₀, t.d₁, t.s⟩ variables (X₀ X₁ X₂ : V) (d₀ : X₀ ⟶ X₁) (d₁ : X₁ ⟶ X₂) (s : d₀ ≫ d₁ = 0) (succ : Π (t : Σ' (X₀ X₁ X₂ : V) (d₀ : X₀ ⟶ X₁) (d₁ : X₁ ⟶ X₂), d₀ ≫ d₁ = 0), Σ' (X₃ : V) (d₂ : t.2.2.1 ⟶ X₃), t.2.2.2.2.1 ≫ d₂ = 0) /-- Auxiliary definition for `mk`. -/ def mk_aux : Π n : ℕ, mk_struct V | 0 := ⟨X₀, X₁, X₂, d₀, d₁, s⟩ | (n+1) := let p := mk_aux n in ⟨p.X₁, p.X₂, (succ p.flat).1, p.d₁, (succ p.flat).2.1, (succ p.flat).2.2⟩ /-- A inductive constructor for `ℕ`-indexed cochain complexes. You provide explicitly the first two differentials, then a function which takes two differentials and the fact they compose to zero, and returns the next object, its differential, and the fact it composes appropiately to zero. See also `mk'`, which only sees the previous differential in the inductive step. -/ def mk : cochain_complex V ℕ := of (λ n, (mk_aux X₀ X₁ X₂ d₀ d₁ s succ n).X₀) (λ n, (mk_aux X₀ X₁ X₂ d₀ d₁ s succ n).d₀) (λ n, (mk_aux X₀ X₁ X₂ d₀ d₁ s succ n).s) @[simp] lemma mk_X_0 : (mk X₀ X₁ X₂ d₀ d₁ s succ).X 0 = X₀ := rfl @[simp] lemma mk_X_1 : (mk X₀ X₁ X₂ d₀ d₁ s succ).X 1 = X₁ := rfl @[simp] lemma mk_X_2 : (mk X₀ X₁ X₂ d₀ d₁ s succ).X 2 = X₂ := rfl @[simp] lemma mk_d_1_0 : (mk X₀ X₁ X₂ d₀ d₁ s succ).d 0 1 = d₀ := by { change ite (1 = 0 + 1) (d₀ ≫ 𝟙 X₁) 0 = d₀, rw [if_pos rfl, category.comp_id] } @[simp] lemma mk_d_2_0 : (mk X₀ X₁ X₂ d₀ d₁ s succ).d 1 2 = d₁ := by { change ite (2 = 1 + 1) (d₁ ≫ 𝟙 X₂) 0 = d₁, rw [if_pos rfl, category.comp_id] } -- TODO simp lemmas for the inductive steps? It's not entirely clear that they are needed. /-- A simpler inductive constructor for `ℕ`-indexed cochain complexes. You provide explicitly the first differential, then a function which takes a differential, and returns the next object, its differential, and the fact it composes appropriately to zero. -/ def mk' (X₀ X₁ : V) (d : X₀ ⟶ X₁) (succ' : Π (t : Σ (X₀ X₁ : V), X₀ ⟶ X₁), Σ' (X₂ : V) (d : t.2.1 ⟶ X₂), t.2.2 ≫ d = 0) : cochain_complex V ℕ := mk X₀ X₁ (succ' ⟨X₀, X₁, d⟩).1 d (succ' ⟨X₀, X₁, d⟩).2.1 (succ' ⟨X₀, X₁, d⟩).2.2 (λ t, succ' ⟨t.2.1, t.2.2.1, t.2.2.2.2.1⟩) variables (succ' : Π (t : Σ (X₀ X₁ : V), X₀ ⟶ X₁), Σ' (X₂ : V) (d : t.2.1 ⟶ X₂), t.2.2 ≫ d = 0) @[simp] lemma mk'_X_0 : (mk' X₀ X₁ d₀ succ').X 0 = X₀ := rfl @[simp] lemma mk'_X_1 : (mk' X₀ X₁ d₀ succ').X 1 = X₁ := rfl @[simp] lemma mk'_d_1_0 : (mk' X₀ X₁ d₀ succ').d 0 1 = d₀ := by { change ite (1 = 0 + 1) (d₀ ≫ 𝟙 X₁) 0 = d₀, rw [if_pos rfl, category.comp_id] } -- TODO simp lemmas for the inductive steps? It's not entirely clear that they are needed. end mk section mk_hom variables {V} (P Q : cochain_complex V ℕ) (zero : P.X 0 ⟶ Q.X 0) (one : P.X 1 ⟶ Q.X 1) (one_zero_comm : zero ≫ Q.d 0 1 = P.d 0 1 ≫ one) (succ : ∀ (n : ℕ) (p : Σ' (f : P.X n ⟶ Q.X n) (f' : P.X (n+1) ⟶ Q.X (n+1)), f ≫ Q.d n (n+1) = P.d n (n+1) ≫ f'), Σ' f'' : P.X (n+2) ⟶ Q.X (n+2), p.2.1 ≫ Q.d (n+1) (n+2) = P.d (n+1) (n+2) ≫ f'') /-- An auxiliary construction for `mk_hom`. Here we build by induction a family of commutative squares, but don't require at the type level that these successive commutative squares actually agree. They do in fact agree, and we then capture that at the type level (i.e. by constructing a chain map) in `mk_hom`. -/ def mk_hom_aux : Π n, Σ' (f : P.X n ⟶ Q.X n) (f' : P.X (n+1) ⟶ Q.X (n+1)), f ≫ Q.d n (n+1) = P.d n (n+1) ≫ f' | 0 := ⟨zero, one, one_zero_comm⟩ | (n+1) := ⟨(mk_hom_aux n).2.1, (succ n (mk_hom_aux n)).1, (succ n (mk_hom_aux n)).2⟩ /-- A constructor for chain maps between `ℕ`-indexed cochain complexes, working by induction on commutative squares. You need to provide the components of the chain map in degrees 0 and 1, show that these form a commutative square, and then give a construction of each component, and the fact that it forms a commutative square with the previous component, using as an inductive hypothesis the data (and commutativity) of the previous two components. -/ def mk_hom : P ⟶ Q := { f := λ n, (mk_hom_aux P Q zero one one_zero_comm succ n).1, comm' := λ n m, begin rintro (rfl : n + 1 = m), exact (mk_hom_aux P Q zero one one_zero_comm succ n).2.2, end } @[simp] lemma mk_hom_f_0 : (mk_hom P Q zero one one_zero_comm succ).f 0 = zero := rfl @[simp] lemma mk_hom_f_1 : (mk_hom P Q zero one one_zero_comm succ).f 1 = one := rfl @[simp] lemma mk_hom_f_succ_succ (n : ℕ) : (mk_hom P Q zero one one_zero_comm succ).f (n+2) = (succ n ⟨(mk_hom P Q zero one one_zero_comm succ).f n, (mk_hom P Q zero one one_zero_comm succ).f (n+1), (mk_hom P Q zero one one_zero_comm succ).comm n (n+1)⟩).1 := begin dsimp [mk_hom, mk_hom_aux], induction n; congr, end end mk_hom end cochain_complex
bcb2dceec88239a8ec87e9ea03fbb526d869027f
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/morphism_property.lean
a690812286cc414f2da1e6e3934b9d1fbce17d45
[ "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
23,548
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 category_theory.limits.shapes.diagonal import category_theory.arrow import category_theory.limits.shapes.comm_sq import category_theory.concrete_category.basic /-! # Properties of morphisms We provide the basic framework for talking about properties of morphisms. The following meta-properties are defined * `respects_iso`: `P` respects isomorphisms if `P f → P (e ≫ f)` and `P f → P (f ≫ e)`, where `e` is an isomorphism. * `stable_under_composition`: `P` is stable under composition if `P f → P g → P (f ≫ g)`. * `stable_under_base_change`: `P` is stable under base change if in all pullback squares, the left map satisfies `P` if the right map satisfies it. * `stable_under_cobase_change`: `P` is stable under cobase change if in all pushout squares, the right map satisfies `P` if the left map satisfies it. -/ universes v u open category_theory category_theory.limits opposite noncomputable theory namespace category_theory variables (C : Type u) [category.{v} C] {D : Type*} [category D] /-- A `morphism_property C` is a class of morphisms between objects in `C`. -/ @[derive complete_lattice] def morphism_property := ∀ ⦃X Y : C⦄ (f : X ⟶ Y), Prop instance : inhabited (morphism_property C) := ⟨⊤⟩ variable {C} namespace morphism_property instance : has_subset (morphism_property C) := ⟨λ P₁ P₂, ∀ ⦃X Y : C⦄ (f : X ⟶ Y) (hf : P₁ f), P₂ f⟩ instance : has_inter (morphism_property C) := ⟨λ P₁ P₂ X Y f, P₁ f ∧ P₂ f⟩ /-- The morphism property in `Cᵒᵖ` associated to a morphism property in `C` -/ @[simp] def op (P : morphism_property C) : morphism_property Cᵒᵖ := λ X Y f, P f.unop /-- The morphism property in `C` associated to a morphism property in `Cᵒᵖ` -/ @[simp] def unop (P : morphism_property Cᵒᵖ) : morphism_property C := λ X Y f, P f.op lemma unop_op (P : morphism_property C) : P.op.unop = P := rfl lemma op_unop (P : morphism_property Cᵒᵖ) : P.unop.op = P := rfl /-- The inverse image of a `morphism_property D` by a functor `C ⥤ D` -/ def inverse_image (P : morphism_property D) (F : C ⥤ D) : morphism_property C := λ X Y f, P (F.map f) /-- A morphism property `respects_iso` if it still holds when composed with an isomorphism -/ def respects_iso (P : morphism_property C) : Prop := (∀ {X Y Z} (e : X ≅ Y) (f : Y ⟶ Z), P f → P (e.hom ≫ f)) ∧ (∀ {X Y Z} (e : Y ≅ Z) (f : X ⟶ Y), P f → P (f ≫ e.hom)) lemma respects_iso.op {P : morphism_property C} (h : respects_iso P) : respects_iso P.op := ⟨λ X Y Z e f hf, h.2 e.unop f.unop hf, λ X Y Z e f hf, h.1 e.unop f.unop hf⟩ lemma respects_iso.unop {P : morphism_property Cᵒᵖ} (h : respects_iso P) : respects_iso P.unop := ⟨λ X Y Z e f hf, h.2 e.op f.op hf, λ X Y Z e f hf, h.1 e.op f.op hf⟩ /-- A morphism property is `stable_under_composition` if the composition of two such morphisms still falls in the class. -/ def stable_under_composition (P : morphism_property C) : Prop := ∀ ⦃X Y Z⦄ (f : X ⟶ Y) (g : Y ⟶ Z), P f → P g → P (f ≫ g) lemma stable_under_composition.op {P : morphism_property C} (h : stable_under_composition P) : stable_under_composition P.op := λ X Y Z f g hf hg, h g.unop f.unop hg hf lemma stable_under_composition.unop {P : morphism_property Cᵒᵖ} (h : stable_under_composition P) : stable_under_composition P.unop := λ X Y Z f g hf hg, h g.op f.op hg hf /-- A morphism property is `stable_under_inverse` if the inverse of a morphism satisfying the property still falls in the class. -/ def stable_under_inverse (P : morphism_property C) : Prop := ∀ ⦃X Y⦄ (e : X ≅ Y), P e.hom → P e.inv lemma stable_under_inverse.op {P : morphism_property C} (h : stable_under_inverse P) : stable_under_inverse P.op := λ X Y e he, h e.unop he lemma stable_under_inverse.unop {P : morphism_property Cᵒᵖ} (h : stable_under_inverse P) : stable_under_inverse P.unop := λ X Y e he, h e.op he /-- A morphism property is `stable_under_base_change` if the base change of such a morphism still falls in the class. -/ def stable_under_base_change (P : morphism_property C) : Prop := ∀ ⦃X Y Y' S : C⦄ ⦃f : X ⟶ S⦄ ⦃g : Y ⟶ S⦄ ⦃f' : Y' ⟶ Y⦄ ⦃g' : Y' ⟶ X⦄ (sq : is_pullback f' g' g f) (hg : P g), P g' /-- A morphism property is `stable_under_cobase_change` if the cobase change of such a morphism still falls in the class. -/ def stable_under_cobase_change (P : morphism_property C) : Prop := ∀ ⦃A A' B B' : C⦄ ⦃f : A ⟶ A'⦄ ⦃g : A ⟶ B⦄ ⦃f' : B ⟶ B'⦄ ⦃g' : A' ⟶ B'⦄ (sq : is_pushout g f f' g') (hf : P f), P f' lemma stable_under_composition.respects_iso {P : morphism_property C} (hP : stable_under_composition P) (hP' : ∀ {X Y} (e : X ≅ Y), P e.hom) : respects_iso P := ⟨λ X Y Z e f hf, hP _ _ (hP' e) hf, λ X Y Z e f hf, hP _ _ hf (hP' e)⟩ lemma respects_iso.cancel_left_is_iso {P : morphism_property C} (hP : respects_iso P) {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) [is_iso f] : P (f ≫ g) ↔ P g := ⟨λ h, by simpa using hP.1 (as_iso f).symm (f ≫ g) h, hP.1 (as_iso f) g⟩ lemma respects_iso.cancel_right_is_iso {P : morphism_property C} (hP : respects_iso P) {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) [is_iso g] : P (f ≫ g) ↔ P f := ⟨λ h, by simpa using hP.2 (as_iso g).symm (f ≫ g) h, hP.2 (as_iso g) f⟩ lemma respects_iso.arrow_iso_iff {P : morphism_property C} (hP : respects_iso P) {f g : arrow C} (e : f ≅ g) : P f.hom ↔ P g.hom := by { rw [← arrow.inv_left_hom_right e.hom, hP.cancel_left_is_iso, hP.cancel_right_is_iso], refl } lemma respects_iso.arrow_mk_iso_iff {P : morphism_property C} (hP : respects_iso P) {W X Y Z : C} {f : W ⟶ X} {g : Y ⟶ Z} (e : arrow.mk f ≅ arrow.mk g) : P f ↔ P g := hP.arrow_iso_iff e lemma respects_iso.of_respects_arrow_iso (P : morphism_property C) (hP : ∀ (f g : arrow C) (e : f ≅ g) (hf : P f.hom), P g.hom) : respects_iso P := begin split, { intros X Y Z e f hf, refine hP (arrow.mk f) (arrow.mk (e.hom ≫ f)) (arrow.iso_mk e.symm (iso.refl _) _) hf, dsimp, simp only [iso.inv_hom_id_assoc, category.comp_id], }, { intros X Y Z e f hf, refine hP (arrow.mk f) (arrow.mk (f ≫ e.hom)) (arrow.iso_mk (iso.refl _) e _) hf, dsimp, simp only [category.id_comp], }, end lemma stable_under_base_change.mk {P : morphism_property C} [has_pullbacks C] (hP₁ : respects_iso P) (hP₂ : ∀ (X Y S : C) (f : X ⟶ S) (g : Y ⟶ S) (hg : P g), P (pullback.fst : pullback f g ⟶ X)) : stable_under_base_change P := λ X Y Y' S f g f' g' sq hg, begin let e := sq.flip.iso_pullback, rw [← hP₁.cancel_left_is_iso e.inv, sq.flip.iso_pullback_inv_fst], exact hP₂ _ _ _ f g hg, end lemma stable_under_base_change.respects_iso {P : morphism_property C} (hP : stable_under_base_change P) : respects_iso P := begin apply respects_iso.of_respects_arrow_iso, intros f g e, exact hP (is_pullback.of_horiz_is_iso (comm_sq.mk e.inv.w)), end lemma stable_under_base_change.fst {P : morphism_property C} (hP : stable_under_base_change P) {X Y S : C} (f : X ⟶ S) (g : Y ⟶ S) [has_pullback f g] (H : P g) : P (pullback.fst : pullback f g ⟶ X) := hP (is_pullback.of_has_pullback f g).flip H lemma stable_under_base_change.snd {P : morphism_property C} (hP : stable_under_base_change P) {X Y S : C} (f : X ⟶ S) (g : Y ⟶ S) [has_pullback f g] (H : P f) : P (pullback.snd : pullback f g ⟶ Y) := hP (is_pullback.of_has_pullback f g) H lemma stable_under_base_change.base_change_obj [has_pullbacks C] {P : morphism_property C} (hP : stable_under_base_change P) {S S' : C} (f : S' ⟶ S) (X : over S) (H : P X.hom) : P ((base_change f).obj X).hom := hP.snd X.hom f H lemma stable_under_base_change.base_change_map [has_pullbacks C] {P : morphism_property C} (hP : stable_under_base_change P) {S S' : C} (f : S' ⟶ S) {X Y : over S} (g : X ⟶ Y) (H : P g.left) : P ((base_change f).map g).left := begin let e := pullback_right_pullback_fst_iso Y.hom f g.left ≪≫ pullback.congr_hom (g.w.trans (category.comp_id _)) rfl, have : e.inv ≫ pullback.snd = ((base_change f).map g).left, { apply pullback.hom_ext; dsimp; simp }, rw [← this, hP.respects_iso.cancel_left_is_iso], exact hP.snd _ _ H, end lemma stable_under_base_change.pullback_map [has_pullbacks C] {P : morphism_property C} (hP : stable_under_base_change P) (hP' : stable_under_composition P) {S X X' Y Y' : C} {f : X ⟶ S} {g : Y ⟶ S} {f' : X' ⟶ S} {g' : Y' ⟶ S} {i₁ : X ⟶ X'} {i₂ : Y ⟶ Y'} (h₁ : P i₁) (h₂ : P i₂) (e₁ : f = i₁ ≫ f') (e₂ : g = i₂ ≫ g') : P (pullback.map f g f' g' i₁ i₂ (𝟙 _) ((category.comp_id _).trans e₁) ((category.comp_id _).trans e₂)) := begin have : pullback.map f g f' g' i₁ i₂ (𝟙 _) ((category.comp_id _).trans e₁) ((category.comp_id _).trans e₂) = ((pullback_symmetry _ _).hom ≫ ((base_change _).map (over.hom_mk _ e₂.symm : over.mk g ⟶ over.mk g')).left) ≫ (pullback_symmetry _ _).hom ≫ ((base_change g').map (over.hom_mk _ e₁.symm : over.mk f ⟶ over.mk f')).left, { apply pullback.hom_ext; dsimp; simp }, rw this, apply hP'; rw hP.respects_iso.cancel_left_is_iso, exacts [hP.base_change_map _ (over.hom_mk _ e₂.symm : over.mk g ⟶ over.mk g') h₂, hP.base_change_map _ (over.hom_mk _ e₁.symm : over.mk f ⟶ over.mk f') h₁], end lemma stable_under_cobase_change.mk {P : morphism_property C} [has_pushouts C] (hP₁ : respects_iso P) (hP₂ : ∀ (A B A' : C) (f : A ⟶ A') (g : A ⟶ B) (hf : P f), P (pushout.inr : B ⟶ pushout f g)) : stable_under_cobase_change P := λ A A' B B' f g f' g' sq hf, begin let e := sq.flip.iso_pushout, rw [← hP₁.cancel_right_is_iso _ e.hom, sq.flip.inr_iso_pushout_hom], exact hP₂ _ _ _ f g hf, end lemma stable_under_cobase_change.respects_iso {P : morphism_property C} (hP : stable_under_cobase_change P) : respects_iso P := respects_iso.of_respects_arrow_iso _ (λ f g e, hP (is_pushout.of_horiz_is_iso (comm_sq.mk e.hom.w))) lemma stable_under_cobase_change.inl {P : morphism_property C} (hP : stable_under_cobase_change P) {A B A' : C} (f : A ⟶ A') (g : A ⟶ B) [has_pushout f g] (H : P g) : P (pushout.inl : A' ⟶ pushout f g) := hP (is_pushout.of_has_pushout f g) H lemma stable_under_cobase_change.inr {P : morphism_property C} (hP : stable_under_cobase_change P) {A B A' : C} (f : A ⟶ A') (g : A ⟶ B) [has_pushout f g] (H : P f) : P (pushout.inr : B ⟶ pushout f g) := hP (is_pushout.of_has_pushout f g).flip H lemma stable_under_cobase_change.op {P : morphism_property C} (hP : stable_under_cobase_change P) : stable_under_base_change P.op := λ X Y Y' S f g f' g' sq hg, hP sq.unop hg lemma stable_under_cobase_change.unop {P : morphism_property Cᵒᵖ} (hP : stable_under_cobase_change P) : stable_under_base_change P.unop := λ X Y Y' S f g f' g' sq hg, hP sq.op hg lemma stable_under_base_change.op {P : morphism_property C} (hP : stable_under_base_change P) : stable_under_cobase_change P.op := λ A A' B B' f g f' g' sq hf, hP sq.unop hf lemma stable_under_base_change.unop {P : morphism_property Cᵒᵖ} (hP : stable_under_base_change P) : stable_under_cobase_change P.unop := λ A A' B B' f g f' g' sq hf, hP sq.op hf /-- If `P : morphism_property C` and `F : C ⥤ D`, then `P.is_inverted_by F` means that all morphisms in `P` are mapped by `F` to isomorphisms in `D`. -/ def is_inverted_by (P : morphism_property C) (F : C ⥤ D) : Prop := ∀ ⦃X Y : C⦄ (f : X ⟶ Y) (hf : P f), is_iso (F.map f) namespace is_inverted_by lemma of_comp {C₁ C₂ C₃ : Type*} [category C₁] [category C₂] [category C₃] (W : morphism_property C₁) (F : C₁ ⥤ C₂) (hF : W.is_inverted_by F) (G : C₂ ⥤ C₃) : W.is_inverted_by (F ⋙ G) := λ X Y f hf, by { haveI := hF f hf, dsimp, apply_instance, } lemma op {W : morphism_property C} {L : C ⥤ D} (h : W.is_inverted_by L) : W.op.is_inverted_by L.op := λ X Y f hf, by { haveI := h f.unop hf, dsimp, apply_instance, } lemma right_op {W : morphism_property C} {L : Cᵒᵖ ⥤ D} (h : W.op.is_inverted_by L) : W.is_inverted_by L.right_op := λ X Y f hf, by { haveI := h f.op hf, dsimp, apply_instance, } lemma left_op {W : morphism_property C} {L : C ⥤ Dᵒᵖ} (h : W.is_inverted_by L) : W.op.is_inverted_by L.left_op := λ X Y f hf, by { haveI := h f.unop hf, dsimp, apply_instance, } lemma unop {W : morphism_property C} {L : Cᵒᵖ ⥤ Dᵒᵖ} (h : W.op.is_inverted_by L) : W.is_inverted_by L.unop := λ X Y f hf, by { haveI := h f.op hf, dsimp, apply_instance, } end is_inverted_by /-- Given `app : Π X, F₁.obj X ⟶ F₂.obj X` where `F₁` and `F₂` are two functors, this is the `morphism_property C` satisfied by the morphisms in `C` with respect to whom `app` is natural. -/ @[simp] def naturality_property {F₁ F₂ : C ⥤ D} (app : Π X, F₁.obj X ⟶ F₂.obj X) : morphism_property C := λ X Y f, F₁.map f ≫ app Y = app X ≫ F₂.map f namespace naturality_property lemma is_stable_under_composition {F₁ F₂ : C ⥤ D} (app : Π X, F₁.obj X ⟶ F₂.obj X) : (naturality_property app).stable_under_composition := λ X Y Z f g hf hg, begin simp only [naturality_property] at ⊢ hf hg, simp only [functor.map_comp, category.assoc, hg], slice_lhs 1 2 { rw hf }, rw category.assoc, end lemma is_stable_under_inverse {F₁ F₂ : C ⥤ D} (app : Π X, F₁.obj X ⟶ F₂.obj X) : (naturality_property app).stable_under_inverse := λ X Y e he, begin simp only [naturality_property] at ⊢ he, rw ← cancel_epi (F₁.map e.hom), slice_rhs 1 2 { rw he }, simp only [category.assoc, ← F₁.map_comp_assoc, ← F₂.map_comp, e.hom_inv_id, functor.map_id, category.id_comp, category.comp_id], end end naturality_property lemma respects_iso.inverse_image {P : morphism_property D} (h : respects_iso P) (F : C ⥤ D) : respects_iso (P.inverse_image F) := begin split, all_goals { intros X Y Z e f hf, dsimp [inverse_image], rw F.map_comp, }, exacts [h.1 (F.map_iso e) (F.map f) hf, h.2 (F.map_iso e) (F.map f) hf], end lemma stable_under_composition.inverse_image {P : morphism_property D} (h : stable_under_composition P) (F : C ⥤ D) : stable_under_composition (P.inverse_image F) := λ X Y Z f g hf hg, by simpa only [← F.map_comp] using h (F.map f) (F.map g) hf hg variable (C) /-- The `morphism_property C` satisfied by isomorphisms in `C`. -/ def isomorphisms : morphism_property C := λ X Y f, is_iso f /-- The `morphism_property C` satisfied by monomorphisms in `C`. -/ def monomorphisms : morphism_property C := λ X Y f, mono f /-- The `morphism_property C` satisfied by epimorphisms in `C`. -/ def epimorphisms : morphism_property C := λ X Y f, epi f section variables {C} {X Y : C} (f : X ⟶ Y) @[simp] lemma isomorphisms.iff : (isomorphisms C) f ↔ is_iso f := by refl @[simp] lemma monomorphisms.iff : (monomorphisms C) f ↔ mono f := by refl @[simp] lemma epimorphisms.iff : (epimorphisms C) f ↔ epi f := by refl lemma isomorphisms.infer_property [hf : is_iso f] : (isomorphisms C) f := hf lemma monomorphisms.infer_property [hf : mono f] : (monomorphisms C) f := hf lemma epimorphisms.infer_property [hf : epi f] : (epimorphisms C) f := hf end lemma respects_iso.monomorphisms : respects_iso (monomorphisms C) := by { split; { intros X Y Z e f, simp only [monomorphisms.iff], introI, apply mono_comp, }, } lemma respects_iso.epimorphisms : respects_iso (epimorphisms C) := by { split; { intros X Y Z e f, simp only [epimorphisms.iff], introI, apply epi_comp, }, } lemma respects_iso.isomorphisms : respects_iso (isomorphisms C) := by { split; { intros X Y Z e f, simp only [isomorphisms.iff], introI, apply_instance, }, } lemma stable_under_composition.isomorphisms : stable_under_composition (isomorphisms C) := λ X Y Z f g hf hg, begin rw isomorphisms.iff at hf hg ⊢, haveI := hf, haveI := hg, apply_instance, end lemma stable_under_composition.monomorphisms : stable_under_composition (monomorphisms C) := λ X Y Z f g hf hg, begin rw monomorphisms.iff at hf hg ⊢, haveI := hf, haveI := hg, apply mono_comp, end lemma stable_under_composition.epimorphisms : stable_under_composition (epimorphisms C) := λ X Y Z f g hf hg, begin rw epimorphisms.iff at hf hg ⊢, haveI := hf, haveI := hg, apply epi_comp, end variable {C} /-- The full subcategory of `C ⥤ D` consisting of functors inverting morphisms in `W` -/ @[derive category, nolint has_nonempty_instance] def functors_inverting (W : morphism_property C) (D : Type*) [category D] := full_subcategory (λ (F : C ⥤ D), W.is_inverted_by F) /-- A constructor for `W.functors_inverting D` -/ def functors_inverting.mk {W : morphism_property C} {D : Type*} [category D] (F : C ⥤ D) (hF : W.is_inverted_by F) : W.functors_inverting D := ⟨F, hF⟩ lemma is_inverted_by.iff_of_iso (W : morphism_property C) {F₁ F₂ : C ⥤ D} (e : F₁ ≅ F₂) : W.is_inverted_by F₁ ↔ W.is_inverted_by F₂ := begin suffices : ∀ (X Y : C) (f : X ⟶ Y), is_iso (F₁.map f) ↔ is_iso (F₂.map f), { split, exact λ h X Y f hf, by { rw ← this, exact h f hf, }, exact λ h X Y f hf, by { rw this, exact h f hf, }, }, intros X Y f, exact (respects_iso.isomorphisms D).arrow_mk_iso_iff (arrow.iso_mk (e.app X) (e.app Y) (by simp)), end section diagonal variables [has_pullbacks C] {P : morphism_property C} /-- For `P : morphism_property C`, `P.diagonal` is a morphism property that holds for `f : X ⟶ Y` whenever `P` holds for `X ⟶ Y xₓ Y`. -/ def diagonal (P : morphism_property C) : morphism_property C := λ X Y f, P (pullback.diagonal f) lemma diagonal_iff {X Y : C} {f : X ⟶ Y} : P.diagonal f ↔ P (pullback.diagonal f) := iff.rfl lemma respects_iso.diagonal (hP : P.respects_iso) : P.diagonal.respects_iso := begin split, { introv H, rwa [diagonal_iff, pullback.diagonal_comp, hP.cancel_left_is_iso, hP.cancel_left_is_iso, ← hP.cancel_right_is_iso _ _, ← pullback.condition, hP.cancel_left_is_iso], apply_instance }, { introv H, delta diagonal, rwa [pullback.diagonal_comp, hP.cancel_right_is_iso] } end lemma stable_under_composition.diagonal (hP : stable_under_composition P) (hP' : respects_iso P) (hP'' : stable_under_base_change P) : P.diagonal.stable_under_composition := begin introv X h₁ h₂, rw [diagonal_iff, pullback.diagonal_comp], apply hP, { assumption }, rw hP'.cancel_left_is_iso, apply hP''.snd, assumption end lemma stable_under_base_change.diagonal (hP : stable_under_base_change P) (hP' : respects_iso P) : P.diagonal.stable_under_base_change := stable_under_base_change.mk hP'.diagonal begin introv h, rw [diagonal_iff, diagonal_pullback_fst, hP'.cancel_left_is_iso, hP'.cancel_right_is_iso], convert hP.base_change_map f _ _; simp; assumption end end diagonal section universally /-- `P.universally` holds for a morphism `f : X ⟶ Y` iff `P` holds for all `X ×[Y] Y' ⟶ Y'`. -/ def universally (P : morphism_property C) : morphism_property C := λ X Y f, ∀ ⦃X' Y' : C⦄ (i₁ : X' ⟶ X) (i₂ : Y' ⟶ Y) (f' : X' ⟶ Y') (h : is_pullback f' i₁ i₂ f), P f' lemma universally_respects_iso (P : morphism_property C) : P.universally.respects_iso := begin constructor, { intros X Y Z e f hf X' Z' i₁ i₂ f' H, have : is_pullback (𝟙 _) (i₁ ≫ e.hom) i₁ e.inv := is_pullback.of_horiz_is_iso ⟨by rw [category.id_comp, category.assoc, e.hom_inv_id, category.comp_id]⟩, replace this := this.paste_horiz H, rw [iso.inv_hom_id_assoc, category.id_comp] at this, exact hf _ _ _ this }, { intros X Y Z e f hf X' Z' i₁ i₂ f' H, have : is_pullback (𝟙 _) i₂ (i₂ ≫ e.inv) e.inv := is_pullback.of_horiz_is_iso ⟨category.id_comp _⟩, replace this := H.paste_horiz this, rw [category.assoc, iso.hom_inv_id, category.comp_id, category.comp_id] at this, exact hf _ _ _ this }, end lemma universally_stable_under_base_change (P : morphism_property C) : P.universally.stable_under_base_change := λ X Y Y' S f g f' g' H h₁ Y'' X'' i₁ i₂ f'' H', h₁ _ _ _ (H'.paste_vert H.flip) lemma stable_under_composition.universally [has_pullbacks C] {P : morphism_property C} (hP : P.stable_under_composition) : P.universally.stable_under_composition := begin intros X Y Z f g hf hg X' Z' i₁ i₂ f' H, have := pullback.lift_fst _ _ (H.w.trans (category.assoc _ _ _).symm), rw ← this at H ⊢, apply hP _ _ _ (hg _ _ _ $ is_pullback.of_has_pullback _ _), exact hf _ _ _ (H.of_right (pullback.lift_snd _ _ _) (is_pullback.of_has_pullback i₂ g)) end lemma universally_le (P : morphism_property C) : P.universally ≤ P := begin intros X Y f hf, exact hf (𝟙 _) (𝟙 _) _ (is_pullback.of_vert_is_iso ⟨by rw [category.comp_id, category.id_comp]⟩) end lemma stable_under_base_change.universally_eq {P : morphism_property C} (hP : P.stable_under_base_change) : P.universally = P := P.universally_le.antisymm $ λ X Y f hf X' Y' i₁ i₂ f' H, hP H.flip hf lemma universally_mono : monotone (universally : morphism_property C → morphism_property C) := λ P₁ P₂ h X Y f h₁ X' Y' i₁ i₂ f' H, h _ _ _ (h₁ _ _ _ H) end universally section bijective variables [concrete_category C] open function local attribute [instance] concrete_category.has_coe_to_fun concrete_category.has_coe_to_sort variable (C) /-- Injectiveness (in a concrete category) as a `morphism_property` -/ protected def injective : morphism_property C := λ X Y f, injective f /-- Surjectiveness (in a concrete category) as a `morphism_property` -/ protected def surjective : morphism_property C := λ X Y f, surjective f /-- Bijectiveness (in a concrete category) as a `morphism_property` -/ protected def bijective : morphism_property C := λ X Y f, bijective f lemma bijective_eq_sup : morphism_property.bijective C = morphism_property.injective C ⊓ morphism_property.surjective C := rfl lemma injective_stable_under_composition : (morphism_property.injective C).stable_under_composition := λ X Y Z f g hf hg, by { delta morphism_property.injective, rw coe_comp, exact hg.comp hf } lemma surjective_stable_under_composition : (morphism_property.surjective C).stable_under_composition := λ X Y Z f g hf hg, by { delta morphism_property.surjective, rw coe_comp, exact hg.comp hf } lemma bijective_stable_under_composition : (morphism_property.bijective C).stable_under_composition := λ X Y Z f g hf hg, by { delta morphism_property.bijective, rw coe_comp, exact hg.comp hf } lemma injective_respects_iso : (morphism_property.injective C).respects_iso := (injective_stable_under_composition C).respects_iso (λ X Y e, ((forget C).map_iso e).to_equiv.injective) lemma surjective_respects_iso : (morphism_property.surjective C).respects_iso := (surjective_stable_under_composition C).respects_iso (λ X Y e, ((forget C).map_iso e).to_equiv.surjective) lemma bijective_respects_iso : (morphism_property.bijective C).respects_iso := (bijective_stable_under_composition C).respects_iso (λ X Y e, ((forget C).map_iso e).to_equiv.bijective) end bijective end morphism_property end category_theory
18b588924c7df01f98323779b6b45be83f36e01c
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/analysis/calculus/formal_multilinear_series.lean
8ceba969eece505e1c9092289e42322af5a7f472
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
7,273
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Sébastien Gouëzel -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.analysis.normed_space.multilinear import Mathlib.ring_theory.power_series.basic import Mathlib.PostPort universes u_1 u_2 u_3 u_4 u_5 namespace Mathlib /-! # Formal multilinear series In this file we define `formal_multilinear_series 𝕜 E F` to be a family of `n`-multilinear maps for all `n`, designed to model the sequence of derivatives of a function. In other files we use this notion to define `C^n` functions (called `times_cont_diff` in `mathlib`) and analytic functions. ## Notations We use the notation `E [×n]→L[𝕜] F` for the space of continuous multilinear maps on `E^n` with values in `F`. This is the space in which the `n`-th derivative of a function from `E` to `F` lives. ## Tags multilinear, formal series -/ /-- A formal multilinear series over a field `𝕜`, from `E` to `F`, is given by a family of multilinear maps from `E^n` to `F` for all `n`. -/ def formal_multilinear_series (𝕜 : Type u_1) [nondiscrete_normed_field 𝕜] (E : Type u_2) [normed_group E] [normed_space 𝕜 E] (F : Type u_3) [normed_group F] [normed_space 𝕜 F] := (n : ℕ) → continuous_multilinear_map 𝕜 (fun (i : fin n) => E) F protected instance formal_multilinear_series.inhabited {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] : Inhabited (formal_multilinear_series 𝕜 E F) := { default := 0 } /- `derive` is not able to find the module structure, probably because Lean is confused by the dependent types. We register it explicitly. -/ protected instance formal_multilinear_series.module {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] : module 𝕜 (formal_multilinear_series 𝕜 E F) := let _inst : (n : ℕ) → module 𝕜 (continuous_multilinear_map 𝕜 (fun (i : fin n) => E) F) := fun (n : ℕ) => continuous_multilinear_map.semimodule; pi.semimodule ℕ (fun (n : ℕ) => continuous_multilinear_map 𝕜 (fun (i : fin n) => E) F) 𝕜 namespace formal_multilinear_series /-- Forgetting the zeroth term in a formal multilinear series, and interpreting the following terms as multilinear maps into `E →L[𝕜] F`. If `p` corresponds to the Taylor series of a function, then `p.shift` is the Taylor series of the derivative of the function. -/ def shift {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] (p : formal_multilinear_series 𝕜 E F) : formal_multilinear_series 𝕜 E (continuous_linear_map 𝕜 E F) := fun (n : ℕ) => continuous_multilinear_map.curry_right (p (Nat.succ n)) /-- Adding a zeroth term to a formal multilinear series taking values in `E →L[𝕜] F`. This corresponds to starting from a Taylor series for the derivative of a function, and building a Taylor series for the function itself. -/ def unshift {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] (q : formal_multilinear_series 𝕜 E (continuous_linear_map 𝕜 E F)) (z : F) : formal_multilinear_series 𝕜 E F := sorry /-- Killing the zeroth coefficient in a formal multilinear series -/ def remove_zero {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] (p : formal_multilinear_series 𝕜 E F) : formal_multilinear_series 𝕜 E F := sorry @[simp] theorem remove_zero_coeff_zero {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] (p : formal_multilinear_series 𝕜 E F) : remove_zero p 0 = 0 := rfl @[simp] theorem remove_zero_coeff_succ {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] (p : formal_multilinear_series 𝕜 E F) (n : ℕ) : remove_zero p (n + 1) = p (n + 1) := rfl theorem remove_zero_of_pos {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] (p : formal_multilinear_series 𝕜 E F) {n : ℕ} (h : 0 < n) : remove_zero p n = p n := eq.mpr (id (Eq._oldrec (Eq.refl (remove_zero p n = p n)) (Eq.symm (nat.succ_pred_eq_of_pos h)))) (Eq.refl (remove_zero p (Nat.succ (Nat.pred n)))) /-- Convenience congruence lemma stating in a dependent setting that, if the arguments to a formal multilinear series are equal, then the values are also equal. -/ theorem congr {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] (p : formal_multilinear_series 𝕜 E F) {m : ℕ} {n : ℕ} {v : fin m → E} {w : fin n → E} (h1 : m = n) (h2 : ∀ (i : ℕ) (him : i < m) (hin : i < n), v { val := i, property := him } = w { val := i, property := hin }) : coe_fn (p m) v = coe_fn (p n) w := sorry /-- Composing each term `pₙ` in a formal multilinear series with `(u, ..., u)` where `u` is a fixed continuous linear map, gives a new formal multilinear series `p.comp_continuous_linear_map u`. -/ def comp_continuous_linear_map {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] {G : Type u_4} [normed_group G] [normed_space 𝕜 G] (p : formal_multilinear_series 𝕜 F G) (u : continuous_linear_map 𝕜 E F) : formal_multilinear_series 𝕜 E G := fun (n : ℕ) => continuous_multilinear_map.comp_continuous_linear_map (p n) fun (i : fin n) => u @[simp] theorem comp_continuous_linear_map_apply {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] {G : Type u_4} [normed_group G] [normed_space 𝕜 G] (p : formal_multilinear_series 𝕜 F G) (u : continuous_linear_map 𝕜 E F) (n : ℕ) (v : fin n → E) : coe_fn (comp_continuous_linear_map p u n) v = coe_fn (p n) (⇑u ∘ v) := rfl /-- Reinterpret a formal `𝕜'`-multilinear series as a formal `𝕜`-multilinear series, where `𝕜'` is a normed algebra over `𝕜`. -/ @[simp] protected def restrict_scalars (𝕜 : Type u_1) [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] {𝕜' : Type u_5} [nondiscrete_normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] [normed_space 𝕜' E] [is_scalar_tower 𝕜 𝕜' E] [normed_space 𝕜' F] [is_scalar_tower 𝕜 𝕜' F] (p : formal_multilinear_series 𝕜' E F) : formal_multilinear_series 𝕜 E F := fun (n : ℕ) => continuous_multilinear_map.restrict_scalars 𝕜 (p n)
69f4657cf8df9b44ad6c9eae948f1f7824b0f2e4
2f4707593665f4eac651cd5e5b39ea8eabafe0d6
/src/pequiv.lean
59df4fb2dade80761a594eb57b32732bfcc7e159
[]
no_license
PatrickMassot/lean-differential-topology
941d2ac639b2c8bcfcbad85fe5ff0a4676d159e9
5b020daa5f935140c53408748a9f11ba02e7bf42
refs/heads/master
1,543,081,959,510
1,536,089,170,000
1,536,089,170,000
112,875,905
12
5
null
1,520,841,685,000
1,512,247,905,000
Lean
UTF-8
Lean
false
false
4,273
lean
import logic.function data.set.function import tactic.interactive import tactic.easy meta def unfold_comp : tactic unit := `[repeat { rw comp_apply }] open function set universes u v w variables {α : Type*} {β : Type*} {γ : Type*} /-- `pequiv α β` is the type of functions from `α → β` which induce a bijection from some `domain ⊆ α` to some `range ⊆ β`. -/ structure pequiv (α : Sort*) (β : Sort*) := (domain : set α) (range : set β) (to_fun : α → β) (inv_fun : β → α) (maps_to : set.maps_to to_fun domain range) (maps_inv : set.maps_to inv_fun range domain) (inv_inv : inv_on inv_fun to_fun domain range) namespace pequiv instance : has_coe_to_fun (pequiv α β) := ⟨_, to_fun⟩ lemma inv_inv' (f : pequiv α β) : inv_on f f.inv_fun f.range f.domain := ⟨f.inv_inv.right, f.inv_inv.left⟩ def symm (f : pequiv α β) : pequiv β α := ⟨f.range, f.domain, f.inv_fun, f.to_fun, f.maps_inv, f.maps_to, inv_inv' f⟩ local notation f`⁻¹` := f.symm lemma inv_to {f : pequiv α β} {a : α} (H : a ∈ f.domain) : f.inv_fun (f.to_fun a) = a := f.inv_inv.1 _ H lemma to_inv {f : pequiv α β} {b : β} (H : b ∈ f.range) : f.to_fun (f.inv_fun b) = b := f.inv_inv'.1 b H lemma domain_to_range {f : pequiv α β} {x : α} (h : x ∈ f.domain) : f x ∈ f.range := f.maps_to h def comp (g : pequiv β γ) (f : pequiv α β) : pequiv α γ := begin refine_struct { domain := f.domain ∩ f.to_fun ⁻¹' (f.range ∩ g.domain), range := g.to_fun '' (f.range ∩ g.domain), to_fun := g.to_fun ∘ f.to_fun, inv_fun := f.inv_fun ∘ g.inv_fun, ..}, { intros a _, existsi f a, easy }, { rintro c ⟨b, ⟨⟨h, h'⟩, h''⟩⟩, rw mem_preimage_eq, split, { unfold_comp, rw [←h'', inv_to], exact f.maps_inv h, assumption }, { unfold_comp, split ; { rw to_inv ; rw [←h'', inv_to]; assumption }}}, { split, { rintro a ⟨a_in_f, f_a_in⟩, unfold_comp, repeat { rwa inv_to }, easy }, { rintro c ⟨b, ⟨⟨b_in_r_f, b_in_d_g⟩, g_b⟩⟩, unfold_comp, repeat { rwa to_inv }, exact g_b ▸ domain_to_range b_in_d_g, rwa [←g_b, inv_to], assumption }} end local infix `∘` := comp @[simp] lemma comp_domain (g : pequiv β γ) (f : pequiv α β) : (g ∘ f).domain = f.domain ∩ f.to_fun ⁻¹' (f.range ∩ g.domain) := rfl @[simp] lemma inv_image_range_iff (f : pequiv α β)(x : α) : x ∈ f.inv_fun '' f.range ↔ x ∈ f.domain := begin split, { rintro ⟨y, ⟨y_in, inv_y⟩⟩, have := f.maps_inv y_in, rwa [mem_preimage_eq, inv_y] at this }, { intro x_in, have := f.maps_to x_in, rw [mem_preimage_eq] at this, existsi f x, split, assumption, unfold_coes, rwa inv_to }, end def id (a : set α) : pequiv α α := begin refine_struct { domain := a, range := a, to_fun := id, inv_fun := id, ..} ; try {split} ; intros x h ; simp * end @[simp] lemma id_domain (a : set α) : (id a).domain = a := rfl @[simp] lemma id_range (a : set α) : (id a).range = a := rfl @[extensionality] lemma ext {f : pequiv α β} {g : pequiv α β} (Hdom : f.domain = g.domain) (Hrg : f.range = g.range) (Hto : f.to_fun = g.to_fun) (Hinv : f.inv_fun = g.inv_fun) : f = g := begin cases f, cases g, congr ; cc end lemma symm_symm (f : pequiv α β) : f.symm.symm = f := by ext ; refl @[simp] lemma symm_self_val {f : pequiv α β} {x : α} (h :x ∈ f.domain) : (f.symm ∘ f) x = x := begin change f.inv_fun (f.to_fun x) = x, rwa inv_to end @[simp] lemma self_symm_val {f : pequiv α β} {x : β} (h :x ∈ f.range) : (f ∘ f.symm) x = x := begin change f.to_fun (f.inv_fun x) = x, rwa to_inv end lemma image_eq_preimage (f : pequiv α β) (U : set α) : f '' (U ∩ f.domain) = f.inv_fun ⁻¹' (U ∩ f.domain) ∩ f.range := begin ext x, split, { rintro ⟨y, y_in, f_y⟩, split ; rw ←f_y, { rw mem_preimage_eq, unfold_coes, rwa inv_to, easy }, { apply domain_to_range, easy } }, { rintro ⟨x_in, x_in'⟩, rw mem_preimage_eq at x_in, existsi f.inv_fun x, unfold_coes, rw to_inv, easy }, end end pequiv
6d9aa50a879a473b7d3899fba6cc90a36457b5ed
9dc8cecdf3c4634764a18254e94d43da07142918
/src/linear_algebra/affine_space/finite_dimensional.lean
7c181394b7b5edd579f99b6d7f35800030d721cb
[ "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
20,247
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers -/ import linear_algebra.affine_space.independent import linear_algebra.finite_dimensional /-! # Finite-dimensional subspaces of affine spaces. This file provides a few results relating to finite-dimensional subspaces of affine spaces. ## Main definitions * `collinear` defines collinear sets of points as those that span a subspace of dimension at most 1. -/ noncomputable theory open_locale big_operators classical affine section affine_space' variables (k : Type*) {V : Type*} {P : Type*} variables {ι : Type*} include V open affine_subspace finite_dimensional module variables [division_ring k] [add_comm_group V] [module k V] [affine_space V P] /-- The `vector_span` of a finite set is finite-dimensional. -/ lemma finite_dimensional_vector_span_of_finite {s : set P} (h : set.finite s) : finite_dimensional k (vector_span k s) := span_of_finite k $ h.vsub h /-- The `vector_span` of a family indexed by a `fintype` is finite-dimensional. -/ instance finite_dimensional_vector_span_range [_root_.finite ι] (p : ι → P) : finite_dimensional k (vector_span k (set.range p)) := finite_dimensional_vector_span_of_finite k (set.finite_range _) /-- The `vector_span` of a subset of a family indexed by a `fintype` is finite-dimensional. -/ instance finite_dimensional_vector_span_image_of_finite [_root_.finite ι] (p : ι → P) (s : set ι) : finite_dimensional k (vector_span k (p '' s)) := finite_dimensional_vector_span_of_finite k (set.to_finite _) /-- The direction of the affine span of a finite set is finite-dimensional. -/ lemma finite_dimensional_direction_affine_span_of_finite {s : set P} (h : set.finite s) : finite_dimensional k (affine_span k s).direction := (direction_affine_span k s).symm ▸ finite_dimensional_vector_span_of_finite k h /-- The direction of the affine span of a family indexed by a `fintype` is finite-dimensional. -/ instance finite_dimensional_direction_affine_span_range [_root_.finite ι] (p : ι → P) : finite_dimensional k (affine_span k (set.range p)).direction := finite_dimensional_direction_affine_span_of_finite k (set.finite_range _) /-- The direction of the affine span of a subset of a family indexed by a `fintype` is finite-dimensional. -/ instance finite_dimensional_direction_affine_span_image_of_finite [_root_.finite ι] (p : ι → P) (s : set ι) : finite_dimensional k (affine_span k (p '' s)).direction := finite_dimensional_direction_affine_span_of_finite k (set.to_finite _) /-- An affine-independent family of points in a finite-dimensional affine space is finite. -/ noncomputable def fintype_of_fin_dim_affine_independent [finite_dimensional k V] {p : ι → P} (hi : affine_independent k p) : fintype ι := if hι : is_empty ι then (@fintype.of_is_empty _ hι) else begin let q := (not_is_empty_iff.mp hι).some, rw affine_independent_iff_linear_independent_vsub k p q at hi, letI : is_noetherian k V := is_noetherian.iff_fg.2 infer_instance, exact fintype_of_fintype_ne _ (@fintype.of_finite _ hi.finite_of_is_noetherian), end /-- An affine-independent subset of a finite-dimensional affine space is finite. -/ lemma finite_of_fin_dim_affine_independent [finite_dimensional k V] {s : set P} (hi : affine_independent k (coe : s → P)) : s.finite := ⟨fintype_of_fin_dim_affine_independent k hi⟩ variables {k} /-- The `vector_span` of a finite subset of an affinely independent family has dimension one less than its cardinality. -/ lemma affine_independent.finrank_vector_span_image_finset {p : ι → P} (hi : affine_independent k p) {s : finset ι} {n : ℕ} (hc : finset.card s = n + 1) : finrank k (vector_span k (s.image p : set P)) = n := begin have hi' := hi.range.mono (set.image_subset_range p ↑s), have hc' : (s.image p).card = n + 1, { rwa s.card_image_of_injective hi.injective }, have hn : (s.image p).nonempty, { simp [hc', ←finset.card_pos] }, rcases hn with ⟨p₁, hp₁⟩, have hp₁' : p₁ ∈ p '' s := by simpa using hp₁, rw [affine_independent_set_iff_linear_independent_vsub k hp₁', ← finset.coe_singleton, ← finset.coe_image, ← finset.coe_sdiff, finset.sdiff_singleton_eq_erase, ← finset.coe_image] at hi', have hc : (finset.image (λ (p : P), p -ᵥ p₁) ((finset.image p s).erase p₁)).card = n, { rw [finset.card_image_of_injective _ (vsub_left_injective _), finset.card_erase_of_mem hp₁], exact nat.pred_eq_of_eq_succ hc' }, rwa [vector_span_eq_span_vsub_finset_right_ne k hp₁, finrank_span_finset_eq_card, hc] end /-- The `vector_span` of a finite affinely independent family has dimension one less than its cardinality. -/ lemma affine_independent.finrank_vector_span [fintype ι] {p : ι → P} (hi : affine_independent k p) {n : ℕ} (hc : fintype.card ι = n + 1) : finrank k (vector_span k (set.range p)) = n := begin rw ← finset.card_univ at hc, rw [← set.image_univ, ← finset.coe_univ, ← finset.coe_image], exact hi.finrank_vector_span_image_finset hc end /-- The `vector_span` of a finite affinely independent family whose cardinality is one more than that of the finite-dimensional space is `⊤`. -/ lemma affine_independent.vector_span_eq_top_of_card_eq_finrank_add_one [finite_dimensional k V] [fintype ι] {p : ι → P} (hi : affine_independent k p) (hc : fintype.card ι = finrank k V + 1) : vector_span k (set.range p) = ⊤ := eq_top_of_finrank_eq $ hi.finrank_vector_span hc variables (k) /-- The `vector_span` of `n + 1` points in an indexed family has dimension at most `n`. -/ lemma finrank_vector_span_image_finset_le (p : ι → P) (s : finset ι) {n : ℕ} (hc : finset.card s = n + 1) : finrank k (vector_span k (s.image p : set P)) ≤ n := begin have hn : (s.image p).nonempty, { rw [finset.nonempty.image_iff, ← finset.card_pos, hc], apply nat.succ_pos }, rcases hn with ⟨p₁, hp₁⟩, rw [vector_span_eq_span_vsub_finset_right_ne k hp₁], refine le_trans (finrank_span_finset_le_card (((s.image p).erase p₁).image (λ p, p -ᵥ p₁))) _, rw [finset.card_image_of_injective _ (vsub_left_injective p₁), finset.card_erase_of_mem hp₁, tsub_le_iff_right, ← hc], apply finset.card_image_le end /-- The `vector_span` of an indexed family of `n + 1` points has dimension at most `n`. -/ lemma finrank_vector_span_range_le [fintype ι] (p : ι → P) {n : ℕ} (hc : fintype.card ι = n + 1) : finrank k (vector_span k (set.range p)) ≤ n := begin rw [←set.image_univ, ←finset.coe_univ, ← finset.coe_image], rw ←finset.card_univ at hc, exact finrank_vector_span_image_finset_le _ _ _ hc end /-- `n + 1` points are affinely independent if and only if their `vector_span` has dimension `n`. -/ lemma affine_independent_iff_finrank_vector_span_eq [fintype ι] (p : ι → P) {n : ℕ} (hc : fintype.card ι = n + 1) : affine_independent k p ↔ finrank k (vector_span k (set.range p)) = n := begin have hn : nonempty ι, by simp [←fintype.card_pos_iff, hc], cases hn with i₁, rw [affine_independent_iff_linear_independent_vsub _ _ i₁, linear_independent_iff_card_eq_finrank_span, eq_comm, vector_span_range_eq_span_range_vsub_right_ne k p i₁], congr', rw ←finset.card_univ at hc, rw fintype.subtype_card, simp [finset.filter_ne', finset.card_erase_of_mem, hc] end /-- `n + 1` points are affinely independent if and only if their `vector_span` has dimension at least `n`. -/ lemma affine_independent_iff_le_finrank_vector_span [fintype ι] (p : ι → P) {n : ℕ} (hc : fintype.card ι = n + 1) : affine_independent k p ↔ n ≤ finrank k (vector_span k (set.range p)) := begin rw affine_independent_iff_finrank_vector_span_eq k p hc, split, { rintro rfl, refl }, { exact λ hle, le_antisymm (finrank_vector_span_range_le k p hc) hle } end /-- `n + 2` points are affinely independent if and only if their `vector_span` does not have dimension at most `n`. -/ lemma affine_independent_iff_not_finrank_vector_span_le [fintype ι] (p : ι → P) {n : ℕ} (hc : fintype.card ι = n + 2) : affine_independent k p ↔ ¬ finrank k (vector_span k (set.range p)) ≤ n := by rw [affine_independent_iff_le_finrank_vector_span k p hc, ←nat.lt_iff_add_one_le, lt_iff_not_ge] /-- `n + 2` points have a `vector_span` with dimension at most `n` if and only if they are not affinely independent. -/ lemma finrank_vector_span_le_iff_not_affine_independent [fintype ι] (p : ι → P) {n : ℕ} (hc : fintype.card ι = n + 2) : finrank k (vector_span k (set.range p)) ≤ n ↔ ¬ affine_independent k p := (not_iff_comm.1 (affine_independent_iff_not_finrank_vector_span_le k p hc).symm).symm variables {k} /-- If the `vector_span` of a finite subset of an affinely independent family lies in a submodule with dimension one less than its cardinality, it equals that submodule. -/ lemma affine_independent.vector_span_image_finset_eq_of_le_of_card_eq_finrank_add_one {p : ι → P} (hi : affine_independent k p) {s : finset ι} {sm : submodule k V} [finite_dimensional k sm] (hle : vector_span k (s.image p : set P) ≤ sm) (hc : finset.card s = finrank k sm + 1) : vector_span k (s.image p : set P) = sm := eq_of_le_of_finrank_eq hle $ hi.finrank_vector_span_image_finset hc /-- If the `vector_span` of a finite affinely independent family lies in a submodule with dimension one less than its cardinality, it equals that submodule. -/ lemma affine_independent.vector_span_eq_of_le_of_card_eq_finrank_add_one [fintype ι] {p : ι → P} (hi : affine_independent k p) {sm : submodule k V} [finite_dimensional k sm] (hle : vector_span k (set.range p) ≤ sm) (hc : fintype.card ι = finrank k sm + 1) : vector_span k (set.range p) = sm := eq_of_le_of_finrank_eq hle $ hi.finrank_vector_span hc /-- If the `affine_span` of a finite subset of an affinely independent family lies in an affine subspace whose direction has dimension one less than its cardinality, it equals that subspace. -/ lemma affine_independent.affine_span_image_finset_eq_of_le_of_card_eq_finrank_add_one {p : ι → P} (hi : affine_independent k p) {s : finset ι} {sp : affine_subspace k P} [finite_dimensional k sp.direction] (hle : affine_span k (s.image p : set P) ≤ sp) (hc : finset.card s = finrank k sp.direction + 1) : affine_span k (s.image p : set P) = sp := begin have hn : (s.image p).nonempty, { rw [finset.nonempty.image_iff, ← finset.card_pos, hc], apply nat.succ_pos }, refine eq_of_direction_eq_of_nonempty_of_le _ ((affine_span_nonempty k _).2 hn) hle, have hd := direction_le hle, rw direction_affine_span at ⊢ hd, exact hi.vector_span_image_finset_eq_of_le_of_card_eq_finrank_add_one hd hc end /-- If the `affine_span` of a finite affinely independent family lies in an affine subspace whose direction has dimension one less than its cardinality, it equals that subspace. -/ lemma affine_independent.affine_span_eq_of_le_of_card_eq_finrank_add_one [fintype ι] {p : ι → P} (hi : affine_independent k p) {sp : affine_subspace k P} [finite_dimensional k sp.direction] (hle : affine_span k (set.range p) ≤ sp) (hc : fintype.card ι = finrank k sp.direction + 1) : affine_span k (set.range p) = sp := begin rw ←finset.card_univ at hc, rw [←set.image_univ, ←finset.coe_univ, ← finset.coe_image] at ⊢ hle, exact hi.affine_span_image_finset_eq_of_le_of_card_eq_finrank_add_one hle hc end /-- The `affine_span` of a finite affinely independent family is `⊤` iff the family's cardinality is one more than that of the finite-dimensional space. -/ lemma affine_independent.affine_span_eq_top_iff_card_eq_finrank_add_one [finite_dimensional k V] [fintype ι] {p : ι → P} (hi : affine_independent k p) : affine_span k (set.range p) = ⊤ ↔ fintype.card ι = finrank k V + 1 := begin split, { intros h_tot, let n := fintype.card ι - 1, have hn : fintype.card ι = n + 1, { exact (nat.succ_pred_eq_of_pos (card_pos_of_affine_span_eq_top k V P h_tot)).symm, }, rw [hn, ← finrank_top, ← (vector_span_eq_top_of_affine_span_eq_top k V P) h_tot, ← hi.finrank_vector_span hn], }, { intros hc, rw [← finrank_top, ← direction_top k V P] at hc, exact hi.affine_span_eq_of_le_of_card_eq_finrank_add_one le_top hc, }, end /-- The `vector_span` of adding a point to a finite-dimensional subspace is finite-dimensional. -/ instance finite_dimensional_vector_span_insert (s : affine_subspace k P) [finite_dimensional k s.direction] (p : P) : finite_dimensional k (vector_span k (insert p (s : set P))) := begin rw [←direction_affine_span, ←affine_span_insert_affine_span], rcases (s : set P).eq_empty_or_nonempty with hs | ⟨p₀, hp₀⟩, { rw coe_eq_bot_iff at hs, rw [hs, bot_coe, span_empty, bot_coe, direction_affine_span], convert finite_dimensional_bot _ _; simp }, { rw [affine_span_coe, direction_affine_span_insert hp₀], apply_instance } end /-- The direction of the affine span of adding a point to a finite-dimensional subspace is finite-dimensional. -/ instance finite_dimensional_direction_affine_span_insert (s : affine_subspace k P) [finite_dimensional k s.direction] (p : P) : finite_dimensional k (affine_span k (insert p (s : set P))).direction := (direction_affine_span k (insert p (s : set P))).symm ▸ finite_dimensional_vector_span_insert s p variables (k) /-- The `vector_span` of adding a point to a set with a finite-dimensional `vector_span` is finite-dimensional. -/ instance finite_dimensional_vector_span_insert_set (s : set P) [finite_dimensional k (vector_span k s)] (p : P) : finite_dimensional k (vector_span k (insert p s)) := begin haveI : finite_dimensional k (affine_span k s).direction := (direction_affine_span k s).symm ▸ infer_instance, rw [←direction_affine_span, ←affine_span_insert_affine_span, direction_affine_span], exact finite_dimensional_vector_span_insert (affine_span k s) p end /-- A set of points is collinear if their `vector_span` has dimension at most `1`. -/ def collinear (s : set P) : Prop := module.rank k (vector_span k s) ≤ 1 /-- The definition of `collinear`. -/ lemma collinear_iff_dim_le_one (s : set P) : collinear k s ↔ module.rank k (vector_span k s) ≤ 1 := iff.rfl /-- A set of points, whose `vector_span` is finite-dimensional, is collinear if and only if their `vector_span` has dimension at most `1`. -/ lemma collinear_iff_finrank_le_one (s : set P) [finite_dimensional k (vector_span k s)] : collinear k s ↔ finrank k (vector_span k s) ≤ 1 := begin have h := collinear_iff_dim_le_one k s, rw ←finrank_eq_dim at h, exact_mod_cast h end variables (P) /-- The empty set is collinear. -/ lemma collinear_empty : collinear k (∅ : set P) := begin rw [collinear_iff_dim_le_one, vector_span_empty], simp end variables {P} /-- A single point is collinear. -/ lemma collinear_singleton (p : P) : collinear k ({p} : set P) := begin rw [collinear_iff_dim_le_one, vector_span_singleton], simp end /-- Given a point `p₀` in a set of points, that set is collinear if and only if the points can all be expressed as multiples of the same vector, added to `p₀`. -/ lemma collinear_iff_of_mem {s : set P} {p₀ : P} (h : p₀ ∈ s) : collinear k s ↔ ∃ v : V, ∀ p ∈ s, ∃ r : k, p = r • v +ᵥ p₀ := begin simp_rw [collinear_iff_dim_le_one, dim_submodule_le_one_iff', submodule.le_span_singleton_iff], split, { rintro ⟨v₀, hv⟩, use v₀, intros p hp, obtain ⟨r, hr⟩ := hv (p -ᵥ p₀) (vsub_mem_vector_span k hp h), use r, rw eq_vadd_iff_vsub_eq, exact hr.symm }, { rintro ⟨v, hp₀v⟩, use v, intros w hw, have hs : vector_span k s ≤ k ∙ v, { rw [vector_span_eq_span_vsub_set_right k h, submodule.span_le, set.subset_def], intros x hx, rw [set_like.mem_coe, submodule.mem_span_singleton], rw set.mem_image at hx, rcases hx with ⟨p, hp, rfl⟩, rcases hp₀v p hp with ⟨r, rfl⟩, use r, simp }, have hw' := set_like.le_def.1 hs hw, rwa submodule.mem_span_singleton at hw' } end /-- A set of points is collinear if and only if they can all be expressed as multiples of the same vector, added to the same base point. -/ lemma collinear_iff_exists_forall_eq_smul_vadd (s : set P) : collinear k s ↔ ∃ (p₀ : P) (v : V), ∀ p ∈ s, ∃ r : k, p = r • v +ᵥ p₀ := begin rcases set.eq_empty_or_nonempty s with rfl | ⟨⟨p₁, hp₁⟩⟩, { simp [collinear_empty] }, { rw collinear_iff_of_mem k hp₁, split, { exact λ h, ⟨p₁, h⟩ }, { rintros ⟨p, v, hv⟩, use v, intros p₂ hp₂, rcases hv p₂ hp₂ with ⟨r, rfl⟩, rcases hv p₁ hp₁ with ⟨r₁, rfl⟩, use r - r₁, simp [vadd_vadd, ←add_smul] } } end /-- Two points are collinear. -/ lemma collinear_pair (p₁ p₂ : P) : collinear k ({p₁, p₂} : set P) := begin rw collinear_iff_exists_forall_eq_smul_vadd, use [p₁, p₂ -ᵥ p₁], intros p hp, rw [set.mem_insert_iff, set.mem_singleton_iff] at hp, cases hp, { use 0, simp [hp] }, { use 1, simp [hp] } end /-- Three points are affinely independent if and only if they are not collinear. -/ lemma affine_independent_iff_not_collinear (p : fin 3 → P) : affine_independent k p ↔ ¬ collinear k (set.range p) := by rw [collinear_iff_finrank_le_one, affine_independent_iff_not_finrank_vector_span_le k p (fintype.card_fin 3)] /-- Three points are collinear if and only if they are not affinely independent. -/ lemma collinear_iff_not_affine_independent (p : fin 3 → P) : collinear k (set.range p) ↔ ¬ affine_independent k p := by rw [collinear_iff_finrank_le_one, finrank_vector_span_le_iff_not_affine_independent k p (fintype.card_fin 3)] end affine_space' section field variables {k : Type*} {V : Type*} {P : Type*} include V open affine_subspace finite_dimensional module variables [field k] [add_comm_group V] [module k V] [affine_space V P] /-- Adding a point to a finite-dimensional subspace increases the dimension by at most one. -/ lemma finrank_vector_span_insert_le (s : affine_subspace k P) (p : P) : finrank k (vector_span k (insert p (s : set P))) ≤ finrank k s.direction + 1 := begin by_cases hf : finite_dimensional k s.direction, swap, { have hf' : ¬finite_dimensional k (vector_span k (insert p (s : set P))), { intro h, have h' : s.direction ≤ vector_span k (insert p (s : set P)), { conv_lhs { rw [←affine_span_coe s, direction_affine_span] }, exact vector_span_mono k (set.subset_insert _ _) }, exactI hf (submodule.finite_dimensional_of_le h') }, rw [finrank_of_infinite_dimensional hf, finrank_of_infinite_dimensional hf', zero_add], exact zero_le_one }, haveI := hf, rw [←direction_affine_span, ←affine_span_insert_affine_span], rcases (s : set P).eq_empty_or_nonempty with hs | ⟨p₀, hp₀⟩, { rw coe_eq_bot_iff at hs, rw [hs, bot_coe, span_empty, bot_coe, direction_affine_span, direction_bot, finrank_bot, zero_add], convert zero_le_one' ℕ, rw ←finrank_bot k V, convert rfl; simp }, { rw [affine_span_coe, direction_affine_span_insert hp₀, add_comm], refine (submodule.dim_add_le_dim_add_dim _ _).trans (add_le_add_right _ _), refine finrank_le_one ⟨p -ᵥ p₀, submodule.mem_span_singleton_self _⟩ (λ v, _), have h := v.property, rw submodule.mem_span_singleton at h, rcases h with ⟨c, hc⟩, refine ⟨c, _⟩, ext, exact hc } end variables (k) /-- Adding a point to a set with a finite-dimensional span increases the dimension by at most one. -/ lemma finrank_vector_span_insert_le_set (s : set P) (p : P) : finrank k (vector_span k (insert p s)) ≤ finrank k (vector_span k s) + 1 := begin rw [←direction_affine_span, ←affine_span_insert_affine_span, direction_affine_span], refine (finrank_vector_span_insert_le _ _).trans (add_le_add_right _ _), rw direction_affine_span end end field
8a6800e22000a10ee8c994a966a21b11a1106860
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/dynamics/circle/rotation_number/translation_number.lean
7bdd98ca4f712cc8cfab6c2e7082404d0f2655e0
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
39,648
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 algebra.iterate_hom import analysis.specific_limits import topology.algebra.ordered.monotone_continuity import order.iterate import order.semiconj_Sup /-! # Translation number of a monotone real map that commutes with `x ↦ x + 1` Let `f : ℝ → ℝ` be a monotone map such that `f (x + 1) = f x + 1` for all `x`. Then the limit $$ \tau(f)=\lim_{n\to\infty}{f^n(x)-x}{n} $$ exists and does not depend on `x`. This number is called the *translation number* of `f`. Different authors use different notation for this number: `τ`, `ρ`, `rot`, etc In this file we define a structure `circle_deg1_lift` for bundled maps with these properties, define translation number of `f : circle_deg1_lift`, prove some estimates relating `f^n(x)-x` to `τ(f)`. In case of a continuous map `f` we also prove that `f` admits a point `x` such that `f^n(x)=x+m` if and only if `τ(f)=m/n`. Maps of this type naturally appear as lifts of orientation preserving circle homeomorphisms. More precisely, let `f` be an orientation preserving homeomorphism of the circle $S^1=ℝ/ℤ$, and consider a real number `a` such that `⟦a⟧ = f 0`, where `⟦⟧` means the natural projection `ℝ → ℝ/ℤ`. Then there exists a unique continuous function `F : ℝ → ℝ` such that `F 0 = a` and `⟦F x⟧ = f ⟦x⟧` for all `x` (this fact is not formalized yet). This function is strictly monotone, continuous, and satisfies `F (x + 1) = F x + 1`. The number `⟦τ F⟧ : ℝ / ℤ` is called the *rotation number* of `f`. It does not depend on the choice of `a`. ## Main definitions * `circle_deg1_lift`: a monotone map `f : ℝ → ℝ` such that `f (x + 1) = f x + 1` for all `x`; the type `circle_deg1_lift` is equipped with `lattice` and `monoid` structures; the multiplication is given by composition: `(f * g) x = f (g x)`. * `circle_deg1_lift.translation_number`: translation number of `f : circle_deg1_lift`. ## Main statements We prove the following properties of `circle_deg1_lift.translation_number`. * `circle_deg1_lift.translation_number_eq_of_dist_bounded`: if the distance between `(f^n) 0` and `(g^n) 0` is bounded from above uniformly in `n : ℕ`, then `f` and `g` have equal translation numbers. * `circle_deg1_lift.translation_number_eq_of_semiconj_by`: if two `circle_deg1_lift` maps `f`, `g` are semiconjugate by a `circle_deg1_lift` map, then `τ f = τ g`. * `circle_deg1_lift.translation_number_units_inv`: if `f` is an invertible `circle_deg1_lift` map (equivalently, `f` is a lift of an orientation-preserving circle homeomorphism), then the translation number of `f⁻¹` is the negative of the translation number of `f`. * `circle_deg1_lift.translation_number_mul_of_commute`: if `f` and `g` commute, then `τ (f * g) = τ f + τ g`. * `circle_deg1_lift.translation_number_eq_rat_iff`: the translation number of `f` is equal to a rational number `m / n` if and only if `(f^n) x = x + m` for some `x`. * `circle_deg1_lift.semiconj_of_bijective_of_translation_number_eq`: if `f` and `g` are two bijective `circle_deg1_lift` maps and their translation numbers are equal, then these maps are semiconjugate to each other. * `circle_deg1_lift.semiconj_of_group_action_of_forall_translation_number_eq`: let `f₁` and `f₂` be two actions of a group `G` on the circle by degree 1 maps (formally, `f₁` and `f₂` are two homomorphisms from `G →* circle_deg1_lift`). If the translation numbers of `f₁ g` and `f₂ g` are equal to each other for all `g : G`, then these two actions are semiconjugate by some `F : circle_deg1_lift`. This is a version of Proposition 5.4 from [Étienne Ghys, Groupes d'homeomorphismes du cercle et cohomologie bornee][ghys87:groupes]. ## Notation We use a local notation `τ` for the translation number of `f : circle_deg1_lift`. ## Implementation notes We define the translation number of `f : circle_deg1_lift` to be the limit of the sequence `(f ^ (2 ^ n)) 0 / (2 ^ n)`, then prove that `((f ^ n) x - x) / n` tends to this number for any `x`. This way it is much easier to prove that the limit exists and basic properties of the limit. We define translation number for a wider class of maps `f : ℝ → ℝ` instead of lifts of orientation preserving circle homeomorphisms for two reasons: * non-strictly monotone circle self-maps with discontinuities naturally appear as Poincaré maps for some flows on the two-torus (e.g., one can take a constant flow and glue in a few Cherry cells); * definition and some basic properties still work for this class. ## References * [Étienne Ghys, Groupes d'homeomorphismes du cercle et cohomologie bornee][ghys87:groupes] ## TODO Here are some short-term goals. * Introduce a structure or a typeclass for lifts of circle homeomorphisms. We use `units circle_deg1_lift` for now, but it's better to have a dedicated type (or a typeclass?). * Prove that the `semiconj_by` relation on circle homeomorphisms is an equivalence relation. * Introduce `conditionally_complete_lattice` structure, use it in the proof of `circle_deg1_lift.semiconj_of_group_action_of_forall_translation_number_eq`. * Prove that the orbits of the irrational rotation are dense in the circle. Deduce that a homeomorphism with an irrational rotation is semiconjugate to the corresponding irrational translation by a continuous `circle_deg1_lift`. ## Tags circle homeomorphism, rotation number -/ open filter set function (hiding commute) int open_locale topological_space classical /-! ### Definition and monoid structure -/ /-- A lift of a monotone degree one map `S¹ → S¹`. -/ structure circle_deg1_lift : Type := (to_fun : ℝ → ℝ) (monotone' : monotone to_fun) (map_add_one' : ∀ x, to_fun (x + 1) = to_fun x + 1) namespace circle_deg1_lift instance : has_coe_to_fun circle_deg1_lift := ⟨λ _, ℝ → ℝ, circle_deg1_lift.to_fun⟩ @[simp] lemma coe_mk (f h₁ h₂) : ⇑(mk f h₁ h₂) = f := rfl variables (f g : circle_deg1_lift) protected lemma monotone : monotone f := f.monotone' @[mono] lemma mono {x y} (h : x ≤ y) : f x ≤ f y := f.monotone h lemma strict_mono_iff_injective : strict_mono f ↔ injective f := f.monotone.strict_mono_iff_injective @[simp] lemma map_add_one : ∀ x, f (x + 1) = f x + 1 := f.map_add_one' @[simp] lemma map_one_add (x : ℝ) : f (1 + x) = 1 + f x := by rw [add_comm, map_add_one, add_comm] theorem coe_inj : ∀ ⦃f g : circle_deg1_lift ⦄, (f : ℝ → ℝ) = g → f = g := assume ⟨f, fm, fd⟩ ⟨g, gm, gd⟩ h, by congr; exact h @[ext] theorem ext ⦃f g : circle_deg1_lift ⦄ (h : ∀ x, f x = g x) : f = g := coe_inj $ funext h theorem ext_iff {f g : circle_deg1_lift} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, λ h, ext h⟩ instance : monoid circle_deg1_lift := { mul := λ f g, { to_fun := f ∘ g, monotone' := f.monotone.comp g.monotone, map_add_one' := λ x, by simp [map_add_one] }, one := ⟨id, monotone_id, λ _, rfl⟩, mul_one := λ f, coe_inj $ function.comp.right_id f, one_mul := λ f, coe_inj $ function.comp.left_id f, mul_assoc := λ f₁ f₂ f₃, coe_inj rfl } instance : inhabited circle_deg1_lift := ⟨1⟩ @[simp] lemma coe_mul : ⇑(f * g) = f ∘ g := rfl lemma mul_apply (x) : (f * g) x = f (g x) := rfl @[simp] lemma coe_one : ⇑(1 : circle_deg1_lift) = id := rfl instance units_has_coe_to_fun : has_coe_to_fun (units circle_deg1_lift) := ⟨λ _, ℝ → ℝ, λ f, ⇑(f : circle_deg1_lift)⟩ @[simp, norm_cast] lemma units_coe (f : units circle_deg1_lift) : ⇑(f : circle_deg1_lift) = f := rfl @[simp] lemma units_inv_apply_apply (f : units circle_deg1_lift) (x : ℝ) : (f⁻¹ : units circle_deg1_lift) (f x) = x := by simp only [← units_coe, ← mul_apply, f.inv_mul, coe_one, id] @[simp] lemma units_apply_inv_apply (f : units circle_deg1_lift) (x : ℝ) : f ((f⁻¹ : units circle_deg1_lift) x) = x := by simp only [← units_coe, ← mul_apply, f.mul_inv, coe_one, id] /-- If a lift of a circle map is bijective, then it is an order automorphism of the line. -/ def to_order_iso : units circle_deg1_lift →* ℝ ≃o ℝ := { to_fun := λ f, { to_fun := f, inv_fun := ⇑(f⁻¹), left_inv := units_inv_apply_apply f, right_inv := units_apply_inv_apply f, map_rel_iff' := λ x y, ⟨λ h, by simpa using mono ↑(f⁻¹) h, mono f⟩ }, map_one' := rfl, map_mul' := λ f g, rfl } @[simp] lemma coe_to_order_iso (f : units circle_deg1_lift) : ⇑(to_order_iso f) = f := rfl @[simp] lemma coe_to_order_iso_symm (f : units circle_deg1_lift) : ⇑(to_order_iso f).symm = (f⁻¹ : units circle_deg1_lift) := rfl @[simp] lemma coe_to_order_iso_inv (f : units circle_deg1_lift) : ⇑(to_order_iso f)⁻¹ = (f⁻¹ : units circle_deg1_lift) := rfl lemma is_unit_iff_bijective {f : circle_deg1_lift} : is_unit f ↔ bijective f := ⟨λ ⟨u, h⟩, h ▸ (to_order_iso u).bijective, λ h, units.is_unit { val := f, inv := { to_fun := (equiv.of_bijective f h).symm, monotone' := λ x y hxy, (f.strict_mono_iff_injective.2 h.1).le_iff_le.1 (by simp only [equiv.of_bijective_apply_symm_apply f h, hxy]), map_add_one' := λ x, h.1 $ by simp only [equiv.of_bijective_apply_symm_apply f, f.map_add_one] }, val_inv := ext $ equiv.of_bijective_apply_symm_apply f h, inv_val := ext $ equiv.of_bijective_symm_apply_apply f h }⟩ lemma coe_pow : ∀ n : ℕ, ⇑(f^n) = (f^[n]) | 0 := rfl | (n+1) := by {ext x, simp [coe_pow n, pow_succ'] } lemma semiconj_by_iff_semiconj {f g₁ g₂ : circle_deg1_lift} : semiconj_by f g₁ g₂ ↔ semiconj f g₁ g₂ := ext_iff lemma commute_iff_commute {f g : circle_deg1_lift} : commute f g ↔ function.commute f g := ext_iff /-! ### Translate by a constant -/ /-- The map `y ↦ x + y` as a `circle_deg1_lift`. More precisely, we define a homomorphism from `multiplicative ℝ` to `units circle_deg1_lift`, so the translation by `x` is `translation (multiplicative.of_add x)`. -/ def translate : multiplicative ℝ →* units circle_deg1_lift := by refine (units.map _).comp to_units.to_monoid_hom; exact { to_fun := λ x, ⟨λ y, x.to_add + y, λ y₁ y₂ h, add_le_add_left h _, λ y, (add_assoc _ _ _).symm⟩, map_one' := ext $ zero_add, map_mul' := λ x y, ext $ add_assoc _ _ } @[simp] lemma translate_apply (x y : ℝ) : translate (multiplicative.of_add x) y = x + y := rfl @[simp] lemma translate_inv_apply (x y : ℝ) : (translate $ multiplicative.of_add x)⁻¹ y = -x + y := rfl @[simp] lemma translate_gpow (x : ℝ) (n : ℤ) : (translate (multiplicative.of_add x))^n = translate (multiplicative.of_add $ ↑n * x) := by simp only [← gsmul_eq_mul, of_add_gsmul, monoid_hom.map_gpow] @[simp] lemma translate_pow (x : ℝ) (n : ℕ) : (translate (multiplicative.of_add x))^n = translate (multiplicative.of_add $ ↑n * x) := translate_gpow x n @[simp] lemma translate_iterate (x : ℝ) (n : ℕ) : (translate (multiplicative.of_add x))^[n] = translate (multiplicative.of_add $ ↑n * x) := by rw [← units_coe, ← coe_pow, ← units.coe_pow, translate_pow, units_coe] /-! ### Commutativity with integer translations In this section we prove that `f` commutes with translations by an integer number. First we formulate these statements (for a natural or an integer number, addition on the left or on the right, addition or subtraction) using `function.commute`, then reformulate as `simp` lemmas `map_int_add` etc. -/ lemma commute_nat_add (n : ℕ) : function.commute f ((+) n) := by simpa only [nsmul_one, add_left_iterate] using function.commute.iterate_right f.map_one_add n lemma commute_add_nat (n : ℕ) : function.commute f (λ x, x + n) := by simp only [add_comm _ (n:ℝ), f.commute_nat_add n] lemma commute_sub_nat (n : ℕ) : function.commute f (λ x, x - n) := by simpa only [sub_eq_add_neg] using (f.commute_add_nat n).inverses_right (equiv.add_right _).right_inv (equiv.add_right _).left_inv lemma commute_add_int : ∀ n : ℤ, function.commute f (λ x, x + n) | (n:ℕ) := f.commute_add_nat n | -[1+n] := by simpa only [sub_eq_add_neg] using f.commute_sub_nat (n + 1) lemma commute_int_add (n : ℤ) : function.commute f ((+) n) := by simpa only [add_comm _ (n:ℝ)] using f.commute_add_int n lemma commute_sub_int (n : ℤ) : function.commute f (λ x, x - n) := by simpa only [sub_eq_add_neg] using (f.commute_add_int n).inverses_right (equiv.add_right _).right_inv (equiv.add_right _).left_inv @[simp] lemma map_int_add (m : ℤ) (x : ℝ) : f (m + x) = m + f x := f.commute_int_add m x @[simp] lemma map_add_int (x : ℝ) (m : ℤ) : f (x + m) = f x + m := f.commute_add_int m x @[simp] lemma map_sub_int (x : ℝ) (n : ℤ) : f (x - n) = f x - n := f.commute_sub_int n x @[simp] lemma map_add_nat (x : ℝ) (n : ℕ) : f (x + n) = f x + n := f.map_add_int x n @[simp] lemma map_nat_add (n : ℕ) (x : ℝ) : f (n + x) = n + f x := f.map_int_add n x @[simp] lemma map_sub_nat (x : ℝ) (n : ℕ) : f (x - n) = f x - n := f.map_sub_int x n lemma map_int_of_map_zero (n : ℤ) : f n = f 0 + n := by rw [← f.map_add_int, zero_add] @[simp] lemma map_fract_sub_fract_eq (x : ℝ) : f (fract x) - fract x = f x - x := by rw [int.fract, f.map_sub_int, sub_sub_sub_cancel_right] /-! ### Pointwise order on circle maps -/ /-- Monotone circle maps form a lattice with respect to the pointwise order -/ noncomputable instance : lattice circle_deg1_lift := { sup := λ f g, { to_fun := λ x, max (f x) (g x), monotone' := λ x y h, max_le_max (f.mono h) (g.mono h), -- TODO: generalize to `monotone.max` map_add_one' := λ x, by simp [max_add_add_right] }, le := λ f g, ∀ x, f x ≤ g x, le_refl := λ f x, le_refl (f x), le_trans := λ f₁ f₂ f₃ h₁₂ h₂₃ x, le_trans (h₁₂ x) (h₂₃ x), le_antisymm := λ f₁ f₂ h₁₂ h₂₁, ext $ λ x, le_antisymm (h₁₂ x) (h₂₁ x), le_sup_left := λ f g x, le_max_left (f x) (g x), le_sup_right := λ f g x, le_max_right (f x) (g x), sup_le := λ f₁ f₂ f₃ h₁ h₂ x, max_le (h₁ x) (h₂ x), inf := λ f g, { to_fun := λ x, min (f x) (g x), monotone' := λ x y h, min_le_min (f.mono h) (g.mono h), map_add_one' := λ x, by simp [min_add_add_right] }, inf_le_left := λ f g x, min_le_left (f x) (g x), inf_le_right := λ f g x, min_le_right (f x) (g x), le_inf := λ f₁ f₂ f₃ h₂ h₃ x, le_min (h₂ x) (h₃ x) } @[simp] lemma sup_apply (x : ℝ) : (f ⊔ g) x = max (f x) (g x) := rfl @[simp] lemma inf_apply (x : ℝ) : (f ⊓ g) x = min (f x) (g x) := rfl lemma iterate_monotone (n : ℕ) : monotone (λ f : circle_deg1_lift, f^[n]) := λ f g h, f.monotone.iterate_le_of_le h _ lemma iterate_mono {f g : circle_deg1_lift} (h : f ≤ g) (n : ℕ) : f^[n] ≤ (g^[n]) := iterate_monotone n h lemma pow_mono {f g : circle_deg1_lift} (h : f ≤ g) (n : ℕ) : f^n ≤ g^n := λ x, by simp only [coe_pow, iterate_mono h n x] lemma pow_monotone (n : ℕ) : monotone (λ f : circle_deg1_lift, f^n) := λ f g h, pow_mono h n /-! ### Estimates on `(f * g) 0` We prove the estimates `f 0 + ⌊g 0⌋ ≤ f (g 0) ≤ f 0 + ⌈g 0⌉` and some corollaries with added/removed floors and ceils. We also prove that for two semiconjugate maps `g₁`, `g₂`, the distance between `g₁ 0` and `g₂ 0` is less than two. -/ lemma map_le_of_map_zero (x : ℝ) : f x ≤ f 0 + ⌈x⌉ := calc f x ≤ f ⌈x⌉ : f.monotone $ le_ceil _ ... = f 0 + ⌈x⌉ : f.map_int_of_map_zero _ lemma map_map_zero_le : f (g 0) ≤ f 0 + ⌈g 0⌉ := f.map_le_of_map_zero (g 0) lemma floor_map_map_zero_le : ⌊f (g 0)⌋ ≤ ⌊f 0⌋ + ⌈g 0⌉ := calc ⌊f (g 0)⌋ ≤ ⌊f 0 + ⌈g 0⌉⌋ : floor_mono $ f.map_map_zero_le g ... = ⌊f 0⌋ + ⌈g 0⌉ : floor_add_int _ _ lemma ceil_map_map_zero_le : ⌈f (g 0)⌉ ≤ ⌈f 0⌉ + ⌈g 0⌉ := calc ⌈f (g 0)⌉ ≤ ⌈f 0 + ⌈g 0⌉⌉ : ceil_mono $ f.map_map_zero_le g ... = ⌈f 0⌉ + ⌈g 0⌉ : ceil_add_int _ _ lemma map_map_zero_lt : f (g 0) < f 0 + g 0 + 1 := calc f (g 0) ≤ f 0 + ⌈g 0⌉ : f.map_map_zero_le g ... < f 0 + (g 0 + 1) : add_lt_add_left (ceil_lt_add_one _) _ ... = f 0 + g 0 + 1 : (add_assoc _ _ _).symm lemma le_map_of_map_zero (x : ℝ) : f 0 + ⌊x⌋ ≤ f x := calc f 0 + ⌊x⌋ = f ⌊x⌋ : (f.map_int_of_map_zero _).symm ... ≤ f x : f.monotone $ floor_le _ lemma le_map_map_zero : f 0 + ⌊g 0⌋ ≤ f (g 0) := f.le_map_of_map_zero (g 0) lemma le_floor_map_map_zero : ⌊f 0⌋ + ⌊g 0⌋ ≤ ⌊f (g 0)⌋ := calc ⌊f 0⌋ + ⌊g 0⌋ = ⌊f 0 + ⌊g 0⌋⌋ : (floor_add_int _ _).symm ... ≤ ⌊f (g 0)⌋ : floor_mono $ f.le_map_map_zero g lemma le_ceil_map_map_zero : ⌈f 0⌉ + ⌊g 0⌋ ≤ ⌈(f * g) 0⌉ := calc ⌈f 0⌉ + ⌊g 0⌋ = ⌈f 0 + ⌊g 0⌋⌉ : (ceil_add_int _ _).symm ... ≤ ⌈f (g 0)⌉ : ceil_mono $ f.le_map_map_zero g lemma lt_map_map_zero : f 0 + g 0 - 1 < f (g 0) := calc f 0 + g 0 - 1 = f 0 + (g 0 - 1) : add_sub_assoc _ _ _ ... < f 0 + ⌊g 0⌋ : add_lt_add_left (sub_one_lt_floor _) _ ... ≤ f (g 0) : f.le_map_map_zero g lemma dist_map_map_zero_lt : dist (f 0 + g 0) (f (g 0)) < 1 := begin rw [dist_comm, real.dist_eq, abs_lt, lt_sub_iff_add_lt', sub_lt_iff_lt_add', ← sub_eq_add_neg], exact ⟨f.lt_map_map_zero g, f.map_map_zero_lt g⟩ end lemma dist_map_zero_lt_of_semiconj {f g₁ g₂ : circle_deg1_lift} (h : function.semiconj f g₁ g₂) : dist (g₁ 0) (g₂ 0) < 2 := calc dist (g₁ 0) (g₂ 0) ≤ dist (g₁ 0) (f (g₁ 0) - f 0) + dist _ (g₂ 0) : dist_triangle _ _ _ ... = dist (f 0 + g₁ 0) (f (g₁ 0)) + dist (g₂ 0 + f 0) (g₂ (f 0)) : by simp only [h.eq, real.dist_eq, sub_sub, add_comm (f 0), sub_sub_assoc_swap, abs_sub_comm (g₂ (f 0))] ... < 2 : add_lt_add (f.dist_map_map_zero_lt g₁) (g₂.dist_map_map_zero_lt f) lemma dist_map_zero_lt_of_semiconj_by {f g₁ g₂ : circle_deg1_lift} (h : semiconj_by f g₁ g₂) : dist (g₁ 0) (g₂ 0) < 2 := dist_map_zero_lt_of_semiconj $ semiconj_by_iff_semiconj.1 h /-! ### Limits at infinities and continuity -/ protected lemma tendsto_at_bot : tendsto f at_bot at_bot := tendsto_at_bot_mono f.map_le_of_map_zero $ tendsto_at_bot_add_const_left _ _ $ tendsto_at_bot_mono (λ x, (ceil_lt_add_one x).le) $ tendsto_at_bot_add_const_right _ _ tendsto_id protected lemma tendsto_at_top : tendsto f at_top at_top := tendsto_at_top_mono f.le_map_of_map_zero $ tendsto_at_top_add_const_left _ _ $ tendsto_at_top_mono (λ x, (sub_one_lt_floor x).le) $ by simpa [sub_eq_add_neg] using tendsto_at_top_add_const_right _ _ tendsto_id lemma continuous_iff_surjective : continuous f ↔ function.surjective f := ⟨λ h, h.surjective f.tendsto_at_top f.tendsto_at_bot, f.monotone.continuous_of_surjective⟩ /-! ### Estimates on `(f^n) x` If we know that `f x` is `≤`/`<`/`≥`/`>`/`=` to `x + m`, then we have a similar estimate on `f^[n] x` and `x + n * m`. For `≤`, `≥`, and `=` we formulate both `of` (implication) and `iff` versions because implications work for `n = 0`. For `<` and `>` we formulate only `iff` versions. -/ lemma iterate_le_of_map_le_add_int {x : ℝ} {m : ℤ} (h : f x ≤ x + m) (n : ℕ) : f^[n] x ≤ x + n * m := by simpa only [nsmul_eq_mul, add_right_iterate] using (f.commute_add_int m).iterate_le_of_map_le f.monotone (monotone_id.add_const m) h n lemma le_iterate_of_add_int_le_map {x : ℝ} {m : ℤ} (h : x + m ≤ f x) (n : ℕ) : x + n * m ≤ (f^[n]) x := by simpa only [nsmul_eq_mul, add_right_iterate] using (f.commute_add_int m).symm.iterate_le_of_map_le (monotone_id.add_const m) f.monotone h n lemma iterate_eq_of_map_eq_add_int {x : ℝ} {m : ℤ} (h : f x = x + m) (n : ℕ) : f^[n] x = x + n * m := by simpa only [nsmul_eq_mul, add_right_iterate] using (f.commute_add_int m).iterate_eq_of_map_eq n h lemma iterate_pos_le_iff {x : ℝ} {m : ℤ} {n : ℕ} (hn : 0 < n) : f^[n] x ≤ x + n * m ↔ f x ≤ x + m := by simpa only [nsmul_eq_mul, add_right_iterate] using (f.commute_add_int m).iterate_pos_le_iff_map_le f.monotone (strict_mono_id.add_const m) hn lemma iterate_pos_lt_iff {x : ℝ} {m : ℤ} {n : ℕ} (hn : 0 < n) : f^[n] x < x + n * m ↔ f x < x + m := by simpa only [nsmul_eq_mul, add_right_iterate] using (f.commute_add_int m).iterate_pos_lt_iff_map_lt f.monotone (strict_mono_id.add_const m) hn lemma iterate_pos_eq_iff {x : ℝ} {m : ℤ} {n : ℕ} (hn : 0 < n) : f^[n] x = x + n * m ↔ f x = x + m := by simpa only [nsmul_eq_mul, add_right_iterate] using (f.commute_add_int m).iterate_pos_eq_iff_map_eq f.monotone (strict_mono_id.add_const m) hn lemma le_iterate_pos_iff {x : ℝ} {m : ℤ} {n : ℕ} (hn : 0 < n) : x + n * m ≤ (f^[n]) x ↔ x + m ≤ f x := by simpa only [not_lt] using not_congr (f.iterate_pos_lt_iff hn) lemma lt_iterate_pos_iff {x : ℝ} {m : ℤ} {n : ℕ} (hn : 0 < n) : x + n * m < (f^[n]) x ↔ x + m < f x := by simpa only [not_le] using not_congr (f.iterate_pos_le_iff hn) lemma mul_floor_map_zero_le_floor_iterate_zero (n : ℕ) : ↑n * ⌊f 0⌋ ≤ ⌊(f^[n] 0)⌋ := begin rw [le_floor, int.cast_mul, int.cast_coe_nat, ← zero_add ((n : ℝ) * _)], apply le_iterate_of_add_int_le_map, simp [floor_le] end /-! ### Definition of translation number -/ noncomputable theory /-- An auxiliary sequence used to define the translation number. -/ def transnum_aux_seq (n : ℕ) : ℝ := (f^(2^n)) 0 / 2^n /-- The translation number of a `circle_deg1_lift`, $τ(f)=\lim_{n→∞}\frac{f^n(x)-x}{n}$. We use an auxiliary sequence `\frac{f^{2^n}(0)}{2^n}` to define `τ(f)` because some proofs are simpler this way. -/ def translation_number : ℝ := lim at_top f.transnum_aux_seq -- TODO: choose two different symbols for `circle_deg1_lift.translation_number` and the future -- `circle_mono_homeo.rotation_number`, then make them `localized notation`s local notation `τ` := translation_number lemma transnum_aux_seq_def : f.transnum_aux_seq = λ n : ℕ, (f^(2^n)) 0 / 2^n := rfl lemma translation_number_eq_of_tendsto_aux {τ' : ℝ} (h : tendsto f.transnum_aux_seq at_top (𝓝 τ')) : τ f = τ' := h.lim_eq lemma translation_number_eq_of_tendsto₀ {τ' : ℝ} (h : tendsto (λ n:ℕ, f^[n] 0 / n) at_top (𝓝 τ')) : τ f = τ' := f.translation_number_eq_of_tendsto_aux $ by simpa [(∘), transnum_aux_seq_def, coe_pow] using h.comp (nat.tendsto_pow_at_top_at_top_of_one_lt one_lt_two) lemma translation_number_eq_of_tendsto₀' {τ' : ℝ} (h : tendsto (λ n:ℕ, f^[n + 1] 0 / (n + 1)) at_top (𝓝 τ')) : τ f = τ' := f.translation_number_eq_of_tendsto₀ $ (tendsto_add_at_top_iff_nat 1).1 h lemma transnum_aux_seq_zero : f.transnum_aux_seq 0 = f 0 := by simp [transnum_aux_seq] lemma transnum_aux_seq_dist_lt (n : ℕ) : dist (f.transnum_aux_seq n) (f.transnum_aux_seq (n+1)) < (1 / 2) / (2^n) := begin have : 0 < (2^(n+1):ℝ) := pow_pos zero_lt_two _, rw [div_div_eq_div_mul, ← pow_succ, ← abs_of_pos this], replace := abs_pos.2 (ne_of_gt this), convert (div_lt_div_right this).2 ((f^(2^n)).dist_map_map_zero_lt (f^(2^n))), simp_rw [transnum_aux_seq, real.dist_eq], rw [← abs_div, sub_div, pow_succ', pow_succ, ← two_mul, mul_div_mul_left _ _ (@two_ne_zero ℝ _ _), pow_mul, sq, mul_apply] end lemma tendsto_translation_number_aux : tendsto f.transnum_aux_seq at_top (𝓝 $ τ f) := (cauchy_seq_of_le_geometric_two 1 (λ n, le_of_lt $ f.transnum_aux_seq_dist_lt n)).tendsto_lim lemma dist_map_zero_translation_number_le : dist (f 0) (τ f) ≤ 1 := f.transnum_aux_seq_zero ▸ dist_le_of_le_geometric_two_of_tendsto₀ 1 (λ n, le_of_lt $ f.transnum_aux_seq_dist_lt n) f.tendsto_translation_number_aux lemma tendsto_translation_number_of_dist_bounded_aux (x : ℕ → ℝ) (C : ℝ) (H : ∀ n : ℕ, dist ((f^n) 0) (x n) ≤ C) : tendsto (λ n : ℕ, x (2^n) / (2^n)) at_top (𝓝 $ τ f) := begin refine f.tendsto_translation_number_aux.congr_dist (squeeze_zero (λ _, dist_nonneg) _ _), { exact λ n, C / 2^n }, { intro n, have : 0 < (2^n:ℝ) := pow_pos zero_lt_two _, convert (div_le_div_right this).2 (H (2^n)), rw [transnum_aux_seq, real.dist_eq, ← sub_div, abs_div, abs_of_pos this, real.dist_eq] }, { exact mul_zero C ▸ tendsto_const_nhds.mul (tendsto_inv_at_top_zero.comp $ tendsto_pow_at_top_at_top_of_one_lt one_lt_two) } end lemma translation_number_eq_of_dist_bounded {f g : circle_deg1_lift} (C : ℝ) (H : ∀ n : ℕ, dist ((f^n) 0) ((g^n) 0) ≤ C) : τ f = τ g := eq.symm $ g.translation_number_eq_of_tendsto_aux $ f.tendsto_translation_number_of_dist_bounded_aux _ C H @[simp] lemma translation_number_one : τ 1 = 0 := translation_number_eq_of_tendsto₀ _ $ by simp [tendsto_const_nhds] lemma translation_number_eq_of_semiconj_by {f g₁ g₂ : circle_deg1_lift} (H : semiconj_by f g₁ g₂) : τ g₁ = τ g₂ := translation_number_eq_of_dist_bounded 2 $ λ n, le_of_lt $ dist_map_zero_lt_of_semiconj_by $ H.pow_right n lemma translation_number_eq_of_semiconj {f g₁ g₂ : circle_deg1_lift} (H : function.semiconj f g₁ g₂) : τ g₁ = τ g₂ := translation_number_eq_of_semiconj_by $ semiconj_by_iff_semiconj.2 H lemma translation_number_mul_of_commute {f g : circle_deg1_lift} (h : commute f g) : τ (f * g) = τ f + τ g := begin have : tendsto (λ n : ℕ, ((λ k, (f^k) 0 + (g^k) 0) (2^n)) / (2^n)) at_top (𝓝 $ τ f + τ g) := ((f.tendsto_translation_number_aux.add g.tendsto_translation_number_aux).congr $ λ n, (add_div ((f^(2^n)) 0) ((g^(2^n)) 0) ((2:ℝ)^n)).symm), refine tendsto_nhds_unique ((f * g).tendsto_translation_number_of_dist_bounded_aux _ 1 (λ n, _)) this, rw [h.mul_pow, dist_comm], exact le_of_lt ((f^n).dist_map_map_zero_lt (g^n)) end @[simp] lemma translation_number_units_inv (f : units circle_deg1_lift) : τ ↑(f⁻¹) = -τ f := eq_neg_iff_add_eq_zero.2 $ by simp [← translation_number_mul_of_commute (commute.refl _).units_inv_left] @[simp] lemma translation_number_pow : ∀ n : ℕ, τ (f^n) = n * τ f | 0 := by simp | (n+1) := by rw [pow_succ', translation_number_mul_of_commute (commute.pow_self f n), translation_number_pow n, nat.cast_add_one, add_mul, one_mul] @[simp] lemma translation_number_gpow (f : units circle_deg1_lift) : ∀ n : ℤ, τ (f ^ n : units _) = n * τ f | (n : ℕ) := by simp [translation_number_pow f n] | -[1+n] := by { simp, ring } @[simp] lemma translation_number_conj_eq (f : units circle_deg1_lift) (g : circle_deg1_lift) : τ (↑f * g * ↑(f⁻¹)) = τ g := (translation_number_eq_of_semiconj_by (f.mk_semiconj_by g)).symm @[simp] lemma translation_number_conj_eq' (f : units circle_deg1_lift) (g : circle_deg1_lift) : τ (↑(f⁻¹) * g * f) = τ g := translation_number_conj_eq f⁻¹ g lemma dist_pow_map_zero_mul_translation_number_le (n:ℕ) : dist ((f^n) 0) (n * f.translation_number) ≤ 1 := f.translation_number_pow n ▸ (f^n).dist_map_zero_translation_number_le lemma tendsto_translation_number₀' : tendsto (λ n:ℕ, (f^(n+1)) 0 / (n+1)) at_top (𝓝 $ τ f) := begin refine (tendsto_iff_dist_tendsto_zero.2 $ squeeze_zero (λ _, dist_nonneg) (λ n, _) ((tendsto_const_div_at_top_nhds_0_nat 1).comp (tendsto_add_at_top_nat 1))), dsimp, have : (0:ℝ) < n + 1 := n.cast_add_one_pos, rw [real.dist_eq, div_sub' _ _ _ (ne_of_gt this), abs_div, ← real.dist_eq, abs_of_pos this, div_le_div_right this, ← nat.cast_add_one], apply dist_pow_map_zero_mul_translation_number_le end lemma tendsto_translation_number₀ : tendsto (λ n:ℕ, ((f^n) 0) / n) at_top (𝓝 $ τ f) := (tendsto_add_at_top_iff_nat 1).1 f.tendsto_translation_number₀' /-- For any `x : ℝ` the sequence $\frac{f^n(x)-x}{n}$ tends to the translation number of `f`. In particular, this limit does not depend on `x`. -/ lemma tendsto_translation_number (x : ℝ) : tendsto (λ n:ℕ, ((f^n) x - x) / n) at_top (𝓝 $ τ f) := begin rw [← translation_number_conj_eq' (translate $ multiplicative.of_add x)], convert tendsto_translation_number₀ _, ext n, simp [sub_eq_neg_add, units.conj_pow'] end lemma tendsto_translation_number' (x : ℝ) : tendsto (λ n:ℕ, ((f^(n+1)) x - x) / (n+1)) at_top (𝓝 $ τ f) := (tendsto_add_at_top_iff_nat 1).2 (f.tendsto_translation_number x) lemma translation_number_mono : monotone τ := λ f g h, le_of_tendsto_of_tendsto' f.tendsto_translation_number₀ g.tendsto_translation_number₀ $ λ n, div_le_div_of_le_of_nonneg (pow_mono h n 0) n.cast_nonneg lemma translation_number_translate (x : ℝ) : τ (translate $ multiplicative.of_add x) = x := translation_number_eq_of_tendsto₀' _ $ by simp [nat.cast_add_one_ne_zero, mul_div_cancel_left, tendsto_const_nhds] lemma translation_number_le_of_le_add {z : ℝ} (hz : ∀ x, f x ≤ x + z) : τ f ≤ z := translation_number_translate z ▸ translation_number_mono (λ x, trans_rel_left _ (hz x) (add_comm _ _)) lemma le_translation_number_of_add_le {z : ℝ} (hz : ∀ x, x + z ≤ f x) : z ≤ τ f := translation_number_translate z ▸ translation_number_mono (λ x, trans_rel_right _ (add_comm _ _) (hz x)) lemma translation_number_le_of_le_add_int {x : ℝ} {m : ℤ} (h : f x ≤ x + m) : τ f ≤ m := le_of_tendsto' (f.tendsto_translation_number' x) $ λ n, (div_le_iff' (n.cast_add_one_pos : (0 : ℝ) < _)).mpr $ sub_le_iff_le_add'.2 $ (coe_pow f (n + 1)).symm ▸ f.iterate_le_of_map_le_add_int h (n + 1) lemma translation_number_le_of_le_add_nat {x : ℝ} {m : ℕ} (h : f x ≤ x + m) : τ f ≤ m := @translation_number_le_of_le_add_int f x m h lemma le_translation_number_of_add_int_le {x : ℝ} {m : ℤ} (h : x + m ≤ f x) : ↑m ≤ τ f := ge_of_tendsto' (f.tendsto_translation_number' x) $ λ n, (le_div_iff (n.cast_add_one_pos : (0 : ℝ) < _)).mpr $ le_sub_iff_add_le'.2 $ by simp only [coe_pow, mul_comm (m:ℝ), ← nat.cast_add_one, f.le_iterate_of_add_int_le_map h] lemma le_translation_number_of_add_nat_le {x : ℝ} {m : ℕ} (h : x + m ≤ f x) : ↑m ≤ τ f := @le_translation_number_of_add_int_le f x m h /-- If `f x - x` is an integer number `m` for some point `x`, then `τ f = m`. On the circle this means that a map with a fixed point has rotation number zero. -/ lemma translation_number_of_eq_add_int {x : ℝ} {m : ℤ} (h : f x = x + m) : τ f = m := le_antisymm (translation_number_le_of_le_add_int f $ le_of_eq h) (le_translation_number_of_add_int_le f $ le_of_eq h.symm) lemma floor_sub_le_translation_number (x : ℝ) : ↑⌊f x - x⌋ ≤ τ f := le_translation_number_of_add_int_le f $ le_sub_iff_add_le'.1 (floor_le $ f x - x) lemma translation_number_le_ceil_sub (x : ℝ) : τ f ≤ ⌈f x - x⌉ := translation_number_le_of_le_add_int f $ sub_le_iff_le_add'.1 (le_ceil $ f x - x) lemma map_lt_of_translation_number_lt_int {n : ℤ} (h : τ f < n) (x : ℝ) : f x < x + n := not_le.1 $ mt f.le_translation_number_of_add_int_le $ not_le.2 h lemma map_lt_of_translation_number_lt_nat {n : ℕ} (h : τ f < n) (x : ℝ) : f x < x + n := @map_lt_of_translation_number_lt_int f n h x lemma map_lt_add_floor_translation_number_add_one (x : ℝ) : f x < x + ⌊τ f⌋ + 1 := begin rw [add_assoc], norm_cast, refine map_lt_of_translation_number_lt_int _ _ _, push_cast, exact lt_floor_add_one _ end lemma map_lt_add_translation_number_add_one (x : ℝ) : f x < x + τ f + 1 := calc f x < x + ⌊τ f⌋ + 1 : f.map_lt_add_floor_translation_number_add_one x ... ≤ x + τ f + 1 : by { mono*, exact floor_le (τ f) } lemma lt_map_of_int_lt_translation_number {n : ℤ} (h : ↑n < τ f) (x : ℝ) : x + n < f x := not_le.1 $ mt f.translation_number_le_of_le_add_int $ not_le.2 h lemma lt_map_of_nat_lt_translation_number {n : ℕ} (h : ↑n < τ f) (x : ℝ) : x + n < f x := @lt_map_of_int_lt_translation_number f n h x /-- If `f^n x - x`, `n > 0`, is an integer number `m` for some point `x`, then `τ f = m / n`. On the circle this means that a map with a periodic orbit has a rational rotation number. -/ lemma translation_number_of_map_pow_eq_add_int {x : ℝ} {n : ℕ} {m : ℤ} (h : (f^n) x = x + m) (hn : 0 < n) : τ f = m / n := begin have := (f^n).translation_number_of_eq_add_int h, rwa [translation_number_pow, mul_comm, ← eq_div_iff] at this, exact nat.cast_ne_zero.2 (ne_of_gt hn) end /-- If a predicate depends only on `f x - x` and holds for all `0 ≤ x ≤ 1`, then it holds for all `x`. -/ lemma forall_map_sub_of_Icc (P : ℝ → Prop) (h : ∀ x ∈ Icc (0:ℝ) 1, P (f x - x)) (x : ℝ) : P (f x - x) := f.map_fract_sub_fract_eq x ▸ h _ ⟨fract_nonneg _, le_of_lt (fract_lt_one _)⟩ lemma translation_number_lt_of_forall_lt_add (hf : continuous f) {z : ℝ} (hz : ∀ x, f x < x + z) : τ f < z := begin obtain ⟨x, xmem, hx⟩ : ∃ x ∈ Icc (0:ℝ) 1, ∀ y ∈ Icc (0:ℝ) 1, f y - y ≤ f x - x, from is_compact_Icc.exists_forall_ge (nonempty_Icc.2 zero_le_one) (hf.sub continuous_id).continuous_on, refine lt_of_le_of_lt _ (sub_lt_iff_lt_add'.2 $ hz x), apply translation_number_le_of_le_add, simp only [← sub_le_iff_le_add'], exact f.forall_map_sub_of_Icc (λ a, a ≤ f x - x) hx end lemma lt_translation_number_of_forall_add_lt (hf : continuous f) {z : ℝ} (hz : ∀ x, x + z < f x) : z < τ f := begin obtain ⟨x, xmem, hx⟩ : ∃ x ∈ Icc (0:ℝ) 1, ∀ y ∈ Icc (0:ℝ) 1, f x - x ≤ f y - y, from is_compact_Icc.exists_forall_le (nonempty_Icc.2 zero_le_one) (hf.sub continuous_id).continuous_on, refine lt_of_lt_of_le (lt_sub_iff_add_lt'.2 $ hz x) _, apply le_translation_number_of_add_le, simp only [← le_sub_iff_add_le'], exact f.forall_map_sub_of_Icc _ hx end /-- If `f` is a continuous monotone map `ℝ → ℝ`, `f (x + 1) = f x + 1`, then there exists `x` such that `f x = x + τ f`. -/ lemma exists_eq_add_translation_number (hf : continuous f) : ∃ x, f x = x + τ f := begin obtain ⟨a, ha⟩ : ∃ x, f x ≤ x + f.translation_number, { by_contradiction H, push_neg at H, exact lt_irrefl _ (f.lt_translation_number_of_forall_add_lt hf H) }, obtain ⟨b, hb⟩ : ∃ x, x + τ f ≤ f x, { by_contradiction H, push_neg at H, exact lt_irrefl _ (f.translation_number_lt_of_forall_lt_add hf H) }, exact intermediate_value_univ₂ hf (continuous_id.add continuous_const) ha hb end lemma translation_number_eq_int_iff (hf : continuous f) {m : ℤ} : τ f = m ↔ ∃ x, f x = x + m := begin refine ⟨λ h, h ▸ f.exists_eq_add_translation_number hf, _⟩, rintros ⟨x, hx⟩, exact f.translation_number_of_eq_add_int hx end lemma continuous_pow (hf : continuous f) (n : ℕ) : continuous ⇑(f^n : circle_deg1_lift) := by { rw coe_pow, exact hf.iterate n } lemma translation_number_eq_rat_iff (hf : continuous f) {m : ℤ} {n : ℕ} (hn : 0 < n) : τ f = m / n ↔ ∃ x, (f^n) x = x + m := begin rw [eq_div_iff, mul_comm, ← translation_number_pow]; [skip, exact ne_of_gt (nat.cast_pos.2 hn)], exact (f^n).translation_number_eq_int_iff (f.continuous_pow hf n) end /-- Consider two actions `f₁ f₂ : G →* circle_deg1_lift` of a group on the real line by lifts of orientation preserving circle homeomorphisms. Suppose that for each `g : G` the homeomorphisms `f₁ g` and `f₂ g` have equal rotation numbers. Then there exists `F : circle_deg1_lift` such that `F * f₁ g = f₂ g * F` for all `g : G`. This is a version of Proposition 5.4 from [Étienne Ghys, Groupes d'homeomorphismes du cercle et cohomologie bornee][ghys87:groupes]. -/ lemma semiconj_of_group_action_of_forall_translation_number_eq {G : Type*} [group G] (f₁ f₂ : G →* circle_deg1_lift) (h : ∀ g, τ (f₁ g) = τ (f₂ g)) : ∃ F : circle_deg1_lift, ∀ g, semiconj F (f₁ g) (f₂ g) := begin -- Equality of translation number guarantees that for each `x` -- the set `{f₂ g⁻¹ (f₁ g x) | g : G}` is bounded above. have : ∀ x, bdd_above (range $ λ g, f₂ g⁻¹ (f₁ g x)), { refine λ x, ⟨x + 2, _⟩, rintro _ ⟨g, rfl⟩, have : τ (f₂ g⁻¹) = -τ (f₂ g), by rw [← monoid_hom.coe_to_hom_units, monoid_hom.map_inv, translation_number_units_inv, monoid_hom.coe_to_hom_units], calc f₂ g⁻¹ (f₁ g x) ≤ f₂ g⁻¹ (x + τ (f₁ g) + 1) : mono _ (map_lt_add_translation_number_add_one _ _).le ... = f₂ g⁻¹ (x + τ (f₂ g)) + 1 : by rw [h, map_add_one] ... ≤ x + τ (f₂ g) + τ (f₂ g⁻¹) + 1 + 1 : by { mono, exact (map_lt_add_translation_number_add_one _ _).le } ... = x + 2 : by simp [this, bit0, add_assoc] }, -- We have a theorem about actions by `order_iso`, so we introduce auxiliary maps -- to `ℝ ≃o ℝ`. set F₁ := to_order_iso.comp f₁.to_hom_units, set F₂ := to_order_iso.comp f₂.to_hom_units, have hF₁ : ∀ g, ⇑(F₁ g) = f₁ g := λ _, rfl, have hF₂ : ∀ g, ⇑(F₂ g) = f₂ g := λ _, rfl, simp only [← hF₁, ← hF₂], -- Now we apply `cSup_div_semiconj` and go back to `f₁` and `f₂`. refine ⟨⟨_, λ x y hxy, _, λ x, _⟩, cSup_div_semiconj F₂ F₁ (λ x, _)⟩; simp only [hF₁, hF₂, ← monoid_hom.map_inv, coe_mk], { refine csupr_le_csupr (this y) (λ g, _), exact mono _ (mono _ hxy) }, { simp only [map_add_one], exact (map_csupr_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) (monotone_id.add_const (1 : ℝ)) (this x)).symm }, { exact this x } end /-- If two lifts of circle homeomorphisms have the same translation number, then they are semiconjugate by a `circle_deg1_lift`. This version uses arguments `f₁ f₂ : units circle_deg1_lift` to assume that `f₁` and `f₂` are homeomorphisms. -/ lemma units_semiconj_of_translation_number_eq {f₁ f₂ : units circle_deg1_lift} (h : τ f₁ = τ f₂) : ∃ F : circle_deg1_lift, semiconj F f₁ f₂ := begin have : ∀ n : multiplicative ℤ, τ ((units.coe_hom _).comp (gpowers_hom _ f₁) n) = τ ((units.coe_hom _).comp (gpowers_hom _ f₂) n), { intro n, simp [h] }, exact (semiconj_of_group_action_of_forall_translation_number_eq _ _ this).imp (λ F hF, hF (multiplicative.of_add 1)) end /-- If two lifts of circle homeomorphisms have the same translation number, then they are semiconjugate by a `circle_deg1_lift`. This version uses assumptions `is_unit f₁` and `is_unit f₂` to assume that `f₁` and `f₂` are homeomorphisms. -/ lemma semiconj_of_is_unit_of_translation_number_eq {f₁ f₂ : circle_deg1_lift} (h₁ : is_unit f₁) (h₂ : is_unit f₂) (h : τ f₁ = τ f₂) : ∃ F : circle_deg1_lift, semiconj F f₁ f₂ := by { rcases ⟨h₁, h₂⟩ with ⟨⟨f₁, rfl⟩, ⟨f₂, rfl⟩⟩, exact units_semiconj_of_translation_number_eq h } /-- If two lifts of circle homeomorphisms have the same translation number, then they are semiconjugate by a `circle_deg1_lift`. This version uses assumptions `bijective f₁` and `bijective f₂` to assume that `f₁` and `f₂` are homeomorphisms. -/ lemma semiconj_of_bijective_of_translation_number_eq {f₁ f₂ : circle_deg1_lift} (h₁ : bijective f₁) (h₂ : bijective f₂) (h : τ f₁ = τ f₂) : ∃ F : circle_deg1_lift, semiconj F f₁ f₂ := semiconj_of_is_unit_of_translation_number_eq (is_unit_iff_bijective.2 h₁) (is_unit_iff_bijective.2 h₂) h end circle_deg1_lift
f61409c7e3fb9a9540cf5f37acb7c623923906d2
367134ba5a65885e863bdc4507601606690974c1
/src/deprecated/subfield.lean
b68a58095d3f4a61aa60c0ffac71038dc8f56ffc
[ "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
5,171
lean
/- Copyright (c) 2018 Andreas Swerdlow. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andreas Swerdlow -/ import deprecated.subring import algebra.group_with_zero.power variables {F : Type*} [field F] (S : set F) class is_subfield extends is_subring S : Prop := (inv_mem : ∀ {x : F}, x ∈ S → x⁻¹ ∈ S) instance is_subfield.field [is_subfield S] : field S := by letI cr_inst : comm_ring S := subset.comm_ring; exact { inv := λ x, ⟨x⁻¹, is_subfield.inv_mem x.2⟩, exists_pair_ne := ⟨0, 1, λ h, zero_ne_one (subtype.ext_iff_val.1 h)⟩, mul_inv_cancel := λ a ha, subtype.ext_iff_val.2 (mul_inv_cancel (λ h, ha $ subtype.ext_iff_val.2 h)), inv_zero := subtype.ext_iff_val.2 inv_zero, .. cr_inst } lemma is_subfield.pow_mem {a : F} {n : ℤ} {s : set F} [is_subfield s] (h : a ∈ s) : a ^ n ∈ s := begin cases n, { exact is_submonoid.pow_mem h }, { exact is_subfield.inv_mem (is_submonoid.pow_mem h) }, end instance univ.is_subfield : is_subfield (@set.univ F) := { inv_mem := by intros; trivial } /- note: in the next two declarations, if we let type-class inference figure out the instance `ring_hom.is_subring_preimage` then that instance only applies when particular instances of `is_add_subgroup _` and `is_submonoid _` are chosen (which are not the default ones). If we specify it explicitly, then it doesn't complain. -/ instance preimage.is_subfield {K : Type*} [field K] (f : F →+* K) (s : set K) [is_subfield s] : is_subfield (f ⁻¹' s) := { inv_mem := λ a (ha : f a ∈ s), show f a⁻¹ ∈ s, by { rw [f.map_inv], exact is_subfield.inv_mem ha }, ..f.is_subring_preimage s } instance image.is_subfield {K : Type*} [field K] (f : F →+* K) (s : set F) [is_subfield s] : is_subfield (f '' s) := { inv_mem := λ a ⟨x, xmem, ha⟩, ⟨x⁻¹, is_subfield.inv_mem xmem, ha ▸ f.map_inv _⟩, ..f.is_subring_image s } instance range.is_subfield {K : Type*} [field K] (f : F →+* K) : is_subfield (set.range f) := by { rw ← set.image_univ, apply_instance } namespace field /-- `field.closure s` is the minimal subfield that includes `s`. -/ def closure : set F := { x | ∃ y ∈ ring.closure S, ∃ z ∈ ring.closure S, y / z = x } variables {S} theorem ring_closure_subset : ring.closure S ⊆ closure S := λ x hx, ⟨x, hx, 1, is_submonoid.one_mem, div_one x⟩ instance closure.is_submonoid : is_submonoid (closure S) := { mul_mem := by rintros _ _ ⟨p, hp, q, hq, hq0, rfl⟩ ⟨r, hr, s, hs, hs0, rfl⟩; exact ⟨p * r, is_submonoid.mul_mem hp hr, q * s, is_submonoid.mul_mem hq hs, (div_mul_div _ _ _ _).symm⟩, one_mem := ring_closure_subset $ is_submonoid.one_mem } instance closure.is_subfield : is_subfield (closure S) := have h0 : (0:F) ∈ closure S, from ring_closure_subset $ is_add_submonoid.zero_mem, { add_mem := begin intros a b ha hb, rcases (id ha) with ⟨p, hp, q, hq, rfl⟩, rcases (id hb) with ⟨r, hr, s, hs, rfl⟩, classical, by_cases hq0 : q = 0, by simp [hb, hq0], by_cases hs0 : s = 0, by simp [ha, hs0], exact ⟨p * s + q * r, is_add_submonoid.add_mem (is_submonoid.mul_mem hp hs) (is_submonoid.mul_mem hq hr), q * s, is_submonoid.mul_mem hq hs, (div_add_div p r hq0 hs0).symm⟩ end, zero_mem := h0, neg_mem := begin rintros _ ⟨p, hp, q, hq, rfl⟩, exact ⟨-p, is_add_subgroup.neg_mem hp, q, hq, neg_div q p⟩ end, inv_mem := begin rintros _ ⟨p, hp, q, hq, rfl⟩, classical, by_cases hp0 : p = 0, by simp [hp0, h0], exact ⟨q, hq, p, hp, inv_div.symm⟩ end } theorem mem_closure {a : F} (ha : a ∈ S) : a ∈ closure S := ring_closure_subset $ ring.mem_closure ha theorem subset_closure : S ⊆ closure S := λ _, mem_closure theorem closure_subset {T : set F} [is_subfield T] (H : S ⊆ T) : closure S ⊆ T := by rintros _ ⟨p, hp, q, hq, hq0, rfl⟩; exact is_submonoid.mul_mem (ring.closure_subset H hp) (is_subfield.inv_mem $ ring.closure_subset H hq) theorem closure_subset_iff (s t : set F) [is_subfield t] : closure s ⊆ t ↔ s ⊆ t := ⟨set.subset.trans subset_closure, closure_subset⟩ theorem closure_mono {s t : set F} (H : s ⊆ t) : closure s ⊆ closure t := closure_subset $ set.subset.trans H subset_closure end field lemma is_subfield_Union_of_directed {ι : Type*} [hι : nonempty ι] (s : ι → set F) [∀ i, is_subfield (s i)] (directed : ∀ i j, ∃ k, s i ⊆ s k ∧ s j ⊆ s k) : is_subfield (⋃i, s i) := { inv_mem := λ x hx, let ⟨i, hi⟩ := set.mem_Union.1 hx in set.mem_Union.2 ⟨i, is_subfield.inv_mem hi⟩, to_is_subring := is_subring_Union_of_directed s directed } instance is_subfield.inter (S₁ S₂ : set F) [is_subfield S₁] [is_subfield S₂] : is_subfield (S₁ ∩ S₂) := { inv_mem := λ x hx, ⟨is_subfield.inv_mem hx.1, is_subfield.inv_mem hx.2⟩ } instance is_subfield.Inter {ι : Sort*} (S : ι → set F) [h : ∀ y : ι, is_subfield (S y)] : is_subfield (set.Inter S) := { inv_mem := λ x hx, set.mem_Inter.2 $ λ y, is_subfield.inv_mem $ set.mem_Inter.1 hx y }
d15e01d6213955505141e920ac425746d2a0f69e
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/probability_theory/notation.lean
4f1fa289a1660769a1d99b9a018eeb818c6f345c
[ "Apache-2.0" ]
permissive
jumpy4/mathlib
d3829e75173012833e9f15ac16e481e17596de0f
af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13
refs/heads/master
1,693,508,842,818
1,636,203,271,000
1,636,203,271,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,532
lean
/- Copyright (c) 2021 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne -/ import measure_theory.function.conditional_expectation import measure_theory.decomposition.radon_nikodym /-! # Notations for probability theory This file defines the following notations, for functions `X,Y`, measures `P, Q` defined on a measurable space `m0`, and another measurable space structure `m` with `hm : m ≤ m0`, - `P[X] = ∫ a, X a ∂P` - `𝔼[X] = ∫ a, X a` - `𝔼[X|hm]`: conditional expectation of `X` with respect to the measure `volume` and the measurable space `m`. The similar `P[X|hm]` for a measure `P` is defined in measure_theory.function.conditional_expectation. - `X =ₐₛ Y`: `X =ᵐ[volume] Y` - `X ≤ₐₛ Y`: `X ≤ᵐ[volume] Y` - `∂P/∂Q = P.rn_deriv Q` TODO: define the notation `ℙ s` for the probability of a set `s`, and decide whether it should be a value in `ℝ`, `ℝ≥0` or `ℝ≥0∞`. -/ open measure_theory localized "notation `𝔼[` X `|` hm `]` := measure_theory.condexp hm volume X" in probability_theory localized "notation P `[` X `]` := ∫ x, X x ∂P" in probability_theory localized "notation `𝔼[` X `]` := ∫ a, X a" in probability_theory localized "notation X `=ₐₛ`:50 Y:50 := X =ᵐ[volume] Y" in probability_theory localized "notation X `≤ₐₛ`:50 Y:50 := X ≤ᵐ[volume] Y" in probability_theory localized "notation `∂` P `/∂`:50 Q:50 := P.rn_deriv Q" in probability_theory
075bd06b35608a7a8f8b4bfe844a38e580c9f17b
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/tests/lean/Format.lean
b2bbe415adf546e531a483dd87bcb2cabf7ff9f7
[ "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
596
lean
#lang lean4 open Lean open Std open Std.Format def eval (w : Nat) (f : Format) : IO Unit := do IO.println $ f.pretty w -- hard line breaks should re-evaluate flattening behavior within group #eval eval 5 $ fill (text "a" ++ line ++ text "b\nlooooooooong" ++ line ++ text "c") ++ line ++ text "d" -- basic `fill` test #eval eval 20 $ fill (Format.joinSep ((List.range 13).map fun i => i.repeat (fun s => s ++ "a") "a") line) -- `fill` items that are too big should get dedicated #eval eval 8 $ fill (Format.joinSep [text "a", text "b", paren (text "ccccc" ++ line ++ text "d"), text "e"] line)
fbdc64c0de89877bf579bd8e84fcb2713a3fa7cd
caa1512363b76923d0e9cdb716122a5c26c3c6bc
/src/inner_product_space.lean
e3c589368c5a03dfed9cc2a60ad3d721027bd817
[]
no_license
apurvanakade/cvx
deb20e425ce478159a98e1ffc0d37f9c88a89280
b47784831339df5a3e45f5cddd84edc545f95808
refs/heads/master
1,687,403,288,536
1,555,930,740,000
1,555,930,740,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,827
lean
-- based on Jeremy's Lean2 formalization import algebra.module import analysis.normed_space.basic import data.real.basic import linear_algebra.basic local attribute [instance] classical.prop_decidable noncomputable theory -- TODO: move lemma le_of_sqr_le_sqr {a : ℝ} {b : ℝ} (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a ^ 2 ≤ b ^ 2) : a ≤ b := begin rw [pow_two,pow_two] at hab, apply or.elim (le_or_gt a b) (λh, h), assume h, apply false.elim, apply lt_irrefl (b * b), exact (lt_of_lt_of_le (mul_self_lt_mul_self hb h) hab) end class has_inner (V : Type*) (W : Type*):= (inner : W → W → V) notation `⟪` v `, ` w `⟫` := has_inner.inner ℝ v w --TODO: try to move add_comm_group in front and use `attribute [-instance] nat.cast_coe` class real_inner_product_space (V : Type*) extends has_inner ℝ V, add_comm_group V, vector_space ℝ V := (inner_add_left : ∀ u v w, inner (u + v) w = inner u w + inner v w) (inner_smul_left : ∀ r v w, inner (r • v) w = r * inner v w) (inner_comm : ∀ v w, inner v w = inner w v) (inner_self_nonneg : ∀ v, 0 ≤ inner v v) (eq_zero_of_inner_self_eq_zero : ∀ {v}, inner v v = 0 → v = 0) namespace real_inner_product_space variables {V : Type*} [real_inner_product_space V] {W : Type*} [real_inner_product_space W] open real_inner_product_space @[simp] lemma inner_add_right (u v w : V) : ⟪u, v + w⟫ = ⟪u, v⟫ + ⟪u, w⟫ := by rw [inner_comm, inner_add_left, inner_comm, inner_comm w] @[simp] lemma inner_smul_right (r : ℝ) (v w : V) : ⟪v, r • w⟫ = r * ⟪v, w⟫ := by rw [inner_comm, inner_smul_left, inner_comm] @[simp] lemma inner_neg_left (u v : V) : ⟪-u, v⟫ = -⟪u, v⟫ := by rw [←neg_one_smul _ u, inner_smul_left, ←neg_eq_neg_one_mul] @[simp] lemma inner_neg_right (u v : V) : ⟪u, -v⟫ = -⟪u, v⟫ := by rw [inner_comm, inner_neg_left, inner_comm] lemma neg_inner_neg (x y : V): ⟪ - x, - y ⟫ = ⟪ x, y ⟫ := by rw [inner_neg_left, inner_neg_right, neg_neg] @[simp] lemma inner_sub_left (u v w : V) : ⟪u - v, w⟫ = ⟪u, w⟫ - ⟪v, w⟫ := by rw [sub_eq_add_neg, sub_eq_add_neg, inner_add_left, inner_neg_left] @[simp] lemma inner_sub_right (u v w : V) : ⟪u, v - w⟫ = ⟪u, v⟫ - ⟪u, w⟫ := by rw [sub_eq_add_neg, sub_eq_add_neg, inner_add_right, inner_neg_right] @[simp] lemma inner_zero_left (v : V) : ⟪0, v⟫ = 0 := by rw [←zero_smul _ v, inner_smul_left, zero_mul] @[simp] lemma inner_zero_right (v : V) : ⟪v, 0⟫ = 0 := by rw [inner_comm, inner_zero_left] @[simp] lemma inner_self_pos {v : V} (h : v ≠ 0) : 0 < ⟪v, v⟫ := lt_of_le_of_ne (inner_self_nonneg _) (λ h_inner_0, h (eq_zero_of_inner_self_eq_zero h_inner_0.symm)) def orthogonal (u v : V) : Prop := ⟪u, v⟫ = 0 infix ` ⊥ `:50 := orthogonal lemma orthogonal_comm {u v : V} (H : u ⊥ v) : v ⊥ u := by unfold orthogonal at *; rw [inner_comm, H] section /- first, we define norm internally, to show that an inner product space is a normed space -/ private def ip_norm (v : V):= real.sqrt ⟪v, v⟫ private lemma ip_norm_zero : ip_norm (0 : V) = 0 := by rw [ip_norm, inner_zero_left, real.sqrt_zero] private lemma ip_norm_squared (v : V) : (ip_norm v) ^2 = ⟪v, v⟫ := real.sqr_sqrt (inner_self_nonneg v) private lemma ip_norm_nonneg (v : V) : 0 ≤ ip_norm v := real.sqrt_nonneg _ private lemma eq_zero_of_ip_norm_eq_zero {v : V} (H : ip_norm v = 0) : v = 0 := have ⟪v, v⟫ = 0, by rw [←ip_norm_squared, H, pow_two, zero_mul], eq_zero_of_inner_self_eq_zero this private lemma ip_norm_eq_zero_iff (v : V) : ip_norm v = 0 ↔ v = 0 := begin apply iff.intro, { intro h, apply eq_zero_of_ip_norm_eq_zero h }, { intro h, rw [h, ip_norm_zero] } end private lemma ip_norm_smul (r : ℝ) (v : V) : ip_norm (r • v) = abs r * ip_norm v := begin rw [ip_norm, inner_smul_left, inner_smul_right , ←mul_assoc], rw [real.sqrt_mul (mul_self_nonneg r) _, real.sqrt_mul_self_eq_abs, ip_norm] end private lemma ip_norm_pythagorean {u v : V} (ortho : u ⊥ v) : (ip_norm (u + v))^2 = (ip_norm u)^2 + (ip_norm v)^2 := begin rw [orthogonal] at ortho, rw [ip_norm_squared, ip_norm_squared, inner_add_right, inner_add_left, inner_add_left], rw [inner_comm v u, ortho, zero_add, add_zero, ip_norm, real.sqr_sqrt (inner_self_nonneg _)] end private def ip_proj_on (u : V) {v : V} (H : v ≠ 0) : V := (⟪u, v⟫ / (ip_norm v)^2) • v private lemma ip_proj_on_orthogonal (u : V) {v : V} (H : v ≠ 0) : ip_proj_on u H ⊥ (u - ip_proj_on u H) := begin rw [ip_proj_on, orthogonal, inner_sub_right, inner_smul_left, inner_smul_left, inner_smul_right], rw [ip_norm_squared], rw [div_mul_cancel _ (assume H', H (eq_zero_of_inner_self_eq_zero H'))], rw [inner_comm v u, sub_self] end private lemma ip_norm_proj_on_eq (u : V) {v : V} (H : v ≠ 0) : ip_norm (ip_proj_on u H) = abs ⟪u, v⟫ / ip_norm v := have H1 : ip_norm v ≠ 0, from assume H', H (eq_zero_of_ip_norm_eq_zero H'), begin rw [ip_proj_on, ip_norm_smul, abs_div, abs_of_nonneg (pow_two_nonneg (ip_norm v)), pow_two], rw [div_mul_eq_mul_div, ←div_mul_div, div_self H1, mul_one] end private lemma ip_norm_squared_pythagorean (u : V) {v : V} (H : v ≠ 0) : (ip_norm u)^2 = (ip_norm (u - ip_proj_on u H))^2 + (ip_norm (ip_proj_on u H))^2 := calc (ip_norm u)^2 = (ip_norm (u - ip_proj_on u H + ip_proj_on u H))^2 : by rw sub_add_cancel ... = (ip_norm (u - ip_proj_on u H))^2 + (ip_norm (ip_proj_on u H))^2 : ip_norm_pythagorean (orthogonal_comm (ip_proj_on_orthogonal u H)) private lemma ip_norm_proj_on_le (u : V) {v : V} (H : v ≠ 0) : ip_norm (ip_proj_on u H) ≤ ip_norm u := have (ip_norm u)^2 ≥ (ip_norm (ip_proj_on u H))^2, begin rw [ip_norm_squared_pythagorean u H], apply le_add_of_nonneg_left (pow_two_nonneg (ip_norm (u - ip_proj_on u H))) end, le_of_sqr_le_sqr (ip_norm_nonneg _) (ip_norm_nonneg _) this private lemma ip_cauchy_schwartz (u v : V) : abs ⟪u, v⟫ ≤ ip_norm u * ip_norm v := begin by_cases h_cases : v = (0 : V), { rw [h_cases, inner_zero_right, abs_zero, ip_norm_zero, mul_zero] }, { have h_norm_ne : ip_norm v ≠ 0, from λH, h_cases (eq_zero_of_ip_norm_eq_zero H), have h_norm_gt : ip_norm v > 0, from lt_of_le_of_ne (real.sqrt_nonneg _) (ne.symm h_norm_ne), let H := ip_norm_proj_on_le u h_cases, rw [ip_norm_proj_on_eq u h_cases] at H, exact (div_le_iff h_norm_gt).1 H } end private lemma ip_cauchy_schwartz' (u v : V) : ⟪u, v⟫ ≤ ip_norm u * ip_norm v := le_trans (le_abs_self _) (ip_cauchy_schwartz _ _) private lemma ip_norm_triangle (u v : V) : ip_norm (u + v) ≤ ip_norm u + ip_norm v := have H : ⟪u, v⟫ ≤ ip_norm u * ip_norm v, from ip_cauchy_schwartz' u v, have (ip_norm (u + v))^2 ≤ (ip_norm u + ip_norm v)^2, from calc (ip_norm (u + v))^2 = (ip_norm u)^2 + (ip_norm v)^2 + ⟪u, v⟫ + ⟪u, v⟫ : begin simp only [ip_norm, real.sqr_sqrt (inner_self_nonneg _)], rw [inner_add_left, inner_add_right, inner_add_right, inner_comm v u], rw [←add_assoc, ←add_right_comm _ _ ⟪v, v⟫, ←add_right_comm _ _ ⟪v, v⟫] end ... ≤ (ip_norm u)^2 + (ip_norm v)^2 + ip_norm u * ip_norm v + ⟪u, v⟫ : add_le_add_right (add_le_add_left H _) _ ... ≤ (ip_norm u)^2 + (ip_norm v)^2 + ip_norm u * ip_norm v + ip_norm u * ip_norm v : add_le_add_left H _ ... = (ip_norm u + ip_norm v)^2 : by rw [pow_two, pow_two, pow_two, right_distrib, left_distrib, left_distrib, ←add_assoc, add_right_comm _ (ip_norm v * ip_norm v), add_right_comm _ (ip_norm v * ip_norm v), mul_comm (ip_norm v) (ip_norm u)], le_of_sqr_le_sqr (ip_norm_nonneg _) (add_nonneg (ip_norm_nonneg _) (ip_norm_nonneg _)) this instance has_norm [real_inner_product_space V] : has_norm V := { norm := ip_norm }. lemma normed_space_core : normed_space.core ℝ V := { norm_eq_zero_iff := ip_norm_eq_zero_iff, triangle := ip_norm_triangle, norm_smul := ip_norm_smul } -- TODO: Should we have a similar setup like "normed_space_core" for inner_product_space? instance is_normed_space [real_inner_product_space V] : normed_space ℝ V := normed_space.of_core _ _ normed_space_core end /- now we restate the new theorems using the norm notation -/ lemma norm_squared (v : V) : ∥ v ∥^2 = ⟪v, v⟫ := ip_norm_squared v lemma norm_pythagorean {u v : V} (ortho : u ⊥ v) : ∥ u + v ∥^2 = ∥ u ∥^2 + ∥ v ∥^2 := ip_norm_pythagorean ortho def proj_on (u : V) {v : V} (H : v ≠ 0) : V := (⟪u, v⟫ / ∥ v ∥^2) • v lemma proj_on_orthogonal (u : V) {v : V} (H : v ≠ 0) : proj_on u H ⊥ (u - proj_on u H) := ip_proj_on_orthogonal u H lemma norm_proj_on_eq (u : V) {v : V} (H : v ≠ 0) : ∥ proj_on u H ∥ = abs ⟪u, v⟫ / ∥ v ∥ := ip_norm_proj_on_eq u H lemma norm_squared_pythagorean (u : V) {v : V} (H : v ≠ 0) : ∥ u ∥^2 = ∥ u - proj_on u H ∥^2 + ∥ proj_on u H ∥^2 := ip_norm_squared_pythagorean u H lemma norm_proj_on_le (u : V) {v : V} (H : v ≠ 0) : ∥ proj_on u H ∥ ≤ ∥ u ∥ := ip_norm_proj_on_le u H theorem cauchy_schwartz (u v : V) : abs ⟪u, v⟫ ≤ ∥ u ∥ * ∥ v ∥ := ip_cauchy_schwartz u v theorem cauchy_schwartz' (u v : V) : ⟪u, v⟫ ≤ ∥ u ∥ * ∥ v ∥ := ip_cauchy_schwartz' u v theorem eq_proj_on_cauchy_schwartz {u v : V} (H : v ≠ 0) (H₁ : abs ⟪u, v⟫ = ∥ u ∥ * ∥ v ∥) : u = proj_on u H := have ∥ v ∥ ≠ 0, from assume H', H ((normed_space_core.norm_eq_zero_iff _).1 H'), have ∥ u ∥ = ∥ proj_on u H ∥, by rw [norm_proj_on_eq, H₁, mul_div_cancel _ this], have ∥ u - proj_on u H ∥^2 + ∥ u ∥^2 = 0 + ∥ u ∥^2, begin rw zero_add, convert (norm_squared_pythagorean u H).symm end, have ∥ u - proj_on u H ∥^2 = 0, from eq_of_add_eq_add_right this, show u = proj_on u H, begin rw pow_two at this, exact eq_of_sub_eq_zero ((normed_space_core.norm_eq_zero_iff _).1 ((or_self _).1 (mul_eq_zero.1 this))) end /- Instances of real_inner_product_space -/ instance real : real_inner_product_space ℝ := { real_inner_product_space . inner := (*), inner_add_left := add_mul, inner_smul_left := mul_assoc, inner_comm := mul_comm, inner_self_nonneg := mul_self_nonneg, eq_zero_of_inner_self_eq_zero := by apply eq_zero_of_mul_self_eq_zero, } -- TODO: move @[simp] lemma real.ring_add (x y : ℝ) : ring.add x y = x + y := rfl @[simp] lemma real.no_zero_divisors_mul (x y : ℝ) : no_zero_divisors.mul x y = x * y := rfl set_option pp.notation false instance prod {V : Type*} [real_inner_product_space V] {W : Type*} [real_inner_product_space W]: real_inner_product_space (V × W):= { inner := λ x y, ⟪x.1,y.1⟫ + ⟪x.2,y.2⟫, inner_add_left := begin intros u v w, dsimp [inner_add_left], let H1 := @inner_add_left V _ u.fst v.fst w.fst, let H2 := @inner_add_left W _ u.snd v.snd w.snd, unfold add_group.add, unfold add_comm_group.add, unfold add_comm_semigroup.add, unfold add_semigroup.add, simp [H1, H2] --TODO: why so complicated? end, inner_smul_left := begin simp [inner_smul_left, mul_add], end, inner_comm := by simp [inner_comm], inner_self_nonneg := by intros; exact add_nonneg (inner_self_nonneg _) (inner_self_nonneg _), eq_zero_of_inner_self_eq_zero := begin intros x hx, apply prod.eq_iff_fst_eq_snd_eq.2, dsimp at hx, rw add_eq_zero_iff_eq_zero_and_eq_zero_of_nonneg_of_nonneg (inner_self_nonneg _) (inner_self_nonneg _) at hx, apply and.intro, { apply eq_zero_of_inner_self_eq_zero hx.1 }, { apply eq_zero_of_inner_self_eq_zero hx.2 } end } end real_inner_product_space
42848f823bf93dbdb0680bb935f9d5951fe15076
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/root.lean
a443a627d07c093a9fd5846f848ed24f41f5184e
[ "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
240
lean
import logic constant foo : Prop namespace N1 constant foo : Prop check N1.foo check _root_.foo namespace N2 constant foo : Prop check N1.foo check N1.N2.foo print raw foo print raw _root_.foo end N2 end N1
2c06f0020d71700cbcc9f5e8ac0881fac365c070
e61a235b8468b03aee0120bf26ec615c045005d2
/src/Init/Lean/Meta/LevelDefEq.lean
cc0037bbfe5e8e155eea361eb345555a440d9814
[ "Apache-2.0" ]
permissive
SCKelemen/lean4
140dc63a80539f7c61c8e43e1c174d8500ec3230
e10507e6615ddbef73d67b0b6c7f1e4cecdd82bc
refs/heads/master
1,660,973,595,917
1,590,278,033,000
1,590,278,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,386
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.Meta.Basic namespace Lean namespace Meta private partial def decAux? : Level → MetaM (Option Level) | Level.zero _ => pure none | Level.param _ _ => pure none | Level.mvar mvarId _ => do mctx ← getMCtx; match mctx.getLevelAssignment? mvarId with | some u => decAux? u | none => condM (isReadOnlyLevelMVar mvarId) (pure none) $ do u ← mkFreshLevelMVar; assignLevelMVar mvarId (mkLevelSucc u); pure u | Level.succ u _ => pure u | u => let process (u v : Level) : MetaM (Option Level) := do { u? ← decAux? u; match u? with | none => pure none | some u => do v? ← decAux? v; match v? with | none => pure none | some v => pure $ mkLevelMax u v }; match u with | Level.max u v _ => process u v /- Remark: If `decAux? v` returns `some ...`, then `imax u v` is equivalent to `max u v`. -/ | Level.imax u v _ => process u v | _ => unreachable! partial def decLevel? (u : Level) : MetaM (Option Level) := do mctx ← getMCtx; result? ← decAux? u; match result? with | some v => pure $ some v | none => do modify $ fun s => { s with mctx := mctx }; pure none private def strictOccursMaxAux (lvl : Level) : Level → Bool | Level.max u v _ => strictOccursMaxAux u || strictOccursMaxAux v | u => u != lvl && lvl.occurs u /-- Return true iff `lvl` occurs in `max u_1 ... u_n` and `lvl != u_i` for all `i in [1, n]`. That is, `lvl` is a proper level subterm of some `u_i`. -/ private def strictOccursMax (lvl : Level) : Level → Bool | Level.max u v _ => strictOccursMaxAux lvl u || strictOccursMaxAux lvl v | _ => false /-- `mkMaxArgsDiff mvarId (max u_1 ... (mvar mvarId) ... u_n) v` => `max v u_1 ... u_n` -/ private def mkMaxArgsDiff (mvarId : MVarId) : Level → Level → Level | Level.max u v _, acc => mkMaxArgsDiff v $ mkMaxArgsDiff u acc | l@(Level.mvar id _), acc => if id != mvarId then mkLevelMax acc l else acc | l, acc => mkLevelMax acc l /-- Solve `?m =?= max ?m v` by creating a fresh metavariable `?n` and assigning `?m := max ?n v` -/ private def solveSelfMax (mvarId : MVarId) (v : Level) : MetaM Unit := do n ← mkFreshLevelMVar; assignLevelMVar mvarId $ mkMaxArgsDiff mvarId v n private def postponeIsLevelDefEq (lhs : Level) (rhs : Level) : MetaM Unit := modify $ fun s => { s with postponed := s.postponed.push { lhs := lhs, rhs := rhs } } inductive LevelConstraintKind | mvarEq -- ?m =?= l where ?m does not occur in l | mvarEqSelfMax -- ?m =?= max ?m l where ?m does not occur in l | other private def getLevelConstraintKind (u v : Level) : MetaM LevelConstraintKind := match u with | Level.mvar mvarId _ => condM (isReadOnlyLevelMVar mvarId) (pure LevelConstraintKind.other) (if !u.occurs v then pure LevelConstraintKind.mvarEq else if !strictOccursMax u v then pure LevelConstraintKind.mvarEqSelfMax else pure LevelConstraintKind.other) | _ => pure LevelConstraintKind.other partial def isLevelDefEqAux : Level → Level → MetaM Bool | Level.succ lhs _, Level.succ rhs _ => isLevelDefEqAux lhs rhs | lhs, rhs => if lhs == rhs then pure true else do trace! `Meta.isLevelDefEq.step (lhs ++ " =?= " ++ rhs); lhs' ← instantiateLevelMVars lhs; let lhs' := lhs'.normalize; rhs' ← instantiateLevelMVars rhs; let rhs' := rhs'.normalize; if lhs != lhs' || rhs != rhs' then isLevelDefEqAux lhs' rhs' else do mctx ← getMCtx; if !mctx.hasAssignableLevelMVar lhs && !mctx.hasAssignableLevelMVar rhs then do ctx ← read; if ctx.config.isDefEqStuckEx && (lhs.isMVar || rhs.isMVar) then do trace! `Meta.isLevelDefEq.stuck (lhs ++ " =?= " ++ rhs); throwEx $ Exception.isLevelDefEqStuck lhs rhs else pure false else do k ← getLevelConstraintKind lhs rhs; match k with | LevelConstraintKind.mvarEq => do assignLevelMVar lhs.mvarId! rhs; pure true | LevelConstraintKind.mvarEqSelfMax => do solveSelfMax lhs.mvarId! rhs; pure true | _ => do k ← getLevelConstraintKind rhs lhs; match k with | LevelConstraintKind.mvarEq => do assignLevelMVar rhs.mvarId! lhs; pure true | LevelConstraintKind.mvarEqSelfMax => do solveSelfMax rhs.mvarId! lhs; pure true | _ => if lhs.isMVar || rhs.isMVar then pure false else let isSuccEq (u v : Level) : MetaM Bool := match u with | Level.succ u _ => do v? ← decLevel? v; match v? with | some v => isLevelDefEqAux u v | none => pure false | _ => pure false; condM (isSuccEq lhs rhs) (pure true) $ condM (isSuccEq rhs lhs) (pure true) $ do postponeIsLevelDefEq lhs rhs; pure true def isListLevelDefEqAux : List Level → List Level → MetaM Bool | [], [] => pure true | u::us, v::vs => isLevelDefEqAux u v <&&> isListLevelDefEqAux us vs | _, _ => pure false private def getNumPostponed : MetaM Nat := do s ← get; pure s.postponed.size private def getResetPostponed : MetaM (PersistentArray PostponedEntry) := do s ← get; let ps := s.postponed; modify $ fun s => { s with postponed := {} }; pure ps private def processPostponedStep : MetaM Bool := traceCtx `Meta.isLevelDefEq.postponed.step $ do ps ← getResetPostponed; ps.foldlM (fun (r : Bool) (p : PostponedEntry) => if r then isLevelDefEqAux p.lhs p.rhs else pure false) true private partial def processPostponedAux : Unit → MetaM Bool | _ => do numPostponed ← getNumPostponed; if numPostponed == 0 then pure true else do trace! `Meta.isLevelDefEq.postponed ("processing #" ++ toString numPostponed ++ " postponed is-def-eq level constraints"); r ← processPostponedStep; if !r then pure r else do numPostponed' ← getNumPostponed; if numPostponed' == 0 then pure true else if numPostponed' < numPostponed then processPostponedAux () else do trace! `Meta.isLevelDefEq.postponed (format "no progress solving pending is-def-eq level constraints"); pure false private def processPostponed : MetaM Bool := do numPostponed ← getNumPostponed; if numPostponed == 0 then pure true else traceCtx `Meta.isLevelDefEq.postponed $ processPostponedAux () def restore (env : Environment) (mctx : MetavarContext) (postponed : PersistentArray PostponedEntry) : MetaM Unit := modify $ fun s => { s with env := env, mctx := mctx, postponed := postponed } /-- `commitWhen x` executes `x` and process all postponed universe level constraints produced by `x`. We keep the modifications only if both return `true`. Remark: postponed universe level constraints must be solved before returning. Otherwise, we don't know whether `x` really succeeded. -/ @[specialize] def commitWhen (x : MetaM Bool) : MetaM Bool := do s ← get; let env := s.env; let mctx := s.mctx; let postponed := s.postponed; modify $ fun s => { s with postponed := {} }; catch (condM x (condM processPostponed (pure true) (do restore env mctx postponed; pure false)) (do restore env mctx postponed; pure false)) (fun ex => do restore env mctx postponed; throw ex) /- Public interface -/ def isLevelDefEq (u v : Level) : MetaM Bool := traceCtx `Meta.isLevelDefEq $ do b ← commitWhen $ isLevelDefEqAux u v; trace! `Meta.isLevelDefEq (u ++ " =?= " ++ v ++ " ... " ++ if b then "success" else "failure"); pure b def isExprDefEq (t s : Expr) : MetaM Bool := traceCtx `Meta.isDefEq $ do b ← commitWhen $ isExprDefEqAux t s; trace! `Meta.isDefEq (t ++ " =?= " ++ s ++ " ... " ++ if b then "success" else "failure"); pure b abbrev isDefEq := @isExprDefEq @[init] private def regTraceClasses : IO Unit := do registerTraceClass `Meta.isLevelDefEq; registerTraceClass `Meta.isLevelDefEq.step; registerTraceClass `Meta.isLevelDefEq.postponed end Meta end Lean
26ffa20f1515e7f7f3e0e706bb928747f69b9ad7
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/list/chain.lean
05e77e86c9f139865263bed0d4f67d222744b613
[ "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
14,719
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kenny Lau, Yury Kudryashov -/ import data.list.pairwise import logic.relation /-! # Relation chain This file provides basic results about `list.chain` (definition in `data.list.defs`). A list `[a₂, ..., aₙ]` is a `chain` starting at `a₁` with respect to the relation `r` if `r a₁ a₂` and `r a₂ a₃` and ... and `r aₙ₋₁ aₙ`. We write it `chain r a₁ [a₂, ..., aₙ]`. A graph-specialized version is in development and will hopefully be added under `combinatorics.` sometime soon. -/ universes u v open nat namespace list variables {α : Type u} {β : Type v} {R r : α → α → Prop} {l l₁ l₂ : list α} {a b : α} mk_iff_of_inductive_prop list.chain list.chain_iff theorem rel_of_chain_cons {a b : α} {l : list α} (p : chain R a (b :: l)) : R a b := (chain_cons.1 p).1 theorem chain_of_chain_cons {a b : α} {l : list α} (p : chain R a (b :: l)) : chain R b l := (chain_cons.1 p).2 theorem chain.imp' {S : α → α → Prop} (HRS : ∀ ⦃a b⦄, R a b → S a b) {a b : α} (Hab : ∀ ⦃c⦄, R a c → S b c) {l : list α} (p : chain R a l) : chain S b l := by induction p with _ a c l r p IH generalizing b; constructor; [exact Hab r, exact IH (@HRS _)] theorem chain.imp {S : α → α → Prop} (H : ∀ a b, R a b → S a b) {a : α} {l : list α} (p : chain R a l) : chain S a l := p.imp' H (H a) theorem chain.iff {S : α → α → Prop} (H : ∀ a b, R a b ↔ S a b) {a : α} {l : list α} : chain R a l ↔ chain S a l := ⟨chain.imp (λ a b, (H a b).1), chain.imp (λ a b, (H a b).2)⟩ theorem chain.iff_mem {a : α} {l : list α} : chain R a l ↔ chain (λ x y, x ∈ a :: l ∧ y ∈ l ∧ R x y) a l := ⟨λ p, by induction p with _ a b l r p IH; constructor; [exact ⟨mem_cons_self _ _, mem_cons_self _ _, r⟩, exact IH.imp (λ a b ⟨am, bm, h⟩, ⟨mem_cons_of_mem _ am, mem_cons_of_mem _ bm, h⟩)], chain.imp (λ a b h, h.2.2)⟩ theorem chain_singleton {a b : α} : chain R a [b] ↔ R a b := by simp only [chain_cons, chain.nil, and_true] theorem chain_split {a b : α} {l₁ l₂ : list α} : chain R a (l₁ ++ b :: l₂) ↔ chain R a (l₁ ++ [b]) ∧ chain R b l₂ := by induction l₁ with x l₁ IH generalizing a; simp only [*, nil_append, cons_append, chain.nil, chain_cons, and_true, and_assoc] @[simp] theorem chain_append_cons_cons {a b c : α} {l₁ l₂ : list α} : chain R a (l₁ ++ b :: c :: l₂) ↔ chain R a (l₁ ++ [b]) ∧ R b c ∧ chain R c l₂ := by rw [chain_split, chain_cons] theorem chain_iff_forall₂ : ∀ {a : α} {l : list α}, chain R a l ↔ l = [] ∨ forall₂ R (a :: init l) l | a [] := by simp | a [b] := by simp [init] | a (b :: c :: l) := by simp [@chain_iff_forall₂ b] theorem chain_append_singleton_iff_forall₂ : chain R a (l ++ [b]) ↔ forall₂ R (a :: l) (l ++ [b]) := by simp [chain_iff_forall₂, init] theorem chain_map (f : β → α) {b : β} {l : list β} : chain R (f b) (map f l) ↔ chain (λ a b : β, R (f a) (f b)) b l := by induction l generalizing b; simp only [map, chain.nil, chain_cons, *] theorem chain_of_chain_map {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, S (f a) (f b) → R a b) {a : α} {l : list α} (p : chain S (f a) (map f l)) : chain R a l := ((chain_map f).1 p).imp H theorem chain_map_of_chain {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, R a b → S (f a) (f b)) {a : α} {l : list α} (p : chain R a l) : chain S (f a) (map f l) := (chain_map f).2 $ p.imp H theorem chain_pmap_of_chain {S : β → β → Prop} {p : α → Prop} {f : Π a, p a → β} (H : ∀ a b ha hb, R a b → S (f a ha) (f b hb)) {a : α} {l : list α} (hl₁ : chain R a l) (ha : p a) (hl₂ : ∀ a ∈ l, p a) : chain S (f a ha) (list.pmap f l hl₂) := begin induction l with lh lt l_ih generalizing a, { simp }, { simp [H _ _ _ _ (rel_of_chain_cons hl₁), l_ih _ (chain_of_chain_cons hl₁)] } end theorem chain_of_chain_pmap {S : β → β → Prop} {p : α → Prop} (f : Π a, p a → β) {l : list α} (hl₁ : ∀ a ∈ l, p a) {a : α} (ha : p a) (hl₂ : chain S (f a ha) (list.pmap f l hl₁)) (H : ∀ a b ha hb, S (f a ha) (f b hb) → R a b) : chain R a l := begin induction l with lh lt l_ih generalizing a, { simp }, { simp [H _ _ _ _ (rel_of_chain_cons hl₂), l_ih _ _ (chain_of_chain_cons hl₂)] } end protected lemma pairwise.chain (p : pairwise R (a :: l)) : chain R a l := begin cases pairwise_cons.1 p with r p', clear p, induction p' with b l r' p IH generalizing a, {exact chain.nil}, simp only [chain_cons, forall_mem_cons] at r, exact chain_cons.2 ⟨r.1, IH r'⟩ end protected lemma chain.pairwise [is_trans α R] : ∀ {a : α} {l : list α}, chain R a l → pairwise R (a :: l) | a [] chain.nil := pairwise_singleton _ _ | a _ (@chain.cons _ _ _ b l h hb) := hb.pairwise.cons begin simp only [mem_cons_iff, forall_eq_or_imp, h, true_and], exact λ c hc, trans h (rel_of_pairwise_cons hb.pairwise hc), end theorem chain_iff_pairwise [is_trans α R] {a : α} {l : list α} : chain R a l ↔ pairwise R (a :: l) := ⟨chain.pairwise, pairwise.chain⟩ protected lemma chain.sublist [is_trans α R] (hl : l₂.chain R a) (h : l₁ <+ l₂) : l₁.chain R a := by { rw chain_iff_pairwise at ⊢ hl, exact hl.sublist (h.cons_cons a) } protected lemma chain.rel [is_trans α R] (hl : l.chain R a) (hb : b ∈ l) : R a b := by { rw chain_iff_pairwise at hl, exact rel_of_pairwise_cons hl hb } theorem chain_iff_nth_le {R} : ∀ {a : α} {l : list α}, chain R a l ↔ (∀ h : 0 < length l, R a (nth_le l 0 h)) ∧ (∀ i (h : i < length l - 1), R (nth_le l i (lt_of_lt_pred h)) (nth_le l (i+1) (lt_pred_iff.mp h))) | a [] := by simp | a (b :: t) := begin rw [chain_cons, chain_iff_nth_le], split, { rintro ⟨R, ⟨h0, h⟩⟩, split, { intro w, exact R }, intros i w, cases i, { apply h0 }, convert h i _ using 1, simp only [succ_eq_add_one, add_succ_sub_one, add_zero, length, add_lt_add_iff_right] at w, exact lt_pred_iff.mpr w, }, rintro ⟨h0, h⟩, split, { apply h0, simp, }, split, { apply h 0, }, intros i w, convert h (i+1) _ using 1, exact lt_pred_iff.mp w, end theorem chain'.imp {S : α → α → Prop} (H : ∀ a b, R a b → S a b) {l : list α} (p : chain' R l) : chain' S l := by cases l; [trivial, exact p.imp H] theorem chain'.iff {S : α → α → Prop} (H : ∀ a b, R a b ↔ S a b) {l : list α} : chain' R l ↔ chain' S l := ⟨chain'.imp (λ a b, (H a b).1), chain'.imp (λ a b, (H a b).2)⟩ theorem chain'.iff_mem : ∀ {l : list α}, chain' R l ↔ chain' (λ x y, x ∈ l ∧ y ∈ l ∧ R x y) l | [] := iff.rfl | (x :: l) := ⟨λ h, (chain.iff_mem.1 h).imp $ λ a b ⟨h₁, h₂, h₃⟩, ⟨h₁, or.inr h₂, h₃⟩, chain'.imp $ λ a b h, h.2.2⟩ @[simp] theorem chain'_nil : chain' R [] := trivial @[simp] theorem chain'_singleton (a : α) : chain' R [a] := chain.nil @[simp] theorem chain'_cons {x y l} : chain' R (x :: y :: l) ↔ R x y ∧ chain' R (y :: l) := chain_cons theorem chain'_split {a : α} : ∀ {l₁ l₂ : list α}, chain' R (l₁ ++ a :: l₂) ↔ chain' R (l₁ ++ [a]) ∧ chain' R (a :: l₂) | [] l₂ := (and_iff_right (chain'_singleton a)).symm | (b :: l₁) l₂ := chain_split @[simp] theorem chain'_append_cons_cons {b c : α} {l₁ l₂ : list α} : chain' R (l₁ ++ b :: c :: l₂) ↔ chain' R (l₁ ++ [b]) ∧ R b c ∧ chain' R (c :: l₂) := by rw [chain'_split, chain'_cons] theorem chain'_map (f : β → α) {l : list β} : chain' R (map f l) ↔ chain' (λ a b : β, R (f a) (f b)) l := by cases l; [refl, exact chain_map _] theorem chain'_of_chain'_map {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, S (f a) (f b) → R a b) {l : list α} (p : chain' S (map f l)) : chain' R l := ((chain'_map f).1 p).imp H theorem chain'_map_of_chain' {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, R a b → S (f a) (f b)) {l : list α} (p : chain' R l) : chain' S (map f l) := (chain'_map f).2 $ p.imp H theorem pairwise.chain' : ∀ {l : list α}, pairwise R l → chain' R l | [] _ := trivial | (a :: l) h := pairwise.chain h theorem chain'_iff_pairwise [is_trans α R] : ∀ {l : list α}, chain' R l ↔ pairwise R l | [] := (iff_true_intro pairwise.nil).symm | (a :: l) := chain_iff_pairwise protected lemma chain'.sublist [is_trans α R] (hl : l₂.chain' R) (h : l₁ <+ l₂) : l₁.chain' R := by { rw chain'_iff_pairwise at ⊢ hl, exact hl.sublist h } theorem chain'.cons {x y l} (h₁ : R x y) (h₂ : chain' R (y :: l)) : chain' R (x :: y :: l) := chain'_cons.2 ⟨h₁, h₂⟩ theorem chain'.tail : ∀ {l} (h : chain' R l), chain' R l.tail | [] _ := trivial | [x] _ := trivial | (x :: y :: l) h := (chain'_cons.mp h).right theorem chain'.rel_head {x y l} (h : chain' R (x :: y :: l)) : R x y := rel_of_chain_cons h theorem chain'.rel_head' {x l} (h : chain' R (x :: l)) ⦃y⦄ (hy : y ∈ head' l) : R x y := by { rw ← cons_head'_tail hy at h, exact h.rel_head } theorem chain'.cons' {x} : ∀ {l : list α}, chain' R l → (∀ y ∈ l.head', R x y) → chain' R (x :: l) | [] _ _ := chain'_singleton x | (a :: l) hl H := hl.cons $ H _ rfl theorem chain'_cons' {x l} : chain' R (x :: l) ↔ (∀ y ∈ head' l, R x y) ∧ chain' R l := ⟨λ h, ⟨h.rel_head', h.tail⟩, λ ⟨h₁, h₂⟩, h₂.cons' h₁⟩ theorem chain'.drop : ∀ (n) {l} (h : chain' R l), chain' R (drop n l) | 0 _ h := h | _ [] _ := by {rw drop_nil, exact chain'_nil} | (n + 1) [a] _ := by {unfold drop, rw drop_nil, exact chain'_nil} | (n + 1) (a :: b :: l) h := chain'.drop n (chain'_cons'.mp h).right theorem chain'.append : ∀ {l₁ l₂ : list α} (h₁ : chain' R l₁) (h₂ : chain' R l₂) (h : ∀ (x ∈ l₁.last') (y ∈ l₂.head'), R x y), chain' R (l₁ ++ l₂) | [] l₂ h₁ h₂ h := h₂ | [a] l₂ h₁ h₂ h := h₂.cons' $ h _ rfl | (a :: b :: l) l₂ h₁ h₂ h := begin simp only [last'] at h, have : chain' R (b :: l) := h₁.tail, exact (this.append h₂ h).cons h₁.rel_head end theorem chain'_pair {x y} : chain' R [x, y] ↔ R x y := by simp only [chain'_singleton, chain'_cons, and_true] theorem chain'.imp_head {x y} (h : ∀ {z}, R x z → R y z) {l} (hl : chain' R (x :: l)) : chain' R (y :: l) := hl.tail.cons' $ λ z hz, h $ hl.rel_head' hz theorem chain'_reverse : ∀ {l}, chain' R (reverse l) ↔ chain' (flip R) l | [] := iff.rfl | [a] := by simp only [chain'_singleton, reverse_singleton] | (a :: b :: l) := by rw [chain'_cons, reverse_cons, reverse_cons, append_assoc, cons_append, nil_append, chain'_split, ← reverse_cons, @chain'_reverse (b :: l), and_comm, chain'_pair, flip] theorem chain'_iff_nth_le {R} : ∀ {l : list α}, chain' R l ↔ ∀ i (h : i < length l - 1), R (nth_le l i (lt_of_lt_pred h)) (nth_le l (i+1) (lt_pred_iff.mp h)) | [] := by simp | [a] := by simp | (a :: b :: t) := begin rw [chain'_cons, chain'_iff_nth_le], split, { rintro ⟨R, h⟩ i w, cases i, { exact R, }, { convert h i _ using 1, simp only [succ_eq_add_one, add_succ_sub_one, add_zero, length, add_lt_add_iff_right] at w, simpa using w, } }, { rintro h, split, { apply h 0, simp, }, { intros i w, convert h (i+1) _ using 1, simp only [add_zero, length, add_succ_sub_one] at w, simpa using w, } }, end /-- If `l₁ l₂` and `l₃` are lists and `l₁ ++ l₂` and `l₂ ++ l₃` both satisfy `chain' R`, then so does `l₁ ++ l₂ ++ l₃` provided `l₂ ≠ []` -/ lemma chain'.append_overlap : ∀ {l₁ l₂ l₃ : list α} (h₁ : chain' R (l₁ ++ l₂)) (h₂ : chain' R (l₂ ++ l₃)) (hn : l₂ ≠ []), chain' R (l₁ ++ l₂ ++ l₃) | [] l₂ l₃ h₁ h₂ hn := h₂ | l₁ [] l₃ h₁ h₂ hn := (hn rfl).elim | [a] (b :: l₂) l₃ h₁ h₂ hn := by { simp at *, tauto } | (a :: b :: l₁) (c :: l₂) l₃ h₁ h₂ hn := begin simp only [cons_append, chain'_cons] at h₁ h₂ ⊢, simp only [← cons_append] at h₁ h₂ ⊢, exact ⟨h₁.1, chain'.append_overlap h₁.2 h₂ (cons_ne_nil _ _)⟩ end /-- If `a` and `b` are related by the reflexive transitive closure of `r`, then there is a `r`-chain starting from `a` and ending on `b`. The converse of `relation_refl_trans_gen_of_exists_chain`. -/ lemma exists_chain_of_relation_refl_trans_gen (h : relation.refl_trans_gen r a b) : ∃ l, chain r a l ∧ last (a :: l) (cons_ne_nil _ _) = b := begin apply relation.refl_trans_gen.head_induction_on h, { exact ⟨[], chain.nil, rfl⟩ }, { intros c d e t ih, obtain ⟨l, hl₁, hl₂⟩ := ih, refine ⟨d :: l, chain.cons e hl₁, _⟩, rwa last_cons_cons } end /-- Given a chain from `a` to `b`, and a predicate true at `b`, if `r x y → p y → p x` then the predicate is true everywhere in the chain and at `a`. That is, we can propagate the predicate up the chain. -/ lemma chain.induction (p : α → Prop) (l : list α) (h : chain r a l) (hb : last (a :: l) (cons_ne_nil _ _) = b) (carries : ∀ ⦃x y : α⦄, r x y → p y → p x) (final : p b) : ∀ i ∈ a :: l, p i := begin induction l generalizing a, { cases hb, simp [final] }, { rw chain_cons at h, rintro _ (rfl | _), apply carries h.1 (l_ih h.2 hb _ (or.inl rfl)), apply l_ih h.2 hb _ H } end /-- Given a chain from `a` to `b`, and a predicate true at `b`, if `r x y → p y → p x` then the predicate is true at `a`. That is, we can propagate the predicate all the way up the chain. -/ @[elab_as_eliminator] lemma chain.induction_head (p : α → Prop) (l : list α) (h : chain r a l) (hb : last (a :: l) (cons_ne_nil _ _) = b) (carries : ∀ ⦃x y : α⦄, r x y → p y → p x) (final : p b) : p a := (chain.induction p l h hb carries final) _ (mem_cons_self _ _) /-- If there is an `r`-chain starting from `a` and ending at `b`, then `a` and `b` are related by the reflexive transitive closure of `r`. The converse of `exists_chain_of_relation_refl_trans_gen`. -/ lemma relation_refl_trans_gen_of_exists_chain (l) (hl₁ : chain r a l) (hl₂ : last (a :: l) (cons_ne_nil _ _) = b) : relation.refl_trans_gen r a b := chain.induction_head _ l hl₁ hl₂ (λ x y, relation.refl_trans_gen.head) relation.refl_trans_gen.refl end list
150791786b517ae2089f890fbdea752df387c3fe
d0664585e88edfefe384f2b01de54487029040bb
/src/uniform_structure/covers.lean
b5f85228b08d1c0aa3f1a487420813e07b35454b
[]
no_license
ImperialCollegeLondon/uniform-structures
acf0a092d764925564595c59e7347e066d2a78ab
a41a170ef125b36bdac1e2201f54affa958d0349
refs/heads/master
1,668,088,958,039
1,592,495,127,000
1,592,495,127,000
269,964,470
2
0
null
null
null
null
UTF-8
Lean
false
false
2,338
lean
import tactic import data.set.basic open set /-- a cover of X is a set of subsets of X whose union is X -/ structure cover (X : Type) := (C : set (set X)) (cov : ∀ x : X, ∃ U ∈ C, x ∈ U) -- note that the subset X of X isn't called X! X is a type. The subset X of X -- is called `univ` /-- The cover {X} of X -/ def univ_cover (X : Type) : cover X := { C := {univ}, cov := by simp} -- proof it's a cover is obvious and `simp` finds it variable {X : Type} -- definition of star refinement def star_ref (P : cover X) (Q : cover X) := ∀ A ∈ P.C, ∃ U ∈ Q.C, ∀ B ∈ P.C, A ∩ B ≠ ∅ → B ⊆ U -- this may or may not work, Lean might get confused because `<` means something else notation P ` <* ` Q := star_ref P Q theorem star_ref_iff (P : cover X) (Q : cover X) : P <* Q ↔ ∀ A ∈ P.C, ∃ U ∈ Q.C, ∀ B ∈ P.C, A ∩ B ≠ ∅ → B ⊆ U := iff.rfl /- {X} is a uniform cover (i.e. {X} ∈ Θ). If P <* Q and P is a uniform cover, then Q is also a uniform cover. If P and Q are uniform covers, then there is a uniform cover R that star-refines both P and Q. Given a point x and a uniform cover P, one can consider the union of the members of P that contain x as a typical neighbourhood of x of "size" P, and this intuitive measure applies uniformly over the space. Given a uniform space in the entourage sense, define a cover P to be uniform if there is some entourage U such that for each x ∈ X, there is an A ∈ P such that U[x] ⊆ A. These uniform covers form a uniform space as in the second definition. Conversely, given a uniform space in the uniform cover sense, the supersets of ⋃{A × A : A ∈ P}, as P ranges over the uniform covers, are the entourages for a uniform space as in the first definition. Moreover, these two transformations are inverses of each other. -/ /-- A distinguished family of covers for a set X is a filter for <* -/ structure dist_covers (X : Type) := -- collection of covers (Θ : set (cover X) ) -- {X} is in Θ (univ_mem : univ_cover X ∈ Θ) -- if P is in Θ and P <* Q then Q is in Θ (star_mem (P Q : cover X) (hP : P ∈ Θ) (hPQ : P <* Q) : Q ∈ Θ) -- if P, Q ∈ Θ then there exists R ∈ Θ with P <* R and Q <* R (ub_mem (P Q : cover X) (hP : P ∈ Θ) (hQ : Q ∈ Θ) : ∃ R : cover X, R ∈ Θ ∧ R <* P ∧ R <* Q)
2cfe2ba4924d53b1ddd99b716aa0f3a598a60a41
5d166a16ae129621cb54ca9dde86c275d7d2b483
/tests/lean/run/destruct.lean
1763337ec39f7a4ec4ed5cd3df224de2ff1c4c98
[ "Apache-2.0" ]
permissive
jcarlson23/lean
b00098763291397e0ac76b37a2dd96bc013bd247
8de88701247f54d325edd46c0eed57aeacb64baf
refs/heads/master
1,611,571,813,719
1,497,020,963,000
1,497,021,515,000
93,882,536
1
0
null
1,497,029,896,000
1,497,029,896,000
null
UTF-8
Lean
false
false
946
lean
universe variables u inductive Vec (α : Type u) : nat → Type (max 1 u) | nil : Vec 0 | cons : ∀ {n}, α → Vec n → Vec (nat.succ n) lemma split {α : Type u} {n : nat} (v : Vec α n) : (v == (Vec.nil α) ∧ n = 0) ∨ ∃ m h (t : Vec α m), v == Vec.cons h t ∧ n = nat.succ m := Vec.cases_on v (or.inl ⟨heq.refl _, rfl⟩) (λ n h t, or.inr ⟨n, h, t, heq.refl _, rfl⟩) constant f {α : Type u} {n : nat} : Vec α n → nat axiom fax1 (α : Type u) : f (Vec.nil α) = 0 axiom fax2 {α : Type u} {n : nat} (v : Vec α (nat.succ n)) : f v = 1 example {α : Type u} {n : nat} (v : Vec α n) : f v ≠ 2 := begin destruct v, {intros, intro, note h := fax1 α, cc}, intros n1 h t, intros, intro, note h := fax2 (Vec.cons h t), cc end open nat example : ∀ n, 0 < n → succ (pred n) = n := begin intro n, destruct n, {dsimp, intros, note h := lt_irrefl 0, cc}, {intros, subst n, dsimp, reflexivity} end
026fbcdc3e5b0fdda4f956699286a95e140c40ac
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/topology/instances/real_vector_space.lean
6ce4f34a597606e4e856840634093e5c074ed167
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
1,477
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import topology.algebra.module import topology.instances.real /-! # Continuous additive maps are `ℝ`-linear In this file we prove that a continuous map `f : E →+ F` between two topological vector spaces over `ℝ` is `ℝ`-linear -/ variables {E : Type*} [add_comm_group E] [module ℝ E] [topological_space E] [has_continuous_smul ℝ E] {F : Type*} [add_comm_group F] [module ℝ F] [topological_space F] [has_continuous_smul ℝ F] [t2_space F] namespace add_monoid_hom /-- A continuous additive map between two vector spaces over `ℝ` is `ℝ`-linear. -/ lemma map_real_smul (f : E →+ F) (hf : continuous f) (c : ℝ) (x : E) : f (c • x) = c • f x := suffices (λ c : ℝ, f (c • x)) = λ c : ℝ, c • f x, from _root_.congr_fun this c, dense_embedding_of_rat.dense.equalizer (hf.comp $ continuous_id.smul continuous_const) (continuous_id.smul continuous_const) (funext $ λ r, f.map_rat_cast_smul r x) /-- Reinterpret a continuous additive homomorphism between two real vector spaces as a continuous real-linear map. -/ def to_real_linear_map (f : E →+ F) (hf : continuous f) : E →L[ℝ] F := ⟨⟨f, f.map_add, f.map_real_smul hf⟩, hf⟩ @[simp] lemma coe_to_real_linear_map (f : E →+ F) (hf : continuous f) : ⇑(f.to_real_linear_map hf) = f := rfl end add_monoid_hom
c59f11722a1bd247425367855900e8de394232f8
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/stage0/src/Init/Data/Format/Syntax.lean
bda8e9ae8458b35c59800420930f566f84712ada
[ "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
1,814
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import Init.Data.Format.Macro import Init.Data.Format.Instances import Init.Meta namespace Lean.Syntax open Std open Std.Format private def formatInfo (showInfo : Bool) (info : SourceInfo) (f : Format) : Format := match showInfo, info with | true, SourceInfo.original lead pos trail endPos => f!"{lead}:{f}:{pos}:{trail}:{endPos}" | true, SourceInfo.synthetic pos endPos => f!"{pos}:{f}:{endPos}" | _, _ => f partial def formatStxAux (maxDepth : Option Nat) (showInfo : Bool) : Nat → Syntax → Format | _, atom info val => formatInfo showInfo info $ format (repr val) | _, ident info _ val pre => formatInfo showInfo info $ format "`" ++ format val | _, missing => "<missing>" | depth, node kind args => let depth := depth + 1; if kind == nullKind then sbracket $ if args.size > 0 && depth > maxDepth.getD depth then ".." else joinSep (args.toList.map (formatStxAux maxDepth showInfo depth)) line else let shorterName := kind.replacePrefix `Lean.Parser Name.anonymous; let header := format shorterName; let body : List Format := if args.size > 0 && depth > maxDepth.getD depth then [".."] else args.toList.map (formatStxAux maxDepth showInfo depth); paren $ joinSep (header :: body) line def formatStx (stx : Syntax) (maxDepth : Option Nat := none) (showInfo := false) : Format := formatStxAux maxDepth showInfo 0 stx instance : ToFormat (Syntax) := ⟨formatStx⟩ instance : ToString (Syntax) := ⟨toString ∘ format⟩ end Lean.Syntax
adc98ef77ee82ce687cdab501a683f1f10b74b4f
a6b711a4e8db20755026231f7ed529a9014b2b6d
/ZZ_IGNORE/RAW/predicates.lean
25553939292d0848e89f7bd5d5f4a2bf20fc4f6f
[]
no_license
chaseboettner/cs-dm-1
b67d4a7e86f56bce59d2af115503769749d423b2
80b35f2957ffaa45b8b7a4479a3570a2d6eb4db0
refs/heads/master
1,585,367,603,488
1,536,235,675,000
1,536,235,675,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,105
lean
/- Predicates -/ def isZero (n: nat) := n = 0 ∨ false /- isZero 3 -- 3 = 0 N isZero 1 -- 1 = 0 N isZero 0 -- 0 = 0 Y isZero -1 -- type error -/ /- or.introduction -/ theorem o1 : 0 = 0 ∨ 0 = 1 := or.intro_left (0 = 1) (eq.refl 0) #check (isZero 3) #reduce isZero 3 theorem foo: isZero 0 := or.intro_left false (eq.refl 0) /- Predicates are programs. They take arguments and reduce to propositions about those arguments. These propositions in turn might or might not be true (have proofs.) -/ /- We've seen here a first example of a program in Lean. Let's write another one. How about a program that takes a natural number and returns that number + 1. -/ def inc (n : nat) := n + 1 #reduce inc 3 /- There's another important notation for programs that is incredibly useful, not only here in Lean but in functional programming more generally and now even in languages such as Java and C++. By the way, the highest paid programmers today are those who understand deeply functional programming. Let's look at an alternative notation for inc. We'll call our new version inc'. -/ def inc' := λ n : nat, n + 1 /- The way to pronounce lambda is "a program that takes a parameter ... (of type ...), ... and that returns the value of the expression ..." -/ #reduce inc' 3 /- EXERCISE: Re-write isZero using lambda notation. Call the new program isZero'. -/ def isZero' := λ n, n = 0 #reduce isZero' /- Predicates encode properties. Here the it's a property of a single natural number, namely the property of being equal to zero. For every argument value that has that property, there is a proof, and there are no proofs for any other values. We could even say that there is a set of natural numbers that has this property. It is of course the set, { 0 }. -/ def aSet: set nat := { 0 } #check aSet lemma xyz : aSet = isZero := rfl #reduce aSet /- If you really think about this a predicate such as isZero is very much like a program that takes an argument and returns a proposition that in general will include that argument value as an element. -/
f416ea2f7d36b7d65947406260d21e41d56317b0
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/data/set/intervals/image_preimage.lean
499107c7ad08c34fbd3cd5ca07a607bb8d1c5841
[ "Apache-2.0" ]
permissive
troyjlee/mathlib
e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5
45e7eb8447555247246e3fe91c87066506c14875
refs/heads/master
1,689,248,035,046
1,629,470,528,000
1,629,470,528,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
20,647
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, Patrick Massot -/ import data.set.intervals.basic import data.equiv.mul_add import algebra.pointwise /-! # (Pre)images of intervals In this file we prove a bunch of trivial lemmas like “if we add `a` to all points of `[b, c]`, then we get `[a + b, a + c]`”. For the functions `x ↦ x ± a`, `x ↦ a ± x`, and `x ↦ -x` we prove lemmas about preimages and images of all intervals. We also prove a few lemmas about images under `x ↦ a * x`, `x ↦ x * a` and `x ↦ x⁻¹`. -/ universe u open_locale pointwise namespace set section has_exists_add_of_le /-! The lemmas in this section state that addition maps intervals bijectively. The typeclass `has_exists_add_of_le` is defined specifically to make them work when combined with `ordered_cancel_add_comm_monoid`; the lemmas below therefore apply to all `ordered_add_comm_group`, but also to `ℕ` and `ℝ≥0`, which are not groups. TODO : move as much as possible in this file to the setting of this weaker typeclass. -/ variables {α : Type u} [ordered_cancel_add_comm_monoid α] [has_exists_add_of_le α] (a b d : α) lemma Icc_add_bij : bij_on (+d) (Icc a b) (Icc (a + d) (b + d)) := begin refine ⟨λ _ h, ⟨add_le_add_right h.1 _, add_le_add_right h.2 _⟩, λ _ _ _ _ h, add_right_cancel h, λ _ h, _⟩, obtain ⟨c, rfl⟩ := exists_add_of_le h.1, rw [mem_Icc, add_right_comm, add_le_add_iff_right, add_le_add_iff_right] at h, exact ⟨a + c, h, by rw add_right_comm⟩, end lemma Ioo_add_bij : bij_on (+d) (Ioo a b) (Ioo (a + d) (b + d)) := begin refine ⟨λ _ h, ⟨add_lt_add_right h.1 _, add_lt_add_right h.2 _⟩, λ _ _ _ _ h, add_right_cancel h, λ _ h, _⟩, obtain ⟨c, rfl⟩ := exists_add_of_le h.1.le, rw [mem_Ioo, add_right_comm, add_lt_add_iff_right, add_lt_add_iff_right] at h, exact ⟨a + c, h, by rw add_right_comm⟩, end lemma Ioc_add_bij : bij_on (+d) (Ioc a b) (Ioc (a + d) (b + d)) := begin refine ⟨λ _ h, ⟨add_lt_add_right h.1 _, add_le_add_right h.2 _⟩, λ _ _ _ _ h, add_right_cancel h, λ _ h, _⟩, obtain ⟨c, rfl⟩ := exists_add_of_le h.1.le, rw [mem_Ioc, add_right_comm, add_lt_add_iff_right, add_le_add_iff_right] at h, exact ⟨a + c, h, by rw add_right_comm⟩, end lemma Ico_add_bij : bij_on (+d) (Ico a b) (Ico (a + d) (b + d)) := begin refine ⟨λ _ h, ⟨add_le_add_right h.1 _, add_lt_add_right h.2 _⟩, λ _ _ _ _ h, add_right_cancel h, λ _ h, _⟩, obtain ⟨c, rfl⟩ := exists_add_of_le h.1, rw [mem_Ico, add_right_comm, add_le_add_iff_right, add_lt_add_iff_right] at h, exact ⟨a + c, h, by rw add_right_comm⟩, end lemma Ici_add_bij : bij_on (+d) (Ici a) (Ici (a + d)) := begin refine ⟨λ x h, add_le_add_right (mem_Ici.mp h) _, λ _ _ _ _ h, add_right_cancel h, λ _ h, _⟩, obtain ⟨c, rfl⟩ := exists_add_of_le (mem_Ici.mp h), rw [mem_Ici, add_right_comm, add_le_add_iff_right] at h, exact ⟨a + c, h, by rw add_right_comm⟩, end lemma Ioi_add_bij : bij_on (+d) (Ioi a) (Ioi (a + d)) := begin refine ⟨λ x h, add_lt_add_right (mem_Ioi.mp h) _, λ _ _ _ _ h, add_right_cancel h, λ _ h, _⟩, obtain ⟨c, rfl⟩ := exists_add_of_le (mem_Ioi.mp h).le, rw [mem_Ioi, add_right_comm, add_lt_add_iff_right] at h, exact ⟨a + c, h, by rw add_right_comm⟩, end end has_exists_add_of_le section ordered_add_comm_group variables {G : Type u} [ordered_add_comm_group G] (a b c : G) /-! ### Preimages under `x ↦ a + x` -/ @[simp] lemma preimage_const_add_Ici : (λ x, a + x) ⁻¹' (Ici b) = Ici (b - a) := ext $ λ x, sub_le_iff_le_add'.symm @[simp] lemma preimage_const_add_Ioi : (λ x, a + x) ⁻¹' (Ioi b) = Ioi (b - a) := ext $ λ x, sub_lt_iff_lt_add'.symm @[simp] lemma preimage_const_add_Iic : (λ x, a + x) ⁻¹' (Iic b) = Iic (b - a) := ext $ λ x, le_sub_iff_add_le'.symm @[simp] lemma preimage_const_add_Iio : (λ x, a + x) ⁻¹' (Iio b) = Iio (b - a) := ext $ λ x, lt_sub_iff_add_lt'.symm @[simp] lemma preimage_const_add_Icc : (λ x, a + x) ⁻¹' (Icc b c) = Icc (b - a) (c - a) := by simp [← Ici_inter_Iic] @[simp] lemma preimage_const_add_Ico : (λ x, a + x) ⁻¹' (Ico b c) = Ico (b - a) (c - a) := by simp [← Ici_inter_Iio] @[simp] lemma preimage_const_add_Ioc : (λ x, a + x) ⁻¹' (Ioc b c) = Ioc (b - a) (c - a) := by simp [← Ioi_inter_Iic] @[simp] lemma preimage_const_add_Ioo : (λ x, a + x) ⁻¹' (Ioo b c) = Ioo (b - a) (c - a) := by simp [← Ioi_inter_Iio] /-! ### Preimages under `x ↦ x + a` -/ @[simp] lemma preimage_add_const_Ici : (λ x, x + a) ⁻¹' (Ici b) = Ici (b - a) := ext $ λ x, sub_le_iff_le_add.symm @[simp] lemma preimage_add_const_Ioi : (λ x, x + a) ⁻¹' (Ioi b) = Ioi (b - a) := ext $ λ x, sub_lt_iff_lt_add.symm @[simp] lemma preimage_add_const_Iic : (λ x, x + a) ⁻¹' (Iic b) = Iic (b - a) := ext $ λ x, le_sub_iff_add_le.symm @[simp] lemma preimage_add_const_Iio : (λ x, x + a) ⁻¹' (Iio b) = Iio (b - a) := ext $ λ x, lt_sub_iff_add_lt.symm @[simp] lemma preimage_add_const_Icc : (λ x, x + a) ⁻¹' (Icc b c) = Icc (b - a) (c - a) := by simp [← Ici_inter_Iic] @[simp] lemma preimage_add_const_Ico : (λ x, x + a) ⁻¹' (Ico b c) = Ico (b - a) (c - a) := by simp [← Ici_inter_Iio] @[simp] lemma preimage_add_const_Ioc : (λ x, x + a) ⁻¹' (Ioc b c) = Ioc (b - a) (c - a) := by simp [← Ioi_inter_Iic] @[simp] lemma preimage_add_const_Ioo : (λ x, x + a) ⁻¹' (Ioo b c) = Ioo (b - a) (c - a) := by simp [← Ioi_inter_Iio] /-! ### Preimages under `x ↦ -x` -/ @[simp] lemma preimage_neg_Ici : - Ici a = Iic (-a) := ext $ λ x, le_neg @[simp] lemma preimage_neg_Iic : - Iic a = Ici (-a) := ext $ λ x, neg_le @[simp] lemma preimage_neg_Ioi : - Ioi a = Iio (-a) := ext $ λ x, lt_neg @[simp] lemma preimage_neg_Iio : - Iio a = Ioi (-a) := ext $ λ x, neg_lt @[simp] lemma preimage_neg_Icc : - Icc a b = Icc (-b) (-a) := by simp [← Ici_inter_Iic, inter_comm] @[simp] lemma preimage_neg_Ico : - Ico a b = Ioc (-b) (-a) := by simp [← Ici_inter_Iio, ← Ioi_inter_Iic, inter_comm] @[simp] lemma preimage_neg_Ioc : - Ioc a b = Ico (-b) (-a) := by simp [← Ioi_inter_Iic, ← Ici_inter_Iio, inter_comm] @[simp] lemma preimage_neg_Ioo : - Ioo a b = Ioo (-b) (-a) := by simp [← Ioi_inter_Iio, inter_comm] /-! ### Preimages under `x ↦ x - a` -/ @[simp] lemma preimage_sub_const_Ici : (λ x, x - a) ⁻¹' (Ici b) = Ici (b + a) := by simp [sub_eq_add_neg] @[simp] lemma preimage_sub_const_Ioi : (λ x, x - a) ⁻¹' (Ioi b) = Ioi (b + a) := by simp [sub_eq_add_neg] @[simp] lemma preimage_sub_const_Iic : (λ x, x - a) ⁻¹' (Iic b) = Iic (b + a) := by simp [sub_eq_add_neg] @[simp] lemma preimage_sub_const_Iio : (λ x, x - a) ⁻¹' (Iio b) = Iio (b + a) := by simp [sub_eq_add_neg] @[simp] lemma preimage_sub_const_Icc : (λ x, x - a) ⁻¹' (Icc b c) = Icc (b + a) (c + a) := by simp [sub_eq_add_neg] @[simp] lemma preimage_sub_const_Ico : (λ x, x - a) ⁻¹' (Ico b c) = Ico (b + a) (c + a) := by simp [sub_eq_add_neg] @[simp] lemma preimage_sub_const_Ioc : (λ x, x - a) ⁻¹' (Ioc b c) = Ioc (b + a) (c + a) := by simp [sub_eq_add_neg] @[simp] lemma preimage_sub_const_Ioo : (λ x, x - a) ⁻¹' (Ioo b c) = Ioo (b + a) (c + a) := by simp [sub_eq_add_neg] /-! ### Preimages under `x ↦ a - x` -/ @[simp] lemma preimage_const_sub_Ici : (λ x, a - x) ⁻¹' (Ici b) = Iic (a - b) := ext $ λ x, le_sub @[simp] lemma preimage_const_sub_Iic : (λ x, a - x) ⁻¹' (Iic b) = Ici (a - b) := ext $ λ x, sub_le @[simp] lemma preimage_const_sub_Ioi : (λ x, a - x) ⁻¹' (Ioi b) = Iio (a - b) := ext $ λ x, lt_sub @[simp] lemma preimage_const_sub_Iio : (λ x, a - x) ⁻¹' (Iio b) = Ioi (a - b) := ext $ λ x, sub_lt @[simp] lemma preimage_const_sub_Icc : (λ x, a - x) ⁻¹' (Icc b c) = Icc (a - c) (a - b) := by simp [← Ici_inter_Iic, inter_comm] @[simp] lemma preimage_const_sub_Ico : (λ x, a - x) ⁻¹' (Ico b c) = Ioc (a - c) (a - b) := by simp [← Ioi_inter_Iic, ← Ici_inter_Iio, inter_comm] @[simp] lemma preimage_const_sub_Ioc : (λ x, a - x) ⁻¹' (Ioc b c) = Ico (a - c) (a - b) := by simp [← Ioi_inter_Iic, ← Ici_inter_Iio, inter_comm] @[simp] lemma preimage_const_sub_Ioo : (λ x, a - x) ⁻¹' (Ioo b c) = Ioo (a - c) (a - b) := by simp [← Ioi_inter_Iio, inter_comm] /-! ### Images under `x ↦ a + x` -/ @[simp] lemma image_const_add_Ici : (λ x, a + x) '' Ici b = Ici (a + b) := by simp [add_comm] @[simp] lemma image_const_add_Iic : (λ x, a + x) '' Iic b = Iic (a + b) := by simp [add_comm] @[simp] lemma image_const_add_Iio : (λ x, a + x) '' Iio b = Iio (a + b) := by simp [add_comm] @[simp] lemma image_const_add_Ioi : (λ x, a + x) '' Ioi b = Ioi (a + b) := by simp [add_comm] @[simp] lemma image_const_add_Icc : (λ x, a + x) '' Icc b c = Icc (a + b) (a + c) := by simp [add_comm] @[simp] lemma image_const_add_Ico : (λ x, a + x) '' Ico b c = Ico (a + b) (a + c) := by simp [add_comm] @[simp] lemma image_const_add_Ioc : (λ x, a + x) '' Ioc b c = Ioc (a + b) (a + c) := by simp [add_comm] @[simp] lemma image_const_add_Ioo : (λ x, a + x) '' Ioo b c = Ioo (a + b) (a + c) := by simp [add_comm] /-! ### Images under `x ↦ x + a` -/ @[simp] lemma image_add_const_Ici : (λ x, x + a) '' Ici b = Ici (b + a) := by simp @[simp] lemma image_add_const_Iic : (λ x, x + a) '' Iic b = Iic (b + a) := by simp @[simp] lemma image_add_const_Iio : (λ x, x + a) '' Iio b = Iio (b + a) := by simp @[simp] lemma image_add_const_Ioi : (λ x, x + a) '' Ioi b = Ioi (b + a) := by simp @[simp] lemma image_add_const_Icc : (λ x, x + a) '' Icc b c = Icc (b + a) (c + a) := by simp @[simp] lemma image_add_const_Ico : (λ x, x + a) '' Ico b c = Ico (b + a) (c + a) := by simp @[simp] lemma image_add_const_Ioc : (λ x, x + a) '' Ioc b c = Ioc (b + a) (c + a) := by simp @[simp] lemma image_add_const_Ioo : (λ x, x + a) '' Ioo b c = Ioo (b + a) (c + a) := by simp /-! ### Images under `x ↦ -x` -/ lemma image_neg_Ici : has_neg.neg '' (Ici a) = Iic (-a) := by simp lemma image_neg_Iic : has_neg.neg '' (Iic a) = Ici (-a) := by simp lemma image_neg_Ioi : has_neg.neg '' (Ioi a) = Iio (-a) := by simp lemma image_neg_Iio : has_neg.neg '' (Iio a) = Ioi (-a) := by simp lemma image_neg_Icc : has_neg.neg '' (Icc a b) = Icc (-b) (-a) := by simp lemma image_neg_Ico : has_neg.neg '' (Ico a b) = Ioc (-b) (-a) := by simp lemma image_neg_Ioc : has_neg.neg '' (Ioc a b) = Ico (-b) (-a) := by simp lemma image_neg_Ioo : has_neg.neg '' (Ioo a b) = Ioo (-b) (-a) := by simp /-! ### Images under `x ↦ a - x` -/ @[simp] lemma image_const_sub_Ici : (λ x, a - x) '' Ici b = Iic (a - b) := by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x)] @[simp] lemma image_const_sub_Iic : (λ x, a - x) '' Iic b = Ici (a - b) := by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x)] @[simp] lemma image_const_sub_Ioi : (λ x, a - x) '' Ioi b = Iio (a - b) := by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x)] @[simp] lemma image_const_sub_Iio : (λ x, a - x) '' Iio b = Ioi (a - b) := by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x)] @[simp] lemma image_const_sub_Icc : (λ x, a - x) '' Icc b c = Icc (a - c) (a - b) := by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x)] @[simp] lemma image_const_sub_Ico : (λ x, a - x) '' Ico b c = Ioc (a - c) (a - b) := by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x)] @[simp] lemma image_const_sub_Ioc : (λ x, a - x) '' Ioc b c = Ico (a - c) (a - b) := by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x)] @[simp] lemma image_const_sub_Ioo : (λ x, a - x) '' Ioo b c = Ioo (a - c) (a - b) := by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x)] /-! ### Images under `x ↦ x - a` -/ @[simp] lemma image_sub_const_Ici : (λ x, x - a) '' Ici b = Ici (b - a) := by simp [sub_eq_neg_add] @[simp] lemma image_sub_const_Iic : (λ x, x - a) '' Iic b = Iic (b - a) := by simp [sub_eq_neg_add] @[simp] lemma image_sub_const_Ioi : (λ x, x - a) '' Ioi b = Ioi (b - a) := by simp [sub_eq_neg_add] @[simp] lemma image_sub_const_Iio : (λ x, x - a) '' Iio b = Iio (b - a) := by simp [sub_eq_neg_add] @[simp] lemma image_sub_const_Icc : (λ x, x - a) '' Icc b c = Icc (b - a) (c - a) := by simp [sub_eq_neg_add] @[simp] lemma image_sub_const_Ico : (λ x, x - a) '' Ico b c = Ico (b - a) (c - a) := by simp [sub_eq_neg_add] @[simp] lemma image_sub_const_Ioc : (λ x, x - a) '' Ioc b c = Ioc (b - a) (c - a) := by simp [sub_eq_neg_add] @[simp] lemma image_sub_const_Ioo : (λ x, x - a) '' Ioo b c = Ioo (b - a) (c - a) := by simp [sub_eq_neg_add] /-! ### Bijections -/ lemma Iic_add_bij : bij_on (+a) (Iic b) (Iic (b + a)) := begin refine ⟨λ x h, add_le_add_right (mem_Iic.mp h) _, λ _ _ _ _ h, add_right_cancel h, λ _ h, _⟩, simpa [add_comm a] using h, end lemma Iio_add_bij : bij_on (+a) (Iio b) (Iio (b + a)) := begin refine ⟨λ x h, add_lt_add_right (mem_Iio.mp h) _, λ _ _ _ _ h, add_right_cancel h, λ _ h, _⟩, simpa [add_comm a] using h, end end ordered_add_comm_group /-! ### Multiplication and inverse in a field -/ section linear_ordered_field variables {k : Type u} [linear_ordered_field k] @[simp] lemma preimage_mul_const_Iio (a : k) {c : k} (h : 0 < c) : (λ x, x * c) ⁻¹' (Iio a) = Iio (a / c) := ext $ λ x, (lt_div_iff h).symm @[simp] lemma preimage_mul_const_Ioi (a : k) {c : k} (h : 0 < c) : (λ x, x * c) ⁻¹' (Ioi a) = Ioi (a / c) := ext $ λ x, (div_lt_iff h).symm @[simp] lemma preimage_mul_const_Iic (a : k) {c : k} (h : 0 < c) : (λ x, x * c) ⁻¹' (Iic a) = Iic (a / c) := ext $ λ x, (le_div_iff h).symm @[simp] lemma preimage_mul_const_Ici (a : k) {c : k} (h : 0 < c) : (λ x, x * c) ⁻¹' (Ici a) = Ici (a / c) := ext $ λ x, (div_le_iff h).symm @[simp] lemma preimage_mul_const_Ioo (a b : k) {c : k} (h : 0 < c) : (λ x, x * c) ⁻¹' (Ioo a b) = Ioo (a / c) (b / c) := by simp [← Ioi_inter_Iio, h] @[simp] lemma preimage_mul_const_Ioc (a b : k) {c : k} (h : 0 < c) : (λ x, x * c) ⁻¹' (Ioc a b) = Ioc (a / c) (b / c) := by simp [← Ioi_inter_Iic, h] @[simp] lemma preimage_mul_const_Ico (a b : k) {c : k} (h : 0 < c) : (λ x, x * c) ⁻¹' (Ico a b) = Ico (a / c) (b / c) := by simp [← Ici_inter_Iio, h] @[simp] lemma preimage_mul_const_Icc (a b : k) {c : k} (h : 0 < c) : (λ x, x * c) ⁻¹' (Icc a b) = Icc (a / c) (b / c) := by simp [← Ici_inter_Iic, h] @[simp] lemma preimage_mul_const_Iio_of_neg (a : k) {c : k} (h : c < 0) : (λ x, x * c) ⁻¹' (Iio a) = Ioi (a / c) := ext $ λ x, (div_lt_iff_of_neg h).symm @[simp] lemma preimage_mul_const_Ioi_of_neg (a : k) {c : k} (h : c < 0) : (λ x, x * c) ⁻¹' (Ioi a) = Iio (a / c) := ext $ λ x, (lt_div_iff_of_neg h).symm @[simp] lemma preimage_mul_const_Iic_of_neg (a : k) {c : k} (h : c < 0) : (λ x, x * c) ⁻¹' (Iic a) = Ici (a / c) := ext $ λ x, (div_le_iff_of_neg h).symm @[simp] lemma preimage_mul_const_Ici_of_neg (a : k) {c : k} (h : c < 0) : (λ x, x * c) ⁻¹' (Ici a) = Iic (a / c) := ext $ λ x, (le_div_iff_of_neg h).symm @[simp] lemma preimage_mul_const_Ioo_of_neg (a b : k) {c : k} (h : c < 0) : (λ x, x * c) ⁻¹' (Ioo a b) = Ioo (b / c) (a / c) := by simp [← Ioi_inter_Iio, h, inter_comm] @[simp] lemma preimage_mul_const_Ioc_of_neg (a b : k) {c : k} (h : c < 0) : (λ x, x * c) ⁻¹' (Ioc a b) = Ico (b / c) (a / c) := by simp [← Ioi_inter_Iic, ← Ici_inter_Iio, h, inter_comm] @[simp] lemma preimage_mul_const_Ico_of_neg (a b : k) {c : k} (h : c < 0) : (λ x, x * c) ⁻¹' (Ico a b) = Ioc (b / c) (a / c) := by simp [← Ici_inter_Iio, ← Ioi_inter_Iic, h, inter_comm] @[simp] lemma preimage_mul_const_Icc_of_neg (a b : k) {c : k} (h : c < 0) : (λ x, x * c) ⁻¹' (Icc a b) = Icc (b / c) (a / c) := by simp [← Ici_inter_Iic, h, inter_comm] @[simp] lemma preimage_const_mul_Iio (a : k) {c : k} (h : 0 < c) : ((*) c) ⁻¹' (Iio a) = Iio (a / c) := ext $ λ x, (lt_div_iff' h).symm @[simp] lemma preimage_const_mul_Ioi (a : k) {c : k} (h : 0 < c) : ((*) c) ⁻¹' (Ioi a) = Ioi (a / c) := ext $ λ x, (div_lt_iff' h).symm @[simp] lemma preimage_const_mul_Iic (a : k) {c : k} (h : 0 < c) : ((*) c) ⁻¹' (Iic a) = Iic (a / c) := ext $ λ x, (le_div_iff' h).symm @[simp] lemma preimage_const_mul_Ici (a : k) {c : k} (h : 0 < c) : ((*) c) ⁻¹' (Ici a) = Ici (a / c) := ext $ λ x, (div_le_iff' h).symm @[simp] lemma preimage_const_mul_Ioo (a b : k) {c : k} (h : 0 < c) : ((*) c) ⁻¹' (Ioo a b) = Ioo (a / c) (b / c) := by simp [← Ioi_inter_Iio, h] @[simp] lemma preimage_const_mul_Ioc (a b : k) {c : k} (h : 0 < c) : ((*) c) ⁻¹' (Ioc a b) = Ioc (a / c) (b / c) := by simp [← Ioi_inter_Iic, h] @[simp] lemma preimage_const_mul_Ico (a b : k) {c : k} (h : 0 < c) : ((*) c) ⁻¹' (Ico a b) = Ico (a / c) (b / c) := by simp [← Ici_inter_Iio, h] @[simp] lemma preimage_const_mul_Icc (a b : k) {c : k} (h : 0 < c) : ((*) c) ⁻¹' (Icc a b) = Icc (a / c) (b / c) := by simp [← Ici_inter_Iic, h] @[simp] lemma preimage_const_mul_Iio_of_neg (a : k) {c : k} (h : c < 0) : ((*) c) ⁻¹' (Iio a) = Ioi (a / c) := by simpa only [mul_comm] using preimage_mul_const_Iio_of_neg a h @[simp] lemma preimage_const_mul_Ioi_of_neg (a : k) {c : k} (h : c < 0) : ((*) c) ⁻¹' (Ioi a) = Iio (a / c) := by simpa only [mul_comm] using preimage_mul_const_Ioi_of_neg a h @[simp] lemma preimage_const_mul_Iic_of_neg (a : k) {c : k} (h : c < 0) : ((*) c) ⁻¹' (Iic a) = Ici (a / c) := by simpa only [mul_comm] using preimage_mul_const_Iic_of_neg a h @[simp] lemma preimage_const_mul_Ici_of_neg (a : k) {c : k} (h : c < 0) : ((*) c) ⁻¹' (Ici a) = Iic (a / c) := by simpa only [mul_comm] using preimage_mul_const_Ici_of_neg a h @[simp] lemma preimage_const_mul_Ioo_of_neg (a b : k) {c : k} (h : c < 0) : ((*) c) ⁻¹' (Ioo a b) = Ioo (b / c) (a / c) := by simpa only [mul_comm] using preimage_mul_const_Ioo_of_neg a b h @[simp] lemma preimage_const_mul_Ioc_of_neg (a b : k) {c : k} (h : c < 0) : ((*) c) ⁻¹' (Ioc a b) = Ico (b / c) (a / c) := by simpa only [mul_comm] using preimage_mul_const_Ioc_of_neg a b h @[simp] lemma preimage_const_mul_Ico_of_neg (a b : k) {c : k} (h : c < 0) : ((*) c) ⁻¹' (Ico a b) = Ioc (b / c) (a / c) := by simpa only [mul_comm] using preimage_mul_const_Ico_of_neg a b h @[simp] lemma preimage_const_mul_Icc_of_neg (a b : k) {c : k} (h : c < 0) : ((*) c) ⁻¹' (Icc a b) = Icc (b / c) (a / c) := by simpa only [mul_comm] using preimage_mul_const_Icc_of_neg a b h lemma image_mul_right_Icc' (a b : k) {c : k} (h : 0 < c) : (λ x, x * c) '' Icc a b = Icc (a * c) (b * c) := ((units.mk0 c h.ne').mul_right.image_eq_preimage _).trans (by simp [h, division_def]) lemma image_mul_right_Icc {a b c : k} (hab : a ≤ b) (hc : 0 ≤ c) : (λ x, x * c) '' Icc a b = Icc (a * c) (b * c) := begin cases eq_or_lt_of_le hc, { subst c, simp [(nonempty_Icc.2 hab).image_const] }, exact image_mul_right_Icc' a b ‹0 < c› end lemma image_mul_left_Icc' {a : k} (h : 0 < a) (b c : k) : ((*) a) '' Icc b c = Icc (a * b) (a * c) := by { convert image_mul_right_Icc' b c h using 1; simp only [mul_comm _ a] } lemma image_mul_left_Icc {a b c : k} (ha : 0 ≤ a) (hbc : b ≤ c) : ((*) a) '' Icc b c = Icc (a * b) (a * c) := by { convert image_mul_right_Icc hbc ha using 1; simp only [mul_comm _ a] } lemma image_mul_right_Ioo (a b : k) {c : k} (h : 0 < c) : (λ x, x * c) '' Ioo a b = Ioo (a * c) (b * c) := ((units.mk0 c h.ne').mul_right.image_eq_preimage _).trans (by simp [h, division_def]) lemma image_mul_left_Ioo {a : k} (h : 0 < a) (b c : k) : ((*) a) '' Ioo b c = Ioo (a * b) (a * c) := by { convert image_mul_right_Ioo b c h using 1; simp only [mul_comm _ a] } /-- The image under `inv` of `Ioo 0 a` is `Ioi a⁻¹`. -/ lemma image_inv_Ioo_0_left {a : k} (ha : 0 < a) : has_inv.inv '' Ioo 0 a = Ioi a⁻¹ := begin ext x, exact ⟨λ ⟨y, ⟨hy0, hya⟩, hyx⟩, hyx ▸ (inv_lt_inv ha hy0).2 hya, λ h, ⟨x⁻¹, ⟨inv_pos.2 (lt_trans (inv_pos.2 ha) h), (inv_lt ha (lt_trans (inv_pos.2 ha) h)).1 h⟩, inv_inv' x⟩⟩, end /-! ### Images under `x ↦ a * x + b` -/ @[simp] lemma image_affine_Icc' {a : k} (h : 0 < a) (b c d : k) : (λ x, a * x + b) '' Icc c d = Icc (a * c + b) (a * d + b) := begin suffices : (λ x, x + b) '' ((λ x, a * x) '' Icc c d) = Icc (a * c + b) (a * d + b), { rwa set.image_image at this, }, rw [image_mul_left_Icc' h, image_add_const_Icc], end end linear_ordered_field end set
3b2a52f1fa9a26f7da9da0de013997d429b5134b
94e33a31faa76775069b071adea97e86e218a8ee
/src/analysis/complex/basic.lean
a3adb83bb01bc6db604e372a32b74c6257458c06
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
14,241
lean
/- Copyright (c) Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import data.complex.determinant import data.complex.is_R_or_C /-! # Normed space structure on `ℂ`. This file gathers basic facts on complex numbers of an analytic nature. ## Main results This file registers `ℂ` as a normed field, expresses basic properties of the norm, and gives tools on the real vector space structure of `ℂ`. Notably, in the namespace `complex`, it defines functions: * `re_clm` * `im_clm` * `of_real_clm` * `conj_cle` They are bundled versions of the real part, the imaginary part, the embedding of `ℝ` in `ℂ`, and the complex conjugate as continuous `ℝ`-linear maps. The last two are also bundled as linear isometries in `of_real_li` and `conj_lie`. We also register the fact that `ℂ` is an `is_R_or_C` field. -/ noncomputable theory namespace complex open_locale complex_conjugate topological_space instance : has_norm ℂ := ⟨abs⟩ @[simp] lemma norm_eq_abs (z : ℂ) : ∥z∥ = abs z := rfl instance : normed_group ℂ := normed_group.of_core ℂ { norm_eq_zero_iff := λ z, abs_eq_zero, triangle := abs_add, norm_neg := abs_neg } instance : normed_field ℂ := { norm := abs, dist_eq := λ _ _, rfl, norm_mul' := abs_mul, .. complex.field, .. complex.normed_group } instance : nondiscrete_normed_field ℂ := { non_trivial := ⟨2, by simp; norm_num⟩ } instance {R : Type*} [normed_field R] [normed_algebra R ℝ] : normed_algebra R ℂ := { norm_smul_le := λ r x, begin rw [norm_eq_abs, norm_eq_abs, ←algebra_map_smul ℝ r x, algebra.smul_def, abs_mul, ←norm_algebra_map' ℝ r, coe_algebra_map, abs_of_real], refl, end, to_algebra := complex.algebra } /-- The module structure from `module.complex_to_real` is a normed space. -/ @[priority 900] -- see Note [lower instance priority] instance _root_.normed_space.complex_to_real {E : Type*} [normed_group E] [normed_space ℂ E] : normed_space ℝ E := normed_space.restrict_scalars ℝ ℂ E lemma dist_eq (z w : ℂ) : dist z w = abs (z - w) := rfl lemma dist_eq_re_im (z w : ℂ) : dist z w = real.sqrt ((z.re - w.re) ^ 2 + (z.im - w.im) ^ 2) := by { rw [sq, sq], refl } @[simp] lemma dist_mk (x₁ y₁ x₂ y₂ : ℝ) : dist (mk x₁ y₁) (mk x₂ y₂) = real.sqrt ((x₁ - x₂) ^ 2 + (y₁ - y₂) ^ 2) := dist_eq_re_im _ _ lemma dist_of_re_eq {z w : ℂ} (h : z.re = w.re) : dist z w = dist z.im w.im := by rw [dist_eq_re_im, h, sub_self, zero_pow two_pos, zero_add, real.sqrt_sq_eq_abs, real.dist_eq] lemma nndist_of_re_eq {z w : ℂ} (h : z.re = w.re) : nndist z w = nndist z.im w.im := nnreal.eq $ dist_of_re_eq h lemma edist_of_re_eq {z w : ℂ} (h : z.re = w.re) : edist z w = edist z.im w.im := by rw [edist_nndist, edist_nndist, nndist_of_re_eq h] lemma dist_of_im_eq {z w : ℂ} (h : z.im = w.im) : dist z w = dist z.re w.re := by rw [dist_eq_re_im, h, sub_self, zero_pow two_pos, add_zero, real.sqrt_sq_eq_abs, real.dist_eq] lemma nndist_of_im_eq {z w : ℂ} (h : z.im = w.im) : nndist z w = nndist z.re w.re := nnreal.eq $ dist_of_im_eq h lemma edist_of_im_eq {z w : ℂ} (h : z.im = w.im) : edist z w = edist z.re w.re := by rw [edist_nndist, edist_nndist, nndist_of_im_eq h] lemma dist_conj_self (z : ℂ) : dist (conj z) z = 2 * |z.im| := by rw [dist_of_re_eq (conj_re z), conj_im, dist_comm, real.dist_eq, sub_neg_eq_add, ← two_mul, _root_.abs_mul, abs_of_pos (@two_pos ℝ _ _)] lemma nndist_conj_self (z : ℂ) : nndist (conj z) z = 2 * real.nnabs z.im := nnreal.eq $ by rw [← dist_nndist, nnreal.coe_mul, nnreal.coe_two, real.coe_nnabs, dist_conj_self] lemma dist_self_conj (z : ℂ) : dist z (conj z) = 2 * |z.im| := by rw [dist_comm, dist_conj_self] lemma nndist_self_conj (z : ℂ) : nndist z (conj z) = 2 * real.nnabs z.im := by rw [nndist_comm, nndist_conj_self] @[simp] lemma comap_abs_nhds_zero : filter.comap abs (𝓝 0) = 𝓝 0 := comap_norm_nhds_zero @[simp] lemma norm_real (r : ℝ) : ∥(r : ℂ)∥ = ∥r∥ := abs_of_real _ @[simp] lemma norm_rat (r : ℚ) : ∥(r : ℂ)∥ = |(r : ℝ)| := by { rw ← of_real_rat_cast, exact norm_real _ } @[simp] lemma norm_nat (n : ℕ) : ∥(n : ℂ)∥ = n := abs_of_nat _ @[simp] lemma norm_int {n : ℤ} : ∥(n : ℂ)∥ = |n| := by simp [← rat.cast_coe_int] {single_pass := tt} lemma norm_int_of_nonneg {n : ℤ} (hn : 0 ≤ n) : ∥(n : ℂ)∥ = n := by simp [hn] @[continuity] lemma continuous_abs : continuous abs := continuous_norm @[continuity] lemma continuous_norm_sq : continuous norm_sq := by simpa [← norm_sq_eq_abs] using continuous_abs.pow 2 @[simp, norm_cast] lemma nnnorm_real (r : ℝ) : ∥(r : ℂ)∥₊ = ∥r∥₊ := subtype.ext $ norm_real r @[simp, norm_cast] lemma nnnorm_nat (n : ℕ) : ∥(n : ℂ)∥₊ = n := subtype.ext $ by simp @[simp, norm_cast] lemma nnnorm_int (n : ℤ) : ∥(n : ℂ)∥₊ = ∥n∥₊ := subtype.ext $ by simp only [coe_nnnorm, norm_int, int.norm_eq_abs] lemma nnnorm_eq_one_of_pow_eq_one {ζ : ℂ} {n : ℕ} (h : ζ ^ n = 1) (hn : n ≠ 0) : ∥ζ∥₊ = 1 := begin refine (@pow_left_inj nnreal _ _ _ _ zero_le' zero_le' hn.bot_lt).mp _, rw [←nnnorm_pow, h, nnnorm_one, one_pow], end lemma norm_eq_one_of_pow_eq_one {ζ : ℂ} {n : ℕ} (h : ζ ^ n = 1) (hn : n ≠ 0) : ∥ζ∥ = 1 := congr_arg coe (nnnorm_eq_one_of_pow_eq_one h hn) /-- The `abs` function on `ℂ` is proper. -/ lemma tendsto_abs_cocompact_at_top : filter.tendsto abs (filter.cocompact ℂ) filter.at_top := tendsto_norm_cocompact_at_top /-- The `norm_sq` function on `ℂ` is proper. -/ lemma tendsto_norm_sq_cocompact_at_top : filter.tendsto norm_sq (filter.cocompact ℂ) filter.at_top := by simpa [mul_self_abs] using tendsto_abs_cocompact_at_top.at_top_mul_at_top tendsto_abs_cocompact_at_top open continuous_linear_map /-- Continuous linear map version of the real part function, from `ℂ` to `ℝ`. -/ def re_clm : ℂ →L[ℝ] ℝ := re_lm.mk_continuous 1 (λ x, by simp [abs_re_le_abs]) @[continuity] lemma continuous_re : continuous re := re_clm.continuous @[simp] lemma re_clm_coe : (coe (re_clm) : ℂ →ₗ[ℝ] ℝ) = re_lm := rfl @[simp] lemma re_clm_apply (z : ℂ) : (re_clm : ℂ → ℝ) z = z.re := rfl @[simp] lemma re_clm_norm : ∥re_clm∥ = 1 := le_antisymm (linear_map.mk_continuous_norm_le _ zero_le_one _) $ calc 1 = ∥re_clm 1∥ : by simp ... ≤ ∥re_clm∥ : unit_le_op_norm _ _ (by simp) @[simp] lemma re_clm_nnnorm : ∥re_clm∥₊ = 1 := subtype.ext re_clm_norm /-- Continuous linear map version of the real part function, from `ℂ` to `ℝ`. -/ def im_clm : ℂ →L[ℝ] ℝ := im_lm.mk_continuous 1 (λ x, by simp [abs_im_le_abs]) @[continuity] lemma continuous_im : continuous im := im_clm.continuous @[simp] lemma im_clm_coe : (coe (im_clm) : ℂ →ₗ[ℝ] ℝ) = im_lm := rfl @[simp] lemma im_clm_apply (z : ℂ) : (im_clm : ℂ → ℝ) z = z.im := rfl @[simp] lemma im_clm_norm : ∥im_clm∥ = 1 := le_antisymm (linear_map.mk_continuous_norm_le _ zero_le_one _) $ calc 1 = ∥im_clm I∥ : by simp ... ≤ ∥im_clm∥ : unit_le_op_norm _ _ (by simp) @[simp] lemma im_clm_nnnorm : ∥im_clm∥₊ = 1 := subtype.ext im_clm_norm lemma restrict_scalars_one_smul_right' {E : Type*} [normed_group E] [normed_space ℂ E] (x : E) : continuous_linear_map.restrict_scalars ℝ ((1 : ℂ →L[ℂ] ℂ).smul_right x : ℂ →L[ℂ] E) = re_clm.smul_right x + I • im_clm.smul_right x := by { ext ⟨a, b⟩, simp [mk_eq_add_mul_I, add_smul, mul_smul, smul_comm I] } lemma restrict_scalars_one_smul_right (x : ℂ) : continuous_linear_map.restrict_scalars ℝ ((1 : ℂ →L[ℂ] ℂ).smul_right x : ℂ →L[ℂ] ℂ) = x • 1 := by { ext1 z, dsimp, apply mul_comm } /-- The complex-conjugation function from `ℂ` to itself is an isometric linear equivalence. -/ def conj_lie : ℂ ≃ₗᵢ[ℝ] ℂ := ⟨conj_ae.to_linear_equiv, abs_conj⟩ @[simp] lemma conj_lie_apply (z : ℂ) : conj_lie z = conj z := rfl @[simp] lemma conj_lie_symm : conj_lie.symm = conj_lie := rfl lemma isometry_conj : isometry (conj : ℂ → ℂ) := conj_lie.isometry @[simp] lemma dist_conj_conj (z w : ℂ) : dist (conj z) (conj w) = dist z w := isometry_conj.dist_eq z w @[simp] lemma nndist_conj_conj (z w : ℂ) : nndist (conj z) (conj w) = nndist z w := isometry_conj.nndist_eq z w lemma dist_conj_comm (z w : ℂ) : dist (conj z) w = dist z (conj w) := by rw [← dist_conj_conj, conj_conj] lemma nndist_conj_comm (z w : ℂ) : nndist (conj z) w = nndist z (conj w) := subtype.ext $ dist_conj_comm _ _ /-- The determinant of `conj_lie`, as a linear map. -/ @[simp] lemma det_conj_lie : (conj_lie.to_linear_equiv : ℂ →ₗ[ℝ] ℂ).det = -1 := det_conj_ae /-- The determinant of `conj_lie`, as a linear equiv. -/ @[simp] lemma linear_equiv_det_conj_lie : conj_lie.to_linear_equiv.det = -1 := linear_equiv_det_conj_ae instance : has_continuous_star ℂ := ⟨conj_lie.continuous⟩ @[continuity] lemma continuous_conj : continuous (conj : ℂ → ℂ) := continuous_star /-- Continuous linear equiv version of the conj function, from `ℂ` to `ℂ`. -/ def conj_cle : ℂ ≃L[ℝ] ℂ := conj_lie @[simp] lemma conj_cle_coe : conj_cle.to_linear_equiv = conj_ae.to_linear_equiv := rfl @[simp] lemma conj_cle_apply (z : ℂ) : conj_cle z = conj z := rfl @[simp] lemma conj_cle_norm : ∥(conj_cle : ℂ →L[ℝ] ℂ)∥ = 1 := conj_lie.to_linear_isometry.norm_to_continuous_linear_map @[simp] lemma conj_cle_nnorm : ∥(conj_cle : ℂ →L[ℝ] ℂ)∥₊ = 1 := subtype.ext conj_cle_norm /-- Linear isometry version of the canonical embedding of `ℝ` in `ℂ`. -/ def of_real_li : ℝ →ₗᵢ[ℝ] ℂ := ⟨of_real_am.to_linear_map, norm_real⟩ lemma isometry_of_real : isometry (coe : ℝ → ℂ) := of_real_li.isometry @[continuity] lemma continuous_of_real : continuous (coe : ℝ → ℂ) := of_real_li.continuous /-- Continuous linear map version of the canonical embedding of `ℝ` in `ℂ`. -/ def of_real_clm : ℝ →L[ℝ] ℂ := of_real_li.to_continuous_linear_map @[simp] lemma of_real_clm_coe : (of_real_clm : ℝ →ₗ[ℝ] ℂ) = of_real_am.to_linear_map := rfl @[simp] lemma of_real_clm_apply (x : ℝ) : of_real_clm x = x := rfl @[simp] lemma of_real_clm_norm : ∥of_real_clm∥ = 1 := of_real_li.norm_to_continuous_linear_map @[simp] lemma of_real_clm_nnnorm : ∥of_real_clm∥₊ = 1 := subtype.ext $ of_real_clm_norm noncomputable instance : is_R_or_C ℂ := { re := ⟨complex.re, complex.zero_re, complex.add_re⟩, im := ⟨complex.im, complex.zero_im, complex.add_im⟩, I := complex.I, I_re_ax := by simp only [add_monoid_hom.coe_mk, complex.I_re], I_mul_I_ax := by simp only [complex.I_mul_I, eq_self_iff_true, or_true], re_add_im_ax := λ z, by simp only [add_monoid_hom.coe_mk, complex.re_add_im, complex.coe_algebra_map, complex.of_real_eq_coe], of_real_re_ax := λ r, by simp only [add_monoid_hom.coe_mk, complex.of_real_re, complex.coe_algebra_map, complex.of_real_eq_coe], of_real_im_ax := λ r, by simp only [add_monoid_hom.coe_mk, complex.of_real_im, complex.coe_algebra_map, complex.of_real_eq_coe], mul_re_ax := λ z w, by simp only [complex.mul_re, add_monoid_hom.coe_mk], mul_im_ax := λ z w, by simp only [add_monoid_hom.coe_mk, complex.mul_im], conj_re_ax := λ z, rfl, conj_im_ax := λ z, rfl, conj_I_ax := by simp only [complex.conj_I, ring_hom.coe_mk], norm_sq_eq_def_ax := λ z, by simp only [←complex.norm_sq_eq_abs, ←complex.norm_sq_apply, add_monoid_hom.coe_mk, complex.norm_eq_abs], mul_im_I_ax := λ z, by simp only [mul_one, add_monoid_hom.coe_mk, complex.I_im], inv_def_ax := λ z, by simp only [complex.inv_def, complex.norm_sq_eq_abs, complex.coe_algebra_map, complex.of_real_eq_coe, complex.norm_eq_abs], div_I_ax := complex.div_I } lemma _root_.is_R_or_C.re_eq_complex_re : ⇑(is_R_or_C.re : ℂ →+ ℝ) = complex.re := rfl lemma _root_.is_R_or_C.im_eq_complex_im : ⇑(is_R_or_C.im : ℂ →+ ℝ) = complex.im := rfl section variables {α β γ : Type*} [add_comm_monoid α] [topological_space α] [add_comm_monoid γ] [topological_space γ] /-- The natural `add_equiv` from `ℂ` to `ℝ × ℝ`. -/ @[simps apply symm_apply_re symm_apply_im { simp_rhs := tt }] def equiv_real_prod_add_hom : ℂ ≃+ ℝ × ℝ := { map_add' := by simp, .. equiv_real_prod } /-- The natural `linear_equiv` from `ℂ` to `ℝ × ℝ`. -/ @[simps apply symm_apply_re symm_apply_im { simp_rhs := tt }] def equiv_real_prod_add_hom_lm : ℂ ≃ₗ[ℝ] ℝ × ℝ := { map_smul' := by simp [equiv_real_prod_add_hom], .. equiv_real_prod_add_hom } /-- The natural `continuous_linear_equiv` from `ℂ` to `ℝ × ℝ`. -/ @[simps apply symm_apply_re symm_apply_im { simp_rhs := tt }] def equiv_real_prodₗ : ℂ ≃L[ℝ] ℝ × ℝ := equiv_real_prod_add_hom_lm.to_continuous_linear_equiv end lemma has_sum_iff {α} (f : α → ℂ) (c : ℂ) : has_sum f c ↔ has_sum (λ x, (f x).re) c.re ∧ has_sum (λ x, (f x).im) c.im := begin -- For some reason, `continuous_linear_map.has_sum` is orders of magnitude faster than -- `has_sum.mapL` here: refine ⟨λ h, ⟨re_clm.has_sum h, im_clm.has_sum h⟩, _⟩, rintro ⟨h₁, h₂⟩, convert (h₁.prod_mk h₂).mapL equiv_real_prodₗ.symm.to_continuous_linear_map, { ext x; refl }, { cases c, refl } end end complex namespace is_R_or_C local notation `reC` := @is_R_or_C.re ℂ _ local notation `imC` := @is_R_or_C.im ℂ _ local notation `IC` := @is_R_or_C.I ℂ _ local notation `absC` := @is_R_or_C.abs ℂ _ local notation `norm_sqC` := @is_R_or_C.norm_sq ℂ _ @[simp] lemma re_to_complex {x : ℂ} : reC x = x.re := rfl @[simp] lemma im_to_complex {x : ℂ} : imC x = x.im := rfl @[simp] lemma I_to_complex : IC = complex.I := rfl @[simp] lemma norm_sq_to_complex {x : ℂ} : norm_sqC x = complex.norm_sq x := by simp [is_R_or_C.norm_sq, complex.norm_sq] @[simp] lemma abs_to_complex {x : ℂ} : absC x = complex.abs x := by simp [is_R_or_C.abs, complex.abs] end is_R_or_C
63f288189e12d2f0413090380295100e88d0eafd
48eee836fdb5c613d9a20741c17db44c8e12e61c
/src/universal/proof.lean
2b2d5a11ee89f6ba5f6c4bc2ee79da16042ba05f
[ "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
3,926
lean
-- Copyright © 2019 François G. Dorais. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. import .basic import .identity import .congruence import .model namespace universal universe u variables {τ : Type} {σ : Type u} {sig : signature τ σ} {ι : Type} (ax : ι → identity sig) inductive proof {ι : Type} (ax : ι → identity sig) {dom : list τ} : Π {cod : τ}, term sig dom cod → term sig dom cod → Type u | ax (i : ι) (sub : substitution sig (ax i).dom dom) : proof (sub.apply (ax i).lhs) (sub.apply (ax i).rhs) | proj {} (i : index dom) : proof (term.proj i) (term.proj i) | func (f : σ) {lhs rhs : Π (i : sig.index f), term sig dom i.val} : (Π i, proof (lhs i) (rhs i)) → proof (term.func f lhs) (term.func f rhs) | eucl {cod : τ} {{t u v : term sig dom cod}} : proof t u → proof t v → proof u v namespace proof variables {ax} {dom : list τ} definition refl : Π {cod} (t : term sig dom cod), proof ax t t | _ (term.proj i) := proof.proj i | _ (term.func f ts) := proof.func f (λ i, refl (ts i)) definition rfl {cod} {t : term sig dom cod} : proof ax t t := proof.refl t definition symm {cod} {{t u : term sig dom cod}} : proof ax t u → proof ax u t := λ h, proof.eucl h $ proof.refl t definition trans {cod} {{t u v : term sig dom cod}} : proof ax t u → proof ax u v → proof ax t v := λ h₁ h₂, proof.eucl h₁.symm h₂ definition subst {dom₁ dom₂ : list τ} (sub : substitution sig dom₁ dom₂) : Π {cod : τ} {t u : term sig dom₁ cod}, proof ax t u → proof ax (sub.apply t) (sub.apply u) | _ _ _ (proof.ax i isub) := eq.rec_on (substitution.comp_apply sub isub (ax i).lhs) $ eq.rec_on (substitution.comp_apply sub isub (ax i).rhs) $ proof.ax i (substitution.comp sub isub) | _ _ _ (proof.proj i) := proof.rfl | _ _ _ (proof.func f hs) := proof.func f (λ i, subst (hs i)) | _ _ _ (proof.eucl h₁ h₂) := proof.eucl (subst h₁) (subst h₂) definition ax_id (i) : proof ax (ax i).lhs (ax i).rhs := eq.rec_on (substitution.id_apply (ax i).lhs) $ eq.rec_on (substitution.id_apply (ax i).rhs) $ proof.ax i substitution.id variables (sig dom ax) definition to_congruence : congruence (term_algebra sig dom) := { r := λ _ t u, nonempty (proof ax t u) , refl := λ _ _, ⟨proof.rfl⟩ , eucl := λ _ _ _ _ ⟨h₁⟩ ⟨h₂⟩, ⟨proof.eucl h₁ h₂⟩ , func := λ f _ _ h, nonempty.elim (index.choice h) (λ h, ⟨proof.func f h⟩) } end proof theorem proof.sound {dom} : ∀ {cod} {t u : term sig dom cod}, proof ax t u → valid ax t u | _ _ _ (proof.ax i sub) := valid.ax i sub | _ _ _ (proof.proj i) := valid.refl (term.proj i) | _ _ _ (proof.func f hs) := valid.app f (λ i, proof.sound (hs i)) | _ _ _ (proof.eucl h₁ h₂) := valid.eucl (proof.sound h₁) (proof.sound h₂) definition proves (e : identity sig) : Prop := nonempty (proof ax e.lhs e.rhs) theorem soundness (e : identity sig) : proves ax e → models ax e := λ ⟨h⟩, proof.sound ax h abbreviation init_algebra (dom : list τ) : algebra sig := quotient (term_algebra sig dom) (proof.to_congruence sig ax dom) namespace init_algebra theorem satisfies_exact (e : identity sig) : (init_algebra ax e.dom).satisfies e → proves ax e := begin rw ← quotient.satisfies, intro H, cases H substitution.id with H, rw ← substitution.apply_def substitution.id at H, rw ← substitution.apply_def substitution.id at H, rw substitution.id_apply at H, rw substitution.id_apply at H, exact ⟨H⟩, end theorem satisfies_axiom (dom) (i) : algebra.satisfies (init_algebra ax dom) (ax i) := begin rw ← quotient.satisfies (proof.to_congruence sig ax dom) (ax i), intro sub, apply nonempty.intro, exact proof.ax i sub, end end init_algebra theorem completeness (e : identity sig) : models ax e → proves ax e := begin intro H, apply init_algebra.satisfies_exact, apply H, apply init_algebra.satisfies_axiom, end end universal
8856f79ed8d2d3d291cd72f4971e6d06a7678e5d
9dc8cecdf3c4634764a18254e94d43da07142918
/src/group_theory/finiteness.lean
0e829a45dadf2bbff774b30cf0b04392d24a1d04
[ "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
13,109
lean
/- Copyright (c) 2021 Riccardo Brasca. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Riccardo Brasca -/ import data.set.finite import data.finset import group_theory.quotient_group import group_theory.submonoid.operations import group_theory.subgroup.basic /-! # Finitely generated monoids and groups We define finitely generated monoids and groups. See also `submodule.fg` and `module.finite` for finitely-generated modules. ## Main definition * `submonoid.fg S`, `add_submonoid.fg S` : A submonoid `S` is finitely generated. * `monoid.fg M`, `add_monoid.fg M` : A typeclass indicating a type `M` is finitely generated as a monoid. * `subgroup.fg S`, `add_subgroup.fg S` : A subgroup `S` is finitely generated. * `group.fg M`, `add_group.fg M` : A typeclass indicating a type `M` is finitely generated as a group. -/ /-! ### Monoids and submonoids -/ open_locale pointwise variables {M N : Type*} [monoid M] [add_monoid N] section submonoid /-- A submonoid of `M` is finitely generated if it is the closure of a finite subset of `M`. -/ @[to_additive] def submonoid.fg (P : submonoid M) : Prop := ∃ S : finset M, submonoid.closure ↑S = P /-- An additive submonoid of `N` is finitely generated if it is the closure of a finite subset of `M`. -/ add_decl_doc add_submonoid.fg /-- An equivalent expression of `submonoid.fg` in terms of `set.finite` instead of `finset`. -/ @[to_additive "An equivalent expression of `add_submonoid.fg` in terms of `set.finite` instead of `finset`."] lemma submonoid.fg_iff (P : submonoid M) : submonoid.fg P ↔ ∃ S : set M, submonoid.closure S = P ∧ S.finite := ⟨λ ⟨S, hS⟩, ⟨S, hS, finset.finite_to_set S⟩, λ ⟨S, hS, hf⟩, ⟨set.finite.to_finset hf, by simp [hS]⟩⟩ lemma submonoid.fg_iff_add_fg (P : submonoid M) : P.fg ↔ P.to_add_submonoid.fg := ⟨λ h, let ⟨S, hS, hf⟩ := (submonoid.fg_iff _).1 h in (add_submonoid.fg_iff _).mpr ⟨additive.to_mul ⁻¹' S, by simp [← submonoid.to_add_submonoid_closure, hS], hf⟩, λ h, let ⟨T, hT, hf⟩ := (add_submonoid.fg_iff _).1 h in (submonoid.fg_iff _).mpr ⟨multiplicative.of_add ⁻¹' T, by simp [← add_submonoid.to_submonoid'_closure, hT], hf⟩⟩ lemma add_submonoid.fg_iff_mul_fg (P : add_submonoid N) : P.fg ↔ P.to_submonoid.fg := begin convert (submonoid.fg_iff_add_fg P.to_submonoid).symm, exact set_like.ext' rfl end end submonoid section monoid variables (M N) /-- A monoid is finitely generated if it is finitely generated as a submonoid of itself. -/ class monoid.fg : Prop := (out : (⊤ : submonoid M).fg) /-- An additive monoid is finitely generated if it is finitely generated as an additive submonoid of itself. -/ class add_monoid.fg : Prop := (out : (⊤ : add_submonoid N).fg) attribute [to_additive] monoid.fg variables {M N} lemma monoid.fg_def : monoid.fg M ↔ (⊤ : submonoid M).fg := ⟨λ h, h.1, λ h, ⟨h⟩⟩ lemma add_monoid.fg_def : add_monoid.fg N ↔ (⊤ : add_submonoid N).fg := ⟨λ h, h.1, λ h, ⟨h⟩⟩ /-- An equivalent expression of `monoid.fg` in terms of `set.finite` instead of `finset`. -/ @[to_additive "An equivalent expression of `add_monoid.fg` in terms of `set.finite` instead of `finset`."] lemma monoid.fg_iff : monoid.fg M ↔ ∃ S : set M, submonoid.closure S = (⊤ : submonoid M) ∧ S.finite := ⟨λ h, (submonoid.fg_iff ⊤).1 h.out, λ h, ⟨(submonoid.fg_iff ⊤).2 h⟩⟩ lemma monoid.fg_iff_add_fg : monoid.fg M ↔ add_monoid.fg (additive M) := ⟨λ h, ⟨(submonoid.fg_iff_add_fg ⊤).1 h.out⟩, λ h, ⟨(submonoid.fg_iff_add_fg ⊤).2 h.out⟩⟩ lemma add_monoid.fg_iff_mul_fg : add_monoid.fg N ↔ monoid.fg (multiplicative N) := ⟨λ h, ⟨(add_submonoid.fg_iff_mul_fg ⊤).1 h.out⟩, λ h, ⟨(add_submonoid.fg_iff_mul_fg ⊤).2 h.out⟩⟩ instance add_monoid.fg_of_monoid_fg [monoid.fg M] : add_monoid.fg (additive M) := monoid.fg_iff_add_fg.1 ‹_› instance monoid.fg_of_add_monoid_fg [add_monoid.fg N] : monoid.fg (multiplicative N) := add_monoid.fg_iff_mul_fg.1 ‹_› @[to_additive, priority 100] instance monoid.fg_of_finite [finite M] : monoid.fg M := by { casesI nonempty_fintype M, exact ⟨⟨finset.univ, by rw finset.coe_univ; exact submonoid.closure_univ⟩⟩ } end monoid @[to_additive] lemma submonoid.fg.map {M' : Type*} [monoid M'] {P : submonoid M} (h : P.fg) (e : M →* M') : (P.map e).fg := begin classical, obtain ⟨s, rfl⟩ := h, exact ⟨s.image e, by rw [finset.coe_image, monoid_hom.map_mclosure]⟩ end @[to_additive] lemma submonoid.fg.map_injective {M' : Type*} [monoid M'] {P : submonoid M} (e : M →* M') (he : function.injective e) (h : (P.map e).fg) : P.fg := begin obtain ⟨s, hs⟩ := h, use s.preimage e (he.inj_on _), apply submonoid.map_injective_of_injective he, rw [← hs, e.map_mclosure, finset.coe_preimage], congr, rw [set.image_preimage_eq_iff, ← e.coe_mrange, ← submonoid.closure_le, hs, e.mrange_eq_map], exact submonoid.monotone_map le_top end @[simp, to_additive] lemma monoid.fg_iff_submonoid_fg (N : submonoid M) : monoid.fg N ↔ N.fg := begin conv_rhs { rw [← N.range_subtype, monoid_hom.mrange_eq_map] }, exact ⟨λ h, h.out.map N.subtype, λ h, ⟨h.map_injective N.subtype subtype.coe_injective⟩⟩ end @[to_additive] lemma monoid.fg_of_surjective {M' : Type*} [monoid M'] [monoid.fg M] (f : M →* M') (hf : function.surjective f) : monoid.fg M' := begin classical, obtain ⟨s, hs⟩ := monoid.fg_def.mp ‹_›, use s.image f, rwa [finset.coe_image, ← monoid_hom.map_mclosure, hs, ← monoid_hom.mrange_eq_map, monoid_hom.mrange_top_iff_surjective], end @[to_additive] instance monoid.fg_range {M' : Type*} [monoid M'] [monoid.fg M] (f : M →* M') : monoid.fg f.mrange := monoid.fg_of_surjective f.mrange_restrict f.mrange_restrict_surjective @[to_additive add_submonoid.multiples_fg] lemma submonoid.powers_fg (r : M) : (submonoid.powers r).fg := ⟨{r}, (finset.coe_singleton r).symm ▸ (submonoid.powers_eq_closure r).symm⟩ @[to_additive add_monoid.multiples_fg] instance monoid.powers_fg (r : M) : monoid.fg (submonoid.powers r) := (monoid.fg_iff_submonoid_fg _).mpr (submonoid.powers_fg r) /-! ### Groups and subgroups -/ variables {G H : Type*} [group G] [add_group H] section subgroup /-- A subgroup of `G` is finitely generated if it is the closure of a finite subset of `G`. -/ @[to_additive] def subgroup.fg (P : subgroup G) : Prop := ∃ S : finset G, subgroup.closure ↑S = P /-- An additive subgroup of `H` is finitely generated if it is the closure of a finite subset of `H`. -/ add_decl_doc add_subgroup.fg /-- An equivalent expression of `subgroup.fg` in terms of `set.finite` instead of `finset`. -/ @[to_additive "An equivalent expression of `add_subgroup.fg` in terms of `set.finite` instead of `finset`."] lemma subgroup.fg_iff (P : subgroup G) : subgroup.fg P ↔ ∃ S : set G, subgroup.closure S = P ∧ S.finite := ⟨λ⟨S, hS⟩, ⟨S, hS, finset.finite_to_set S⟩, λ⟨S, hS, hf⟩, ⟨set.finite.to_finset hf, by simp [hS]⟩⟩ /-- A subgroup is finitely generated if and only if it is finitely generated as a submonoid. -/ @[to_additive add_subgroup.fg_iff_add_submonoid.fg "An additive subgroup is finitely generated if and only if it is finitely generated as an additive submonoid."] lemma subgroup.fg_iff_submonoid_fg (P : subgroup G) : P.fg ↔ P.to_submonoid.fg := begin split, { rintro ⟨S, rfl⟩, rw submonoid.fg_iff, refine ⟨S ∪ S⁻¹, _, S.finite_to_set.union S.finite_to_set.inv⟩, exact (subgroup.closure_to_submonoid _).symm }, { rintro ⟨S, hS⟩, refine ⟨S, le_antisymm _ _⟩, { rw [subgroup.closure_le, ←subgroup.coe_to_submonoid, ←hS], exact submonoid.subset_closure }, { rw [← subgroup.to_submonoid_le, ← hS, submonoid.closure_le], exact subgroup.subset_closure } } end lemma subgroup.fg_iff_add_fg (P : subgroup G) : P.fg ↔ P.to_add_subgroup.fg := begin rw [subgroup.fg_iff_submonoid_fg, add_subgroup.fg_iff_add_submonoid.fg], exact (subgroup.to_submonoid P).fg_iff_add_fg end lemma add_subgroup.fg_iff_mul_fg (P : add_subgroup H) : P.fg ↔ P.to_subgroup.fg := begin rw [add_subgroup.fg_iff_add_submonoid.fg, subgroup.fg_iff_submonoid_fg], exact add_submonoid.fg_iff_mul_fg (add_subgroup.to_add_submonoid P) end end subgroup section group variables (G H) /-- A group is finitely generated if it is finitely generated as a submonoid of itself. -/ class group.fg : Prop := (out : (⊤ : subgroup G).fg) /-- An additive group is finitely generated if it is finitely generated as an additive submonoid of itself. -/ class add_group.fg : Prop := (out : (⊤ : add_subgroup H).fg) attribute [to_additive] group.fg variables {G H} lemma group.fg_def : group.fg G ↔ (⊤ : subgroup G).fg := ⟨λ h, h.1, λ h, ⟨h⟩⟩ lemma add_group.fg_def : add_group.fg H ↔ (⊤ : add_subgroup H).fg := ⟨λ h, h.1, λ h, ⟨h⟩⟩ /-- An equivalent expression of `group.fg` in terms of `set.finite` instead of `finset`. -/ @[to_additive "An equivalent expression of `add_group.fg` in terms of `set.finite` instead of `finset`."] lemma group.fg_iff : group.fg G ↔ ∃ S : set G, subgroup.closure S = (⊤ : subgroup G) ∧ S.finite := ⟨λ h, (subgroup.fg_iff ⊤).1 h.out, λ h, ⟨(subgroup.fg_iff ⊤).2 h⟩⟩ @[to_additive] lemma group.fg_iff' : group.fg G ↔ ∃ n (S : finset G), S.card = n ∧ subgroup.closure (S : set G) = ⊤ := group.fg_def.trans ⟨λ ⟨S, hS⟩, ⟨S.card, S, rfl, hS⟩, λ ⟨n, S, hn, hS⟩, ⟨S, hS⟩⟩ /-- A group is finitely generated if and only if it is finitely generated as a monoid. -/ @[to_additive add_group.fg_iff_add_monoid.fg "An additive group is finitely generated if and only if it is finitely generated as an additive monoid."] lemma group.fg_iff_monoid.fg : group.fg G ↔ monoid.fg G := ⟨λ h, monoid.fg_def.2 $ (subgroup.fg_iff_submonoid_fg ⊤).1 (group.fg_def.1 h), λ h, group.fg_def.2 $ (subgroup.fg_iff_submonoid_fg ⊤).2 (monoid.fg_def.1 h)⟩ lemma group_fg.iff_add_fg : group.fg G ↔ add_group.fg (additive G) := ⟨λ h, ⟨(subgroup.fg_iff_add_fg ⊤).1 h.out⟩, λ h, ⟨(subgroup.fg_iff_add_fg ⊤).2 h.out⟩⟩ lemma add_group.fg_iff_mul_fg : add_group.fg H ↔ group.fg (multiplicative H) := ⟨λ h, ⟨(add_subgroup.fg_iff_mul_fg ⊤).1 h.out⟩, λ h, ⟨(add_subgroup.fg_iff_mul_fg ⊤).2 h.out⟩⟩ instance add_group.fg_of_group_fg [group.fg G] : add_group.fg (additive G) := group_fg.iff_add_fg.1 ‹_› instance group.fg_of_mul_group_fg [add_group.fg H] : group.fg (multiplicative H) := add_group.fg_iff_mul_fg.1 ‹_› @[to_additive, priority 100] instance group.fg_of_finite [finite G] : group.fg G := by { casesI nonempty_fintype G, exact ⟨⟨finset.univ, by rw finset.coe_univ; exact subgroup.closure_univ⟩⟩ } @[to_additive] lemma group.fg_of_surjective {G' : Type*} [group G'] [hG : group.fg G] {f : G →* G'} (hf : function.surjective f) : group.fg G' := group.fg_iff_monoid.fg.mpr $ @monoid.fg_of_surjective G _ G' _ (group.fg_iff_monoid.fg.mp hG) f hf @[to_additive] instance group.fg_range {G' : Type*} [group G'] [group.fg G] (f : G →* G') : group.fg f.range := group.fg_of_surjective f.range_restrict_surjective variables (G) /-- The minimum number of generators of a group. -/ @[to_additive "The minimum number of generators of an additive group"] noncomputable def group.rank [h : group.fg G] := @nat.find _ (classical.dec_pred _) (group.fg_iff'.mp h) @[to_additive] lemma group.rank_spec [h : group.fg G] : ∃ S : finset G, S.card = group.rank G ∧ subgroup.closure (S : set G) = ⊤ := @nat.find_spec _ (classical.dec_pred _) (group.fg_iff'.mp h) @[to_additive] lemma group.rank_le [h : group.fg G] {S : finset G} (hS : subgroup.closure (S : set G) = ⊤) : group.rank G ≤ S.card := @nat.find_le _ _ (classical.dec_pred _) (group.fg_iff'.mp h) ⟨S, rfl, hS⟩ variables {G} {G' : Type*} [group G'] @[to_additive] lemma group.rank_le_of_surjective [group.fg G] [group.fg G'] (f : G →* G') (hf : function.surjective f) : group.rank G' ≤ group.rank G := begin classical, obtain ⟨S, hS1, hS2⟩ := group.rank_spec G, transitivity (S.image f).card, { apply group.rank_le, rw [finset.coe_image, ←monoid_hom.map_closure, hS2, subgroup.map_top_of_surjective f hf] }, { exact finset.card_image_le.trans_eq hS1 }, end @[to_additive] lemma group.rank_range_le [group.fg G] {f : G →* G'} : group.rank f.range ≤ group.rank G := group.rank_le_of_surjective f.range_restrict f.range_restrict_surjective @[to_additive] lemma group.rank_congr [group.fg G] [group.fg G'] (f : G ≃* G') : group.rank G = group.rank G' := le_antisymm (group.rank_le_of_surjective f.symm f.symm.surjective) (group.rank_le_of_surjective f f.surjective) end group section quotient_group @[to_additive] instance quotient_group.fg [group.fg G] (N : subgroup G) [subgroup.normal N] : group.fg $ G ⧸ N := group.fg_of_surjective $ quotient_group.mk'_surjective N end quotient_group
900df1f1796094824879e9c5a749e771ba37458c
87a08a8e9b222ec02f3327dca4ae24590c1b3de9
/src/topology/maps.lean
6ff101142aa16d57e3dd43dcd2769d3423b5926e
[ "Apache-2.0" ]
permissive
naussicaa/mathlib
86d05223517a39e80920549a8052f9cf0e0b77b8
1ef2c2df20cf45c21675d855436228c7ae02d47a
refs/heads/master
1,592,104,950,080
1,562,073,069,000
1,562,073,069,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
17,520
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 Specific classes of maps between topological spaces: embeddings, open maps, quotient maps. -/ import topology.order topology.separation noncomputable theory open set filter lattice local attribute [instance] classical.prop_decidable variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} section embedding /-- A function between topological spaces is an embedding if it is injective, and for all `s : set α`, `s` is open iff it is the preimage of an open set. -/ def embedding [tα : topological_space α] [tβ : topological_space β] (f : α → β) : Prop := function.injective f ∧ tα = tβ.induced f variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] lemma embedding_id : embedding (@id α) := ⟨assume a₁ a₂ h, h, induced_id.symm⟩ lemma embedding_compose {f : α → β} {g : β → γ} (hg : embedding g) (hf : embedding f) : embedding (g ∘ f) := ⟨assume a₁ a₂ h, hf.left $ hg.left h, by rw [hf.right, hg.right, induced_compose]⟩ lemma embedding_prod_mk {f : α → β} {g : γ → δ} (hf : embedding f) (hg : embedding g) : embedding (λx:α×γ, (f x.1, g x.2)) := ⟨assume ⟨x₁, x₂⟩ ⟨y₁, y₂⟩, by simp; exact assume h₁ h₂, ⟨hf.left h₁, hg.left h₂⟩, by rw [prod.topological_space, prod.topological_space, hf.right, hg.right, induced_compose, induced_compose, induced_inf, induced_compose, induced_compose]⟩ lemma embedding_of_embedding_compose {f : α → β} {g : β → γ} (hf : continuous f) (hg : continuous g) (hgf : embedding (g ∘ f)) : embedding f := ⟨assume a₁ a₂ h, hgf.left $ by simp [h, (∘)], le_antisymm (by rwa ← continuous_iff_le_induced) (by rw [hgf.right, ← continuous_iff_le_induced]; apply hg.comp continuous_induced_dom)⟩ lemma embedding_open {f : α → β} {s : set α} (hf : embedding f) (h : is_open (range f)) (hs : is_open s) : is_open (f '' s) := let ⟨t, ht, h_eq⟩ := by rw [hf.right] at hs; exact hs in have is_open (t ∩ range f), from is_open_inter ht h, h_eq ▸ by rwa [image_preimage_eq_inter_range] lemma embedding_is_closed {f : α → β} {s : set α} (hf : embedding f) (h : is_closed (range f)) (hs : is_closed s) : is_closed (f '' s) := let ⟨t, ht, h_eq⟩ := by rw [hf.right, is_closed_induced_iff] at hs; exact hs in have is_closed (t ∩ range f), from is_closed_inter ht h, h_eq.symm ▸ by rwa [image_preimage_eq_inter_range] lemma embedding.map_nhds_eq [topological_space α] [topological_space β] {f : α → β} (hf : embedding f) (a : α) (h : range f ∈ nhds (f a)) : (nhds a).map f = nhds (f a) := by rw [hf.2]; exact map_nhds_induced_eq h lemma embedding.tendsto_nhds_iff {ι : Type*} {f : ι → β} {g : β → γ} {a : filter ι} {b : β} (hg : embedding g) : tendsto f a (nhds b) ↔ tendsto (g ∘ f) a (nhds (g b)) := by rw [tendsto, tendsto, hg.right, nhds_induced_eq_comap, ← map_le_iff_le_comap, filter.map_map] lemma embedding.continuous_iff {f : α → β} {g : β → γ} (hg : embedding g) : continuous f ↔ continuous (g ∘ f) := by simp [continuous_iff_continuous_at, continuous_at, embedding.tendsto_nhds_iff hg] lemma embedding.continuous {f : α → β} (hf : embedding f) : continuous f := hf.continuous_iff.mp continuous_id lemma embedding.closure_eq_preimage_closure_image {e : α → β} (he : embedding e) (s : set α) : closure s = e ⁻¹' closure (e '' s) := by ext x; rw [set.mem_preimage_eq, ← closure_induced he.1, he.2] end embedding -- TODO: use embeddings from above! structure dense_embedding [topological_space α] [topological_space β] (e : α → β) : Prop := (dense : ∀x, x ∈ closure (range e)) (inj : function.injective e) (induced : ∀a, comap e (nhds (e a)) = nhds a) theorem dense_embedding.mk' [topological_space α] [topological_space β] (e : α → β) (c : continuous e) (dense : ∀x, x ∈ closure (range e)) (inj : function.injective e) (H : ∀ (a:α) s ∈ nhds a, ∃t ∈ nhds (e a), ∀ b, e b ∈ t → b ∈ s) : dense_embedding e := ⟨dense, inj, λ a, le_antisymm (by simpa [le_def] using H a) (tendsto_iff_comap.1 $ c.tendsto _)⟩ namespace dense_embedding variables [topological_space α] [topological_space β] variables {e : α → β} (de : dense_embedding e) protected lemma embedding (de : dense_embedding e) : embedding e := ⟨de.inj, eq_of_nhds_eq_nhds begin intro a, rw [← de.induced a, nhds_induced_eq_comap] end⟩ protected lemma continuous_at (de : dense_embedding e) {a : α} : continuous_at e a := by rw [continuous_at, ←de.induced a]; exact tendsto_comap protected lemma continuous (de : dense_embedding e) {a : α} : continuous e := continuous_iff_continuous_at.mpr $ λ a, de.continuous_at lemma inj_iff (de : dense_embedding e) {x y} : e x = e y ↔ x = y := de.inj.eq_iff lemma closure_range : closure (range e) = univ := let h := de.dense in set.ext $ assume x, ⟨assume _, trivial, assume _, @h x⟩ lemma self_sub_closure_image_preimage_of_open {s : set β} (de : dense_embedding e) : is_open s → s ⊆ closure (e '' (e ⁻¹' s)) := begin intros s_op b b_in_s, rw [image_preimage_eq_inter_range, mem_closure_iff], intros U U_op b_in, rw ←inter_assoc, have ne_e : U ∩ s ≠ ∅ := ne_empty_of_mem ⟨b_in, b_in_s⟩, exact (dense_iff_inter_open.1 de.closure_range) _ (is_open_inter U_op s_op) ne_e end lemma closure_image_nhds_of_nhds {s : set α} {a : α} (de : dense_embedding e) : s ∈ nhds a → closure (e '' s) ∈ nhds (e a) := begin rw [← de.induced a, mem_comap_sets], intro h, rcases h with ⟨t, t_nhd, sub⟩, rw mem_nhds_sets_iff at t_nhd, rcases t_nhd with ⟨U, U_sub, ⟨U_op, e_a_in_U⟩⟩, have := calc e ⁻¹' U ⊆ e⁻¹' t : preimage_mono U_sub ... ⊆ s : sub, have := calc U ⊆ closure (e '' (e ⁻¹' U)) : self_sub_closure_image_preimage_of_open de U_op ... ⊆ closure (e '' s) : closure_mono (image_subset e this), have U_nhd : U ∈ nhds (e a) := mem_nhds_sets U_op e_a_in_U, exact (nhds (e a)).sets_of_superset U_nhd this end variables [topological_space δ] {f : γ → α} {g : γ → δ} {h : δ → β} /-- γ -f→ α g↓ ↓e δ -h→ β -/ lemma tendsto_comap_nhds_nhds {d : δ} {a : α} (de : dense_embedding e) (H : tendsto h (nhds d) (nhds (e a))) (comm : h ∘ g = e ∘ f) : tendsto f (comap g (nhds d)) (nhds a) := begin have lim1 : map g (comap g (nhds d)) ≤ nhds d := map_comap_le, replace lim1 : map h (map g (comap g (nhds d))) ≤ map h (nhds d) := map_mono lim1, rw [filter.map_map, comm, ← filter.map_map, map_le_iff_le_comap] at lim1, have lim2 : comap e (map h (nhds d)) ≤ comap e (nhds (e a)) := comap_mono H, rw de.induced at lim2, exact le_trans lim1 lim2, end protected lemma nhds_inf_neq_bot (de : dense_embedding e) {b : β} : nhds b ⊓ principal (range e) ≠ ⊥ := begin have h := de.dense, simp [closure_eq_nhds] at h, exact h _ end lemma comap_nhds_neq_bot (de : dense_embedding e) {b : β} : comap e (nhds b) ≠ ⊥ := forall_sets_neq_empty_iff_neq_bot.mp $ assume s ⟨t, ht, (hs : e ⁻¹' t ⊆ s)⟩, have t ∩ range e ∈ nhds b ⊓ principal (range e), from inter_mem_inf_sets ht (subset.refl _), let ⟨_, ⟨hx₁, y, rfl⟩⟩ := inhabited_of_mem_sets de.nhds_inf_neq_bot this in subset_ne_empty hs $ ne_empty_of_mem hx₁ variables [topological_space γ] /-- If `e : α → β` is a dense embedding, then any function `α → γ` extends to a function `β → γ`. It only extends the parts of `β` which are not mapped by `e`, everything else equal to `f (e a)`. This allows us to gain equality even if `γ` is not T2. -/ def extend (de : dense_embedding e) (f : α → γ) (b : β) : γ := have nonempty γ, from let ⟨_, ⟨_, a, _⟩⟩ := exists_mem_of_ne_empty (mem_closure_iff.1 (de.dense b) _ is_open_univ trivial) in ⟨f a⟩, if hb : b ∈ range e then f (classical.some hb) else @lim _ _ (classical.inhabited_of_nonempty this) (map f (comap e (nhds b))) lemma extend_e_eq {f : α → γ} (a : α) : de.extend f (e a) = f a := have e a ∈ range e := ⟨a, rfl⟩, begin simp [extend, this], congr, refine classical.some_spec2 (λx, x = a) _, exact assume a h, de.inj h end lemma extend_eq [t2_space γ] {b : β} {c : γ} {f : α → γ} (hf : map f (comap e (nhds b)) ≤ nhds c) : de.extend f b = c := begin by_cases hb : b ∈ range e, { rcases hb with ⟨a, rfl⟩, rw [extend_e_eq], have f_a_c : tendsto f (pure a) (nhds c), { rw [de.induced] at hf, refine le_trans (map_mono _) hf, exact pure_le_nhds a }, have f_a_fa : tendsto f (pure a) (nhds (f a)), { rw [tendsto, filter.map_pure], exact pure_le_nhds _ }, exact tendsto_nhds_unique pure_neq_bot f_a_fa f_a_c }, { simp [extend, hb], exact @lim_eq _ _ (id _) _ _ _ (by simp; exact comap_nhds_neq_bot de) hf } end lemma tendsto_extend [regular_space γ] {b : β} {f : α → γ} (de : dense_embedding e) (hf : {b | ∃c, tendsto f (comap e $ nhds b) (nhds c)} ∈ nhds b) : tendsto (de.extend f) (nhds b) (nhds (de.extend f b)) := let φ := {b | tendsto f (comap e $ nhds b) (nhds $ de.extend f b)} in have hφ : φ ∈ nhds b, from (nhds b).sets_of_superset hf $ assume b ⟨c, hc⟩, show tendsto f (comap e (nhds b)) (nhds (de.extend f b)), from (de.extend_eq hc).symm ▸ hc, assume s hs, let ⟨s'', hs''₁, hs''₂, hs''₃⟩ := nhds_is_closed hs in let ⟨s', hs'₁, (hs'₂ : e ⁻¹' s' ⊆ f ⁻¹' s'')⟩ := mem_of_nhds hφ hs''₁ in let ⟨t, (ht₁ : t ⊆ φ ∩ s'), ht₂, ht₃⟩ := mem_nhds_sets_iff.mp $ inter_mem_sets hφ hs'₁ in have h₁ : closure (f '' (e ⁻¹' s')) ⊆ s'', by rw [closure_subset_iff_subset_of_is_closed hs''₃, image_subset_iff]; exact hs'₂, have h₂ : t ⊆ de.extend f ⁻¹' closure (f '' (e ⁻¹' t)), from assume b' hb', have nhds b' ≤ principal t, by simp; exact mem_nhds_sets ht₂ hb', have map f (comap e (nhds b')) ≤ nhds (de.extend f b') ⊓ principal (f '' (e ⁻¹' t)), from calc _ ≤ map f (comap e (nhds b' ⊓ principal t)) : map_mono $ comap_mono $ le_inf (le_refl _) this ... ≤ map f (comap e (nhds b')) ⊓ map f (comap e (principal t)) : le_inf (map_mono $ comap_mono $ inf_le_left) (map_mono $ comap_mono $ inf_le_right) ... ≤ map f (comap e (nhds b')) ⊓ principal (f '' (e ⁻¹' t)) : by simp [le_refl] ... ≤ _ : inf_le_inf ((ht₁ hb').left) (le_refl _), show de.extend f b' ∈ closure (f '' (e ⁻¹' t)), begin rw [closure_eq_nhds], apply neq_bot_of_le_neq_bot _ this, simp, exact de.comap_nhds_neq_bot end, (nhds b).sets_of_superset (show t ∈ nhds b, from mem_nhds_sets ht₂ ht₃) (calc t ⊆ de.extend f ⁻¹' closure (f '' (e ⁻¹' t)) : h₂ ... ⊆ de.extend f ⁻¹' closure (f '' (e ⁻¹' s')) : preimage_mono $ closure_mono $ image_subset f $ preimage_mono $ subset.trans ht₁ $ inter_subset_right _ _ ... ⊆ de.extend f ⁻¹' s'' : preimage_mono h₁ ... ⊆ de.extend f ⁻¹' s : preimage_mono hs''₂) lemma continuous_extend [regular_space γ] {f : α → γ} (de : dense_embedding e) (hf : ∀b, ∃c, tendsto f (comap e (nhds b)) (nhds c)) : continuous (de.extend f) := continuous_iff_continuous_at.mpr $ assume b, de.tendsto_extend $ univ_mem_sets' hf end dense_embedding /-- A function between topological spaces is a quotient map if it is surjective, and for all `s : set β`, `s` is open iff its preimage is an open set. -/ def quotient_map {α : Type*} {β : Type*} [tα : topological_space α] [tβ : topological_space β] (f : α → β) : Prop := function.surjective f ∧ tβ = tα.coinduced f namespace quotient_map variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] protected lemma id : quotient_map (@id α) := ⟨assume a, ⟨a, rfl⟩, coinduced_id.symm⟩ protected lemma comp {f : α → β} {g : β → γ} (hf : quotient_map f) (hg : quotient_map g) : quotient_map (g ∘ f) := ⟨function.surjective_comp hg.left hf.left, by rw [hg.right, hf.right, coinduced_compose]⟩ protected lemma of_quotient_map_compose {f : α → β} {g : β → γ} (hf : continuous f) (hg : continuous g) (hgf : quotient_map (g ∘ f)) : quotient_map g := ⟨assume b, let ⟨a, h⟩ := hgf.left b in ⟨f a, h⟩, le_antisymm (by rw [hgf.right, ← continuous_iff_coinduced_le]; apply continuous_coinduced_rng.comp hf) (by rwa ← continuous_iff_coinduced_le)⟩ protected lemma continuous_iff {f : α → β} {g : β → γ} (hf : quotient_map f) : continuous g ↔ continuous (g ∘ f) := by rw [continuous_iff_coinduced_le, continuous_iff_coinduced_le, hf.right, coinduced_compose] protected lemma continuous {f : α → β} (hf : quotient_map f) : continuous f := hf.continuous_iff.mp continuous_id end quotient_map section is_open_map variables [topological_space α] [topological_space β] def is_open_map (f : α → β) := ∀ U : set α, is_open U → is_open (f '' U) lemma is_open_map_iff_nhds_le (f : α → β) : is_open_map f ↔ ∀(a:α), nhds (f a) ≤ (nhds a).map f := begin split, { assume h a s hs, rcases mem_nhds_sets_iff.1 hs with ⟨t, hts, ht, hat⟩, exact filter.mem_sets_of_superset (mem_nhds_sets (h t ht) (mem_image_of_mem _ hat)) (image_subset_iff.2 hts) }, { refine assume h s hs, is_open_iff_mem_nhds.2 _, rintros b ⟨a, ha, rfl⟩, exact h _ (filter.image_mem_map $ mem_nhds_sets hs ha) } end end is_open_map namespace is_open_map variables [topological_space α] [topological_space β] [topological_space γ] open function protected lemma id : is_open_map (@id α) := assume s hs, by rwa [image_id] protected lemma comp {f : α → β} {g : β → γ} (hf : is_open_map f) (hg : is_open_map g) : is_open_map (g ∘ f) := by intros s hs; rw [image_comp]; exact hg _ (hf _ hs) lemma of_inverse {f : α → β} {f' : β → α} (h : continuous f') (l_inv : left_inverse f f') (r_inv : right_inverse f f') : is_open_map f := assume s hs, have f' ⁻¹' s = f '' s, by ext x; simp [mem_image_iff_of_inverse r_inv l_inv], this ▸ h s hs lemma to_quotient_map {f : α → β} (open_map : is_open_map f) (cont : continuous f) (surj : function.surjective f) : quotient_map f := ⟨ surj, begin ext s, show is_open s ↔ is_open (f ⁻¹' s), split, { exact cont s }, { assume h, rw ← @image_preimage_eq _ _ _ s surj, exact open_map _ h } end⟩ end is_open_map section is_closed_map variables [topological_space α] [topological_space β] def is_closed_map (f : α → β) := ∀ U : set α, is_closed U → is_closed (f '' U) end is_closed_map namespace is_closed_map variables [topological_space α] [topological_space β] [topological_space γ] open function protected lemma id : is_closed_map (@id α) := assume s hs, by rwa image_id protected lemma comp {f : α → β} {g : β → γ} (hf : is_closed_map f) (hg : is_closed_map g) : is_closed_map (g ∘ f) := by { intros s hs, rw image_comp, exact hg _ (hf _ hs) } lemma of_inverse {f : α → β} {f' : β → α} (h : continuous f') (l_inv : left_inverse f f') (r_inv : right_inverse f f') : is_closed_map f := assume s hs, have f' ⁻¹' s = f '' s, by ext x; simp [mem_image_iff_of_inverse r_inv l_inv], this ▸ continuous_iff_is_closed.mp h s hs end is_closed_map section closed_embedding variables [topological_space α] [topological_space β] [topological_space γ] /-- A closed embedding is an embedding with closed image. -/ def closed_embedding (f : α → β) : Prop := embedding f ∧ is_closed (range f) lemma closed_embedding.closed_iff_image_closed {f : α → β} (hf : closed_embedding f) {s : set α} : is_closed s ↔ is_closed (f '' s) := ⟨embedding_is_closed hf.1 hf.2, λ h, begin convert ←continuous_iff_is_closed.mp hf.1.continuous _ h, apply preimage_image_eq _ hf.1.1 end⟩ lemma closed_embedding.closed_iff_preimage_closed {f : α → β} (hf : closed_embedding f) {s : set β} (hs : s ⊆ range f) : is_closed s ↔ is_closed (f ⁻¹' s) := begin convert ←hf.closed_iff_image_closed.symm, rwa [image_preimage_eq_inter_range, inter_eq_self_of_subset_left] end lemma closed_embedding_of_continuous_injective_closed {f : α → β} (h₁ : continuous f) (h₂ : function.injective f) (h₃ : is_closed_map f) : closed_embedding f := begin refine ⟨⟨h₂, _⟩, by convert h₃ univ is_closed_univ; simp⟩, apply le_antisymm (continuous_iff_le_induced.mp h₁) _, intro s', change is_open _ ≤ is_open _, rw [←is_closed_compl_iff, ←is_closed_compl_iff], generalize : -s' = s, rw is_closed_induced_iff, refine λ hs, ⟨f '' s, h₃ s hs, _⟩, rw preimage_image_eq _ h₂ end lemma closed_embedding_id : closed_embedding (@id α) := ⟨embedding_id, by convert is_closed_univ; apply range_id⟩ lemma closed_embedding_compose {f : α → β} {g : β → γ} (hg : closed_embedding g) (hf : closed_embedding f) : closed_embedding (g ∘ f) := ⟨embedding_compose hg.1 hf.1, show is_closed (range (g ∘ f)), by rw [range_comp, ←hg.closed_iff_image_closed]; exact hf.2⟩ end closed_embedding
0b0c38d9454082d56010ee9d2678eacfc7308ee1
491068d2ad28831e7dade8d6dff871c3e49d9431
/tests/lean/737.lean
977c72c0ca9d62aee762d92d8d2187457232a903
[ "Apache-2.0" ]
permissive
davidmueller13/lean
65a3ed141b4088cd0a268e4de80eb6778b21a0e9
c626e2e3c6f3771e07c32e82ee5b9e030de5b050
refs/heads/master
1,611,278,313,401
1,444,021,177,000
1,444,021,177,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,557
lean
/- Copyright (c) 2015 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Robert Y. Lewis The real numbers, constructed as equivalence classes of Cauchy sequences of rationals. This construction follows Bishop and Bridges (1985). To do: o Break positive naturals into their own file and fill in sorry's o Fill in sorrys for helper lemmas that will not be handled by simplifier o Rename things and possibly make theorems private -/ import data.nat data.rat.order data.pnat open nat eq eq.ops pnat open -[coercions] rat local notation 0 := rat.of_num 0 local notation 1 := rat.of_num 1 ---------------------------------------------------------------------------------------------------- ------------------------------------- -- theorems to add to (ordered) field and/or rat -- this can move to pnat once sorry is filled in theorem find_midpoint {a b : ℚ} (H : a > b) : ∃ c : ℚ, a > b + c ∧ c > 0 := sorry theorem add_sub_comm (a b c d : ℚ) : a + b - (c + d) = (a - c) + (b - d) := sorry theorem s_mul_assoc_lemma_4 {n : ℕ+} {ε q : ℚ} (Hε : ε > 0) (Hq : q > 0) (H : n ≥ pceil (q / ε)) : q * n⁻¹ ≤ ε := sorry theorem s_mul_assoc_lemma_3 (a b n : ℕ+) (p : ℚ) : p * ((a * n)⁻¹ + (b * n)⁻¹) = p * (a⁻¹ + b⁻¹) * n⁻¹ := sorry theorem find_thirds (a b : ℚ) : ∃ n : ℕ+, a + n⁻¹ + n⁻¹ + n⁻¹ < a + b := sorry theorem squeeze {a b : ℚ} (H : ∀ j : ℕ+, a ≤ b + j⁻¹ + j⁻¹ + j⁻¹) : a ≤ b := sorry theorem squeeze_2 {a b : ℚ} (H : ∀ ε : ℚ, ε > 0 → a ≥ b - ε) : a ≥ b := sorry theorem rewrite_helper (a b c d : ℚ) : a * b - c * d = a * (b - d) + (a - c) * d := sorry theorem rewrite_helper3 (a b c d e f g: ℚ) : a * (b + c) - (d * e + f * g) = (a * b - d * e) + (a * c - f * g) := sorry theorem rewrite_helper4 (a b c d : ℚ) : a * b - c * d = (a * b - a * d) + (a * d - c * d) := sorry theorem rewrite_helper5 (a b x y : ℚ) : a - b = (a - x) + (x - y) + (y - b) := sorry theorem rewrite_helper7 (a b c d x : ℚ) : a * b * c - d = (b * c) * (a - x) + (x * b * c - d) := sorry theorem ineq_helper (a b : ℚ) (k m n : ℕ+) (H : a ≤ (k * 2 * m)⁻¹ + (k * 2 * n)⁻¹) (H2 : b ≤ (k * 2 * m)⁻¹ + (k * 2 * n)⁻¹) : (rat_of_pnat k) * a + b * (rat_of_pnat k) ≤ m⁻¹ + n⁻¹ := sorry theorem factor_lemma (a b c d e : ℚ) : abs (a + b + c - (d + (b + e))) = abs ((a - d) + (c - e)) := sorry theorem factor_lemma_2 (a b c d : ℚ) : (a + b) + (c + d) = (a + c) + (d + b) := sorry namespace s notation `seq` := ℕ+ → ℚ definition regular (s : seq) := ∀ m n : ℕ+, abs (s m - s n) ≤ m⁻¹ + n⁻¹ definition equiv (s t : seq) := ∀ n : ℕ+, abs (s n - t n) ≤ n⁻¹ + n⁻¹ infix `≡` := equiv theorem equiv.refl (s : seq) : s ≡ s := sorry theorem equiv.symm (s t : seq) (H : s ≡ t) : t ≡ s := sorry theorem bdd_of_eq {s t : seq} (H : s ≡ t) : ∀ j : ℕ+, ∀ n : ℕ+, n ≥ 2 * j → abs (s n - t n) ≤ j⁻¹ := sorry theorem eq_of_bdd {s t : seq} (Hs : regular s) (Ht : regular t) (H : ∀ j : ℕ+, ∃ Nj : ℕ+, ∀ n : ℕ+, Nj ≤ n → abs (s n - t n) ≤ j⁻¹) : s ≡ t := sorry theorem eq_of_bdd_var {s t : seq} (Hs : regular s) (Ht : regular t) (H : ∀ ε : ℚ, ε > 0 → ∃ Nj : ℕ+, ∀ n : ℕ+, Nj ≤ n → abs (s n - t n) ≤ ε) : s ≡ t := sorry set_option pp.beta false theorem pnat_bound {ε : ℚ} (Hε : ε > 0) : ∃ p : ℕ+, p⁻¹ ≤ ε := sorry theorem bdd_of_eq_var {s t : seq} (Hs : regular s) (Ht : regular t) (Heq : s ≡ t) : ∀ ε : ℚ, ε > 0 → ∃ Nj : ℕ+, ∀ n : ℕ+, Nj ≤ n → abs (s n - t n) ≤ ε := sorry theorem equiv.trans (s t u : seq) (Hs : regular s) (Ht : regular t) (Hu : regular u) (H : s ≡ t) (H2 : t ≡ u) : s ≡ u := sorry ----------------------------------- -- define operations on cauchy sequences. show operations preserve regularity definition K (s : seq) : ℕ+ := pnat.pos (ubound (abs (s pone)) + 1 + 1) dec_trivial theorem canon_bound {s : seq} (Hs : regular s) (n : ℕ+) : abs (s n) ≤ rat_of_pnat (K s) := sorry definition K₂ (s t : seq) := max (K s) (K t) theorem K₂_symm (s t : seq) : K₂ s t = K₂ t s := sorry theorem canon_2_bound_left (s t : seq) (Hs : regular s) (n : ℕ+) : abs (s n) ≤ rat_of_pnat (K₂ s t) := sorry theorem canon_2_bound_right (s t : seq) (Ht : regular t) (n : ℕ+) : abs (t n) ≤ rat_of_pnat (K₂ s t) := sorry definition sadd (s t : seq) : seq := λ n, (s (2 * n)) + (t (2 * n)) theorem reg_add_reg {s t : seq} (Hs : regular s) (Ht : regular t) : regular (sadd s t) := sorry definition smul (s t : seq) : seq := λ n : ℕ+, (s ((K₂ s t) * 2 * n)) * (t ((K₂ s t) * 2 * n)) theorem reg_mul_reg {s t : seq} (Hs : regular s) (Ht : regular t) : regular (smul s t) := sorry definition sneg (s : seq) : seq := λ n : ℕ+, - (s n) theorem reg_neg_reg {s : seq} (Hs : regular s) : regular (sneg s) := sorry ----------------------------------- -- show properties of +, *, - definition zero : seq := λ n, 0 definition one : seq := λ n, 1 theorem s_add_comm (s t : seq) : sadd s t ≡ sadd t s := sorry theorem s_add_assoc (s t u : seq) (Hs : regular s) (Hu : regular u) : sadd (sadd s t) u ≡ sadd s (sadd t u) := sorry theorem s_mul_comm (s t : seq) : smul s t ≡ smul t s := sorry definition DK (s t : seq) := (K₂ s t) * 2 theorem DK_rewrite (s t : seq) : (K₂ s t) * 2 = DK s t := rfl definition TK (s t u : seq) := (DK (λ (n : ℕ+), s (mul (DK s t) n) * t (mul (DK s t) n)) u) theorem TK_rewrite (s t u : seq) : (DK (λ (n : ℕ+), s (mul (DK s t) n) * t (mul (DK s t) n)) u) = TK s t u := rfl theorem s_mul_assoc_lemma (s t u : seq) (a b c d : ℕ+) : abs (s a * t a * u b - s c * t d * u d) ≤ abs (t a) * abs (u b) * abs (s a - s c) + abs (s c) * abs (t a) * abs (u b - u d) + abs (s c) * abs (u d) * abs (t a - t d) := sorry definition Kq (s : seq) := rat_of_pnat (K s) + 1 theorem Kq_bound {s : seq} (H : regular s) : ∀ n, abs (s n) ≤ Kq s := sorry theorem Kq_bound_nonneg {s : seq} (H : regular s) : 0 ≤ Kq s := rat.le.trans !abs_nonneg (Kq_bound H 2) theorem Kq_bound_pos {s : seq} (H : regular s) : 0 < Kq s := sorry theorem s_mul_assoc_lemma_5 {s t u : seq} (Hs : regular s) (Ht : regular t) (Hu : regular u) (a b c : ℕ+) : abs (t a) * abs (u b) * abs (s a - s c) ≤ (Kq t) * (Kq u) * (a⁻¹ + c⁻¹) := sorry theorem s_mul_assoc_lemma_2 {s t u : seq} (Hs : regular s) (Ht : regular t) (Hu : regular u) (a b c d : ℕ+) : abs (t a) * abs (u b) * abs (s a - s c) + abs (s c) * abs (t a) * abs (u b - u d) + abs (s c) * abs (u d) * abs (t a - t d) ≤ (Kq t) * (Kq u) * (a⁻¹ + c⁻¹) + (Kq s) * (Kq t) * (b⁻¹ + d⁻¹) + (Kq s) * (Kq u) * (a⁻¹ + d⁻¹) := sorry theorem s_mul_assoc {s t u : seq} (Hs : regular s) (Ht : regular t) (Hu : regular u) : smul (smul s t) u ≡ smul s (smul t u) := sorry theorem zero_is_reg : regular zero := sorry theorem s_zero_add (s : seq) (H : regular s) : sadd zero s ≡ s := sorry theorem s_add_zero (s : seq) (H : regular s) : sadd s zero ≡ s := sorry theorem s_neg_cancel (s : seq) (H : regular s) : sadd (sneg s) s ≡ zero := sorry theorem neg_s_cancel (s : seq) (H : regular s) : sadd s (sneg s) ≡ zero := sorry theorem add_well_defined {s t u v : seq} (Hs : regular s) (Ht : regular t) (Hu : regular u) (Hv : regular v) (Esu : s ≡ u) (Etv : t ≡ v) : sadd s t ≡ sadd u v := sorry theorem mul_bound_helper {s t : seq} (Hs : regular s) (Ht : regular t) (a b c : ℕ+) (j : ℕ+) : ∃ N : ℕ+, ∀ n : ℕ+, n ≥ N → abs (s (a * n) * t (b * n) - s (c * n) * t (c * n)) ≤ j⁻¹ := begin existsi pceil (((rat_of_pnat (K s)) * (b⁻¹ + c⁻¹) + (a⁻¹ + c⁻¹) * (rat_of_pnat (K t))) * (rat_of_pnat j)), intros n Hn, rewrite rewrite_helper4, apply rat.le.trans, apply abs_add_le_abs_add_abs, apply rat.le.trans, rotate 1, show n⁻¹ * ((rat_of_pnat (K s)) * (b⁻¹ + c⁻¹)) + n⁻¹ * ((a⁻¹ + c⁻¹) * (rat_of_pnat (K t))) ≤ j⁻¹, begin rewrite -rat.left_distrib, apply rat.le.trans, apply rat.mul_le_mul_of_nonneg_right, apply pceil_helper Hn, repeat (apply rat.mul_pos | apply rat.add_pos | apply inv_pos | apply rat_of_pnat_is_pos), end end end s
7b778b8afdcedbfeb04cb5ebc7ed0710b1117212
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/control/applicative.lean
9d22f43feadcc3410590f1f0a18dc5167872a77d
[ "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
4,737
lean
/- Copyright (c) 2017 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon Instances for identity and composition functors -/ import control.functor import algebra.group.basic universe variables u v w section lemmas open function variables {F : Type u → Type v} variables [applicative F] [is_lawful_applicative F] variables {α β γ σ : Type u} lemma applicative.map_seq_map (f : α → β → γ) (g : σ → β) (x : F α) (y : F σ) : (f <$> x) <*> (g <$> y) = (flip (∘) g ∘ f) <$> x <*> y := by simp [flip] with functor_norm lemma applicative.pure_seq_eq_map' (f : α → β) : (<*>) (pure f : F (α → β)) = (<$>) f := by ext; simp with functor_norm theorem applicative.ext {F} : ∀ {A1 : applicative F} {A2 : applicative F} [@is_lawful_applicative F A1] [@is_lawful_applicative F A2] (H1 : ∀ {α : Type u} (x : α), @has_pure.pure _ A1.to_has_pure _ x = @has_pure.pure _ A2.to_has_pure _ x) (H2 : ∀ {α β : Type u} (f : F (α → β)) (x : F α), @has_seq.seq _ A1.to_has_seq _ _ f x = @has_seq.seq _ A2.to_has_seq _ _ f x), A1 = A2 | {to_functor := F1, seq := s1, pure := p1, seq_left := sl1, seq_right := sr1} {to_functor := F2, seq := s2, pure := p2, seq_left := sl2, seq_right := sr2} L1 L2 H1 H2 := begin have : @p1 = @p2, {funext α x, apply H1}, subst this, have : @s1 = @s2, {funext α β f x, apply H2}, subst this, cases L1, cases L2, have : F1 = F2, { resetI, apply functor.ext, intros, exact (L1_pure_seq_eq_map _ _).symm.trans (L2_pure_seq_eq_map _ _) }, subst this, congr; funext α β x y, { exact (L1_seq_left_eq _ _).trans (L2_seq_left_eq _ _).symm }, { exact (L1_seq_right_eq _ _).trans (L2_seq_right_eq _ _).symm } end end lemmas instance : is_comm_applicative id := by refine { .. }; intros; refl namespace functor namespace comp open function (hiding comp) open functor variables {F : Type u → Type w} {G : Type v → Type u} variables [applicative F] [applicative G] variables [is_lawful_applicative F] [is_lawful_applicative G] variables {α β γ : Type v} lemma map_pure (f : α → β) (x : α) : (f <$> pure x : comp F G β) = pure (f x) := comp.ext $ by simp lemma seq_pure (f : comp F G (α → β)) (x : α) : f <*> pure x = (λ g : α → β, g x) <$> f := comp.ext $ by simp [(∘)] with functor_norm lemma seq_assoc (x : comp F G α) (f : comp F G (α → β)) (g : comp F G (β → γ)) : g <*> (f <*> x) = (@function.comp α β γ <$> g) <*> f <*> x := comp.ext $ by simp [(∘)] with functor_norm lemma pure_seq_eq_map (f : α → β) (x : comp F G α) : pure f <*> x = f <$> x := comp.ext $ by simp [applicative.pure_seq_eq_map'] with functor_norm instance : is_lawful_applicative (comp F G) := { pure_seq_eq_map := @comp.pure_seq_eq_map F G _ _ _ _, map_pure := @comp.map_pure F G _ _ _ _, seq_pure := @comp.seq_pure F G _ _ _ _, seq_assoc := @comp.seq_assoc F G _ _ _ _ } theorem applicative_id_comp {F} [AF : applicative F] [LF : is_lawful_applicative F] : @comp.applicative id F _ _ = AF := @applicative.ext F _ _ (@comp.is_lawful_applicative id F _ _ _ _) _ (λ α x, rfl) (λ α β f x, rfl) theorem applicative_comp_id {F} [AF : applicative F] [LF : is_lawful_applicative F] : @comp.applicative F id _ _ = AF := @applicative.ext F _ _ (@comp.is_lawful_applicative F id _ _ _ _) _ (λ α x, rfl) (λ α β f x, show id <$> f <*> x = f <*> x, by rw id_map) open is_comm_applicative instance {f : Type u → Type w} {g : Type v → Type u} [applicative f] [applicative g] [is_comm_applicative f] [is_comm_applicative g] : is_comm_applicative (comp f g) := by { refine { .. @comp.is_lawful_applicative f g _ _ _ _, .. }, intros, casesm* comp _ _ _, simp! [map,has_seq.seq] with functor_norm, rw [commutative_map], simp [comp.mk,flip,(∘)] with functor_norm, congr, funext, rw [commutative_map], congr } end comp end functor open functor @[functor_norm] lemma comp.seq_mk {α β : Type w} {f : Type u → Type v} {g : Type w → Type u} [applicative f] [applicative g] (h : f (g (α → β))) (x : f (g α)) : comp.mk h <*> comp.mk x = comp.mk (has_seq.seq <$> h <*> x) := rfl instance {α} [has_one α] [has_mul α] : applicative (const α) := { pure := λ β x, (1 : α), seq := λ β γ f x, (f * x : α) } instance {α} [monoid α] : is_lawful_applicative (const α) := by refine { .. }; intros; simp [mul_assoc] instance {α} [has_zero α] [has_add α] : applicative (add_const α) := { pure := λ β x, (0 : α), seq := λ β γ f x, (f + x : α) } instance {α} [add_monoid α] : is_lawful_applicative (add_const α) := by refine { .. }; intros; simp [add_assoc]
56ccf7d5bc6a46d8d2625bb194535f657211cac0
e953c38599905267210b87fb5d82dcc3e52a4214
/hott/types/arrow.hlean
576e7d4b3ac3b7e7bf241982b02ee438165c21fa
[ "Apache-2.0" ]
permissive
c-cube/lean
563c1020bff98441c4f8ba60111fef6f6b46e31b
0fb52a9a139f720be418dafac35104468e293b66
refs/heads/master
1,610,753,294,113
1,440,451,356,000
1,440,499,588,000
41,748,334
0
0
null
1,441,122,656,000
1,441,122,656,000
null
UTF-8
Lean
false
false
2,760
hlean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Ported from Coq HoTT Theorems about arrow types (function spaces) -/ import types.pi open eq equiv is_equiv funext pi equiv.ops namespace pi variables {A A' : Type} {B B' : Type} {C : A → B → Type} {a a' a'' : A} {b b' b'' : B} {f g : A → B} -- all lemmas here are special cases of the ones for pi-types /- Functorial action -/ variables (f0 : A' → A) (f1 : B → B') definition arrow_functor : (A → B) → (A' → B') := pi_functor f0 (λa, f1) /- Equivalences -/ definition is_equiv_arrow_functor [H0 : is_equiv f0] [H1 : is_equiv f1] : is_equiv (arrow_functor f0 f1) := is_equiv_pi_functor f0 (λa, f1) definition arrow_equiv_arrow_rev (f0 : A' ≃ A) (f1 : B ≃ B') : (A → B) ≃ (A' → B') := equiv.mk _ (is_equiv_arrow_functor f0 f1) definition arrow_equiv_arrow (f0 : A ≃ A') (f1 : B ≃ B') : (A → B) ≃ (A' → B') := arrow_equiv_arrow_rev (equiv.symm f0) f1 definition arrow_equiv_arrow_right (f1 : B ≃ B') : (A → B) ≃ (A → B') := arrow_equiv_arrow_rev equiv.refl f1 definition arrow_equiv_arrow_left_rev (f0 : A' ≃ A) : (A → B) ≃ (A' → B) := arrow_equiv_arrow_rev f0 equiv.refl definition arrow_equiv_arrow_left (f0 : A ≃ A') : (A → B) ≃ (A' → B) := arrow_equiv_arrow f0 equiv.refl /- Transport -/ definition arrow_transport {B C : A → Type} (p : a = a') (f : B a → C a) : (transport (λa, B a → C a) p f) ~ (λb, p ▸ f (p⁻¹ ▸ b)) := eq.rec_on p (λx, idp) /- Pathovers -/ definition arrow_pathover {B C : A → Type} {f : B a → C a} {g : B a' → C a'} {p : a = a'} (r : Π(b : B a) (b' : B a') (q : b =[p] b'), f b =[p] g b') : f =[p] g := begin cases p, apply pathover_idp_of_eq, apply eq_of_homotopy, intro b, exact eq_of_pathover_idp (r b b idpo), end definition arrow_pathover_left {B C : A → Type} {f : B a → C a} {g : B a' → C a'} {p : a = a'} (r : Π(b : B a), f b =[p] g (p ▸ b)) : f =[p] g := begin cases p, apply pathover_idp_of_eq, apply eq_of_homotopy, intro b, exact eq_of_pathover_idp (r b), end definition arrow_pathover_right {B C : A → Type} {f : B a → C a} {g : B a' → C a'} {p : a = a'} (r : Π(b' : B a'), f (p⁻¹ ▸ b') =[p] g b') : f =[p] g := begin cases p, apply pathover_idp_of_eq, apply eq_of_homotopy, intro b, exact eq_of_pathover_idp (r b), end definition arrow_pathover_constant {B : Type} {C : A → Type} {f : B → C a} {g : B → C a'} {p : a = a'} (r : Π(b : B), f b =[p] g b) : f =[p] g := pi_pathover_constant r end pi
3eaa9f721d4b3b434751e8d6a3e89715fe1325e7
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/run/Reformat.lean
c72d229f0d20f95e797cd2c3e10edd7690ff970f
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,041
lean
/-! Parse and reformat file -/ import Lean.PrettyPrinter new_frontend open Lean open Lean.Elab open Lean.Elab.Term open Lean.Format unsafe def main (args : List String) : IO Unit := do let (debug, f) : Bool × String := match args with | [f, "-d"] => (true, f) | [f] => (false, f) | _ => panic! "usage: file [-d]"; let env ← mkEmptyEnvironment; let stx ← Lean.Parser.parseFile env args.head!; let (f, _) ← («finally» (PrettyPrinter.ppModule stx) printTraces).toIO { options := Options.empty.setBool `trace.PrettyPrinter.parenthesize debug } { env := env }; IO.print f; --stx' ← Lean.Parser.parseModule env args.head! (toString f); pure () -- TODO: this doesn't quite work yet because the parenthesizer adds unnecessary parentheses in one case /- when (stx' != stx) $ stx.getArgs.size.forM fun i => when (stx.getArg i != stx'.getArg i) $ throw $ IO.userError $ "reparsing failed:\n" ++ toString (stx.getArg i) ++ "\n" ++ toString (stx'.getArg i) -/ #eval main ["../../../src/Init/Core.lean"]
186c5f04ebaf12889011dd83bc2e065d59af733d
130c49f47783503e462c16b2eff31933442be6ff
/stage0/src/Lean/Elab/Tactic/ElabTerm.lean
63f3622c6f45bd851acde8fac5502ff09de99acd
[ "Apache-2.0" ]
permissive
Hazel-Brown/lean4
8aa5860e282435ffc30dcdfccd34006c59d1d39c
79e6732fc6bbf5af831b76f310f9c488d44e7a16
refs/heads/master
1,689,218,208,951
1,629,736,869,000
1,629,736,896,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,812
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.CollectMVars import Lean.Meta.Tactic.Apply import Lean.Meta.Tactic.Constructor import Lean.Meta.Tactic.Assert import Lean.Elab.Tactic.Basic import Lean.Elab.SyntheticMVars namespace Lean.Elab.Tactic open Meta /- `elabTerm` for Tactics and basic tactics that use it. -/ def elabTerm (stx : Syntax) (expectedType? : Option Expr) (mayPostpone := false) : TacticM Expr := do /- We have disabled `Term.withoutErrToSorry` to improve error recovery. When we were using it, any tactic using `elabTerm` would be interrupted at elaboration errors. Tactics that do not want to proceed should check whether the result contains sythetic sorrys or disable `errToSorry` before invoking `elabTerm` -/ withRef stx do -- <| Term.withoutErrToSorry do let e ← Term.elabTerm stx expectedType? Term.synthesizeSyntheticMVars mayPostpone instantiateMVars e def elabTermEnsuringType (stx : Syntax) (expectedType? : Option Expr) (mayPostpone := false) : TacticM Expr := do let e ← elabTerm stx expectedType? mayPostpone -- We do use `Term.ensureExpectedType` because we don't want coercions being inserted here. match expectedType? with | none => return e | some expectedType => let eType ← inferType e -- We allow synthetic opaque metavars to be assigned in the following step since the `isDefEq` is not really -- part of the elaboration, but part of the tactic. See issue #492 unless (← withAssignableSyntheticOpaque do isDefEq eType expectedType) do Term.throwTypeMismatchError none expectedType eType e return e /- Try to close main goal using `x target`, where `target` is the type of the main goal. -/ def closeMainGoalUsing (x : Expr → TacticM Expr) (checkUnassigned := true) : TacticM Unit := withMainContext do closeMainGoal (checkUnassigned := checkUnassigned) (← x (← getMainTarget)) private def logUnassignedAndAbort (mvarIds : Array MVarId) : TacticM Unit := do if (← Term.logUnassignedUsingErrorInfos mvarIds) then throwAbortTactic private def filterOldMVars (mvarIds : Array MVarId) (mvarCounterSaved : Nat) : MetaM (Array MVarId) := do let mctx ← getMCtx return mvarIds.filter fun mvarId => (mctx.getDecl mvarId |>.index) >= mvarCounterSaved @[builtinTactic «exact»] def evalExact : Tactic := fun stx => match stx with | `(tactic| exact $e) => closeMainGoalUsing (checkUnassigned := false) fun type => do let mvarCounterSaved := (← getMCtx).mvarCounter let r ← elabTermEnsuringType e type logUnassignedAndAbort (← filterOldMVars (← getMVars r) mvarCounterSaved) return r | _ => throwUnsupportedSyntax def elabTermWithHoles (stx : Syntax) (expectedType? : Option Expr) (tagSuffix : Name) (allowNaturalHoles := false) : TacticM (Expr × List MVarId) := do let mvarCounterSaved := (← getMCtx).mvarCounter let val ← elabTermEnsuringType stx expectedType? let newMVarIds ← getMVarsNoDelayed val /- ignore let-rec auxiliary variables, they are synthesized automatically later -/ let newMVarIds ← newMVarIds.filterM fun mvarId => return !(← Term.isLetRecAuxMVar mvarId) let newMVarIds ← if allowNaturalHoles then pure newMVarIds.toList else let naturalMVarIds ← newMVarIds.filterM fun mvarId => return (← getMVarDecl mvarId).kind.isNatural let syntheticMVarIds ← newMVarIds.filterM fun mvarId => return !(← getMVarDecl mvarId).kind.isNatural let naturalMVarIds ← filterOldMVars naturalMVarIds mvarCounterSaved logUnassignedAndAbort naturalMVarIds pure syntheticMVarIds.toList tagUntaggedGoals (← getMainTag) tagSuffix newMVarIds pure (val, newMVarIds) /- If `allowNaturalHoles == true`, then we allow the resultant expression to contain unassigned "natural" metavariables. Recall that "natutal" metavariables are created for explicit holes `_` and implicit arguments. They are meant to be filled by typing constraints. "Synthetic" metavariables are meant to be filled by tactics and are usually created using the synthetic hole notation `?<hole-name>`. -/ def refineCore (stx : Syntax) (tagSuffix : Name) (allowNaturalHoles : Bool) : TacticM Unit := do withMainContext do let (val, mvarIds') ← elabTermWithHoles stx (← getMainTarget) tagSuffix allowNaturalHoles assignExprMVar (← getMainGoal) val replaceMainGoal mvarIds' @[builtinTactic «refine»] def evalRefine : Tactic := fun stx => match stx with | `(tactic| refine $e) => refineCore e `refine (allowNaturalHoles := false) | _ => throwUnsupportedSyntax @[builtinTactic «refine'»] def evalRefine' : Tactic := fun stx => match stx with | `(tactic| refine' $e) => refineCore e `refine' (allowNaturalHoles := true) | _ => throwUnsupportedSyntax /-- Given a tactic ``` apply f ``` we want the `apply` tactic to create all metavariables. The following definition will return `@f` for `f`. That is, it will **not** create metavariables for implicit arguments. A similar method is also used in Lean 3. This method is useful when applying lemmas such as: ``` theorem infLeRight {s t : Set α} : s ⊓ t ≤ t ``` where `s ≤ t` here is defined as ``` ∀ {x : α}, x ∈ s → x ∈ t ``` -/ def elabTermForApply (stx : Syntax) : TacticM Expr := do if stx.isIdent then match (← Term.resolveId? stx (withInfo := true)) with | some e => return e | _ => pure () elabTerm stx none (mayPostpone := true) def evalApplyLikeTactic (tac : MVarId → Expr → MetaM (List MVarId)) (e : Syntax) : TacticM Unit := do withMainContext do let val ← elabTermForApply e let mvarIds' ← tac (← getMainGoal) val Term.synthesizeSyntheticMVarsNoPostponing replaceMainGoal mvarIds' @[builtinTactic Lean.Parser.Tactic.apply] def evalApply : Tactic := fun stx => match stx with | `(tactic| apply $e) => evalApplyLikeTactic Meta.apply e | _ => throwUnsupportedSyntax @[builtinTactic Lean.Parser.Tactic.constructor] def evalConstructor : Tactic := fun stx => withMainContext do let mvarIds' ← Meta.constructor (← getMainGoal) Term.synthesizeSyntheticMVarsNoPostponing replaceMainGoal mvarIds' @[builtinTactic Lean.Parser.Tactic.existsIntro] def evalExistsIntro : Tactic := fun stx => match stx with | `(tactic| exists $e) => evalApplyLikeTactic (fun mvarId e => return [(← Meta.existsIntro mvarId e)]) e | _ => throwUnsupportedSyntax @[builtinTactic Lean.Parser.Tactic.withReducible] def evalWithReducible : Tactic := fun stx => withReducible <| evalTactic stx[1] @[builtinTactic Lean.Parser.Tactic.withReducibleAndInstances] def evalWithReducibleAndInstances : Tactic := fun stx => withReducibleAndInstances <| evalTactic stx[1] /-- Elaborate `stx`. If it a free variable, return it. Otherwise, assert it, and return the free variable. Note that, the main goal is updated when `Meta.assert` is used in the second case. -/ def elabAsFVar (stx : Syntax) (userName? : Option Name := none) : TacticM FVarId := withMainContext do let e ← elabTerm stx none match e with | Expr.fvar fvarId _ => pure fvarId | _ => let type ← inferType e let intro (userName : Name) (preserveBinderNames : Bool) : TacticM FVarId := do let mvarId ← getMainGoal let (fvarId, mvarId) ← liftMetaM do let mvarId ← Meta.assert mvarId userName type e Meta.intro1Core mvarId preserveBinderNames replaceMainGoal [mvarId] return fvarId match userName? with | none => intro `h false | some userName => intro userName true @[builtinTactic Lean.Parser.Tactic.rename] def evalRename : Tactic := fun stx => match stx with | `(tactic| rename $typeStx:term => $h:ident) => do withMainContext do let fvarId ← withoutModifyingState <| withNewMCtxDepth do let type ← elabTerm typeStx none (mayPostpone := true) let fvarId? ← (← getLCtx).findDeclRevM? fun localDecl => do if (← isDefEq type localDecl.type) then return localDecl.fvarId else return none match fvarId? with | none => throwError "failed to find a hypothesis with type{indentExpr type}" | some fvarId => return fvarId let lctxNew := (← getLCtx).setUserName fvarId h.getId let mvarNew ← mkFreshExprMVarAt lctxNew (← getLocalInstances) (← getMainTarget) MetavarKind.syntheticOpaque (← getMainTag) assignExprMVar (← getMainGoal) mvarNew replaceMainGoal [mvarNew.mvarId!] | _ => throwUnsupportedSyntax /-- Make sure `expectedType` does not contain free and metavariables. It applies zeta-reduction to eliminate let-free-vars. -/ private def preprocessPropToDecide (expectedType : Expr) : TermElabM Expr := do let mut expectedType ← instantiateMVars expectedType if expectedType.hasFVar then expectedType ← zetaReduce expectedType if expectedType.hasFVar || expectedType.hasMVar then throwError "expected type must not contain free or meta variables{indentExpr expectedType}" return expectedType @[builtinTactic Lean.Parser.Tactic.decide] def evalDecide : Tactic := fun stx => closeMainGoalUsing fun expectedType => do let expectedType ← preprocessPropToDecide expectedType let d ← mkDecide expectedType let d ← instantiateMVars d let r ← withDefault <| whnf d unless r.isConstOf ``true do throwError "failed to reduce to 'true'{indentExpr r}" let s := d.appArg! -- get instance from `d` let rflPrf ← mkEqRefl (toExpr true) return mkApp3 (Lean.mkConst ``of_decide_eq_true) expectedType s rflPrf private def mkNativeAuxDecl (baseName : Name) (type val : Expr) : TermElabM Name := do let auxName ← Term.mkAuxName baseName let decl := Declaration.defnDecl { name := auxName, levelParams := [], type := type, value := val, hints := ReducibilityHints.abbrev, safety := DefinitionSafety.safe } addDecl decl compileDecl decl pure auxName @[builtinTactic Lean.Parser.Tactic.nativeDecide] def evalNativeDecide : Tactic := fun stx => closeMainGoalUsing fun expectedType => do let expectedType ← preprocessPropToDecide expectedType let d ← mkDecide expectedType let auxDeclName ← mkNativeAuxDecl `_nativeDecide (Lean.mkConst `Bool) d let rflPrf ← mkEqRefl (toExpr true) let s := d.appArg! -- get instance from `d` return mkApp3 (Lean.mkConst ``of_decide_eq_true) expectedType s <| mkApp3 (Lean.mkConst ``Lean.ofReduceBool) (Lean.mkConst auxDeclName) (toExpr true) rflPrf end Lean.Elab.Tactic
a3685cf53ce735ed9ebee3a77afc35d109f98e4f
a44280b79dc85615010e3fbda46abf82c6730fa3
/tests/playground/task_test4.lean
7ec3e69bba6003f6b1e6834a7ed80b9ae2d8e58e
[ "Apache-2.0" ]
permissive
kodyvajjha/lean4
8e1c613248b531d47367ca6e8d97ee1046645aa1
c8a045d69fac152fd5e3a577f718615cecb9c53d
refs/heads/master
1,589,684,450,102
1,555,200,447,000
1,556,139,945,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
437
lean
def run1 (i : Nat) (n : Nat) (xs : List Nat) : Nat := n.repeat (λ _ r, let s := (">> [" ++ toString i ++ "] " ++ toString r) in xs.foldl (+) (r + s.length)) 0 def main (xs : List String) : IO UInt32 := let ys := (List.repeat 1 xs.head.toNat) in let ts : List (Task Nat) := (List.iota 10).map (λ i, Task.mk $ λ _, run1 (i+1) xs.head.toNat ys) in let ns : List Nat := ts.map Task.get in IO.println (">> " ++ toString ns) *> pure 0
d0545b3c4d19fc9b81937771e8b35d9f11f1e3fe
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/algebra/ordered_ring.lean
a5e191ccfca4b595d159421199b104cee3e251fa
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
61,287
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro -/ import algebra.ordered_group import algebra.invertible import data.set.intervals.basic set_option old_structure_cmd true universe u variable {α : Type u} /-- An `ordered_semiring α` is a semiring `α` with a partial order such that multiplication with a positive number and addition are monotone. -/ @[protect_proj] class ordered_semiring (α : Type u) extends semiring α, ordered_cancel_add_comm_monoid α := (zero_le_one : 0 ≤ (1 : α)) (mul_lt_mul_of_pos_left : ∀ a b c : α, a < b → 0 < c → c * a < c * b) (mul_lt_mul_of_pos_right : ∀ a b c : α, a < b → 0 < c → a * c < b * c) section ordered_semiring variables [ordered_semiring α] {a b c d : α} lemma zero_le_one : 0 ≤ (1:α) := ordered_semiring.zero_le_one lemma zero_le_two : 0 ≤ (2:α) := add_nonneg zero_le_one zero_le_one lemma one_le_two : 1 ≤ (2:α) := calc (1:α) = 0 + 1 : (zero_add _).symm ... ≤ 1 + 1 : add_le_add_right zero_le_one _ section nontrivial variables [nontrivial α] lemma zero_lt_one : 0 < (1 : α) := lt_of_le_of_ne zero_le_one zero_ne_one lemma zero_lt_two : 0 < (2:α) := add_pos zero_lt_one zero_lt_one @[field_simps] lemma two_ne_zero : (2:α) ≠ 0 := ne.symm (ne_of_lt zero_lt_two) lemma one_lt_two : 1 < (2:α) := calc (2:α) = 1+1 : one_add_one_eq_two ... > 1+0 : add_lt_add_left zero_lt_one _ ... = 1 : add_zero 1 lemma zero_lt_three : 0 < (3:α) := add_pos zero_lt_two zero_lt_one lemma zero_lt_four : 0 < (4:α) := add_pos zero_lt_two zero_lt_two end nontrivial lemma mul_lt_mul_of_pos_left (h₁ : a < b) (h₂ : 0 < c) : c * a < c * b := ordered_semiring.mul_lt_mul_of_pos_left a b c h₁ h₂ lemma mul_lt_mul_of_pos_right (h₁ : a < b) (h₂ : 0 < c) : a * c < b * c := ordered_semiring.mul_lt_mul_of_pos_right a b c h₁ h₂ -- See Note [decidable namespace] protected lemma decidable.mul_le_mul_of_nonneg_left [@decidable_rel α (≤)] (h₁ : a ≤ b) (h₂ : 0 ≤ c) : c * a ≤ c * b := begin by_cases ba : b ≤ a, { simp [ba.antisymm h₁] }, by_cases c0 : c ≤ 0, { simp [c0.antisymm h₂] }, exact (mul_lt_mul_of_pos_left (h₁.lt_of_not_le ba) (h₂.lt_of_not_le c0)).le, end lemma mul_le_mul_of_nonneg_left : a ≤ b → 0 ≤ c → c * a ≤ c * b := by classical; exact decidable.mul_le_mul_of_nonneg_left -- See Note [decidable namespace] protected lemma decidable.mul_le_mul_of_nonneg_right [@decidable_rel α (≤)] (h₁ : a ≤ b) (h₂ : 0 ≤ c) : a * c ≤ b * c := begin by_cases ba : b ≤ a, { simp [ba.antisymm h₁] }, by_cases c0 : c ≤ 0, { simp [c0.antisymm h₂] }, exact (mul_lt_mul_of_pos_right (h₁.lt_of_not_le ba) (h₂.lt_of_not_le c0)).le, end lemma mul_le_mul_of_nonneg_right : a ≤ b → 0 ≤ c → a * c ≤ b * c := by classical; exact decidable.mul_le_mul_of_nonneg_right -- TODO: there are four variations, depending on which variables we assume to be nonneg -- See Note [decidable namespace] protected lemma decidable.mul_le_mul [@decidable_rel α (≤)] (hac : a ≤ c) (hbd : b ≤ d) (nn_b : 0 ≤ b) (nn_c : 0 ≤ c) : a * b ≤ c * d := calc a * b ≤ c * b : decidable.mul_le_mul_of_nonneg_right hac nn_b ... ≤ c * d : decidable.mul_le_mul_of_nonneg_left hbd nn_c lemma mul_le_mul : a ≤ c → b ≤ d → 0 ≤ b → 0 ≤ c → a * b ≤ c * d := by classical; exact decidable.mul_le_mul -- See Note [decidable namespace] protected lemma decidable.mul_nonneg_le_one_le {α : Type*} [ordered_semiring α] [@decidable_rel α (≤)] {a b c : α} (h₁ : 0 ≤ c) (h₂ : a ≤ c) (h₃ : 0 ≤ b) (h₄ : b ≤ 1) : a * b ≤ c := by simpa only [mul_one] using decidable.mul_le_mul h₂ h₄ h₃ h₁ lemma mul_nonneg_le_one_le {α : Type*} [ordered_semiring α] {a b c : α} : 0 ≤ c → a ≤ c → 0 ≤ b → b ≤ 1 → a * b ≤ c := by classical; exact decidable.mul_nonneg_le_one_le -- See Note [decidable namespace] protected lemma decidable.mul_nonneg [@decidable_rel α (≤)] (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a * b := have h : 0 * b ≤ a * b, from decidable.mul_le_mul_of_nonneg_right ha hb, by rwa [zero_mul] at h lemma mul_nonneg : 0 ≤ a → 0 ≤ b → 0 ≤ a * b := by classical; exact decidable.mul_nonneg -- See Note [decidable namespace] protected lemma decidable.mul_nonpos_of_nonneg_of_nonpos [@decidable_rel α (≤)] (ha : 0 ≤ a) (hb : b ≤ 0) : a * b ≤ 0 := have h : a * b ≤ a * 0, from decidable.mul_le_mul_of_nonneg_left hb ha, by rwa mul_zero at h lemma mul_nonpos_of_nonneg_of_nonpos : 0 ≤ a → b ≤ 0 → a * b ≤ 0 := by classical; exact decidable.mul_nonpos_of_nonneg_of_nonpos -- See Note [decidable namespace] protected lemma decidable.mul_nonpos_of_nonpos_of_nonneg [@decidable_rel α (≤)] (ha : a ≤ 0) (hb : 0 ≤ b) : a * b ≤ 0 := have h : a * b ≤ 0 * b, from decidable.mul_le_mul_of_nonneg_right ha hb, by rwa zero_mul at h lemma mul_nonpos_of_nonpos_of_nonneg : a ≤ 0 → 0 ≤ b → a * b ≤ 0 := by classical; exact decidable.mul_nonpos_of_nonpos_of_nonneg -- See Note [decidable namespace] protected lemma decidable.mul_lt_mul [@decidable_rel α (≤)] (hac : a < c) (hbd : b ≤ d) (pos_b : 0 < b) (nn_c : 0 ≤ c) : a * b < c * d := calc a * b < c * b : mul_lt_mul_of_pos_right hac pos_b ... ≤ c * d : decidable.mul_le_mul_of_nonneg_left hbd nn_c lemma mul_lt_mul : a < c → b ≤ d → 0 < b → 0 ≤ c → a * b < c * d := by classical; exact decidable.mul_lt_mul -- See Note [decidable namespace] protected lemma decidable.mul_lt_mul' [@decidable_rel α (≤)] (h1 : a ≤ c) (h2 : b < d) (h3 : 0 ≤ b) (h4 : 0 < c) : a * b < c * d := calc a * b ≤ c * b : decidable.mul_le_mul_of_nonneg_right h1 h3 ... < c * d : mul_lt_mul_of_pos_left h2 h4 lemma mul_lt_mul' : a ≤ c → b < d → 0 ≤ b → 0 < c → a * b < c * d := by classical; exact decidable.mul_lt_mul' lemma mul_pos (ha : 0 < a) (hb : 0 < b) : 0 < a * b := have h : 0 * b < a * b, from mul_lt_mul_of_pos_right ha hb, by rwa zero_mul at h lemma mul_neg_of_pos_of_neg (ha : 0 < a) (hb : b < 0) : a * b < 0 := have h : a * b < a * 0, from mul_lt_mul_of_pos_left hb ha, by rwa mul_zero at h lemma mul_neg_of_neg_of_pos (ha : a < 0) (hb : 0 < b) : a * b < 0 := have h : a * b < 0 * b, from mul_lt_mul_of_pos_right ha hb, by rwa zero_mul at h -- See Note [decidable namespace] protected lemma decidable.mul_self_lt_mul_self [@decidable_rel α (≤)] (h1 : 0 ≤ a) (h2 : a < b) : a * a < b * b := decidable.mul_lt_mul' h2.le h2 h1 $ h1.trans_lt h2 lemma mul_self_lt_mul_self (h1 : 0 ≤ a) (h2 : a < b) : a * a < b * b := mul_lt_mul' h2.le h2 h1 $ h1.trans_lt h2 -- See Note [decidable namespace] protected lemma decidable.strict_mono_incr_on_mul_self [@decidable_rel α (≤)] : strict_mono_incr_on (λ x : α, x * x) (set.Ici 0) := λ x hx y hy hxy, decidable.mul_self_lt_mul_self hx hxy lemma strict_mono_incr_on_mul_self : strict_mono_incr_on (λ x : α, x * x) (set.Ici 0) := λ x hx y hy hxy, mul_self_lt_mul_self hx hxy -- See Note [decidable namespace] protected lemma decidable.mul_self_le_mul_self [@decidable_rel α (≤)] (h1 : 0 ≤ a) (h2 : a ≤ b) : a * a ≤ b * b := decidable.mul_le_mul h2 h2 h1 $ h1.trans h2 lemma mul_self_le_mul_self (h1 : 0 ≤ a) (h2 : a ≤ b) : a * a ≤ b * b := mul_le_mul h2 h2 h1 $ h1.trans h2 -- See Note [decidable namespace] protected lemma decidable.mul_lt_mul'' [@decidable_rel α (≤)] (h1 : a < c) (h2 : b < d) (h3 : 0 ≤ a) (h4 : 0 ≤ b) : a * b < c * d := h4.lt_or_eq_dec.elim (λ b0, decidable.mul_lt_mul h1 h2.le b0 $ h3.trans h1.le) (λ b0, by rw [← b0, mul_zero]; exact mul_pos (h3.trans_lt h1) (h4.trans_lt h2)) lemma mul_lt_mul'' : a < c → b < d → 0 ≤ a → 0 ≤ b → a * b < c * d := by classical; exact decidable.mul_lt_mul'' -- See Note [decidable namespace] protected lemma decidable.le_mul_of_one_le_right [@decidable_rel α (≤)] (hb : 0 ≤ b) (h : 1 ≤ a) : b ≤ b * a := suffices b * 1 ≤ b * a, by rwa mul_one at this, decidable.mul_le_mul_of_nonneg_left h hb lemma le_mul_of_one_le_right : 0 ≤ b → 1 ≤ a → b ≤ b * a := by classical; exact decidable.le_mul_of_one_le_right -- See Note [decidable namespace] protected lemma decidable.le_mul_of_one_le_left [@decidable_rel α (≤)] (hb : 0 ≤ b) (h : 1 ≤ a) : b ≤ a * b := suffices 1 * b ≤ a * b, by rwa one_mul at this, decidable.mul_le_mul_of_nonneg_right h hb lemma le_mul_of_one_le_left : 0 ≤ b → 1 ≤ a → b ≤ a * b := by classical; exact decidable.le_mul_of_one_le_left -- See Note [decidable namespace] protected lemma decidable.lt_mul_of_one_lt_right [@decidable_rel α (≤)] (hb : 0 < b) (h : 1 < a) : b < b * a := suffices b * 1 < b * a, by rwa mul_one at this, decidable.mul_lt_mul' (le_refl _) h zero_le_one hb lemma lt_mul_of_one_lt_right : 0 < b → 1 < a → b < b * a := by classical; exact decidable.lt_mul_of_one_lt_right -- See Note [decidable namespace] protected lemma decidable.lt_mul_of_one_lt_left [@decidable_rel α (≤)] (hb : 0 < b) (h : 1 < a) : b < a * b := suffices 1 * b < a * b, by rwa one_mul at this, decidable.mul_lt_mul h (le_refl _) hb (zero_le_one.trans h.le) lemma lt_mul_of_one_lt_left : 0 < b → 1 < a → b < a * b := by classical; exact decidable.lt_mul_of_one_lt_left -- See Note [decidable namespace] protected lemma decidable.add_le_mul_two_add [@decidable_rel α (≤)] {a b : α} (a2 : 2 ≤ a) (b0 : 0 ≤ b) : a + (2 + b) ≤ a * (2 + b) := calc a + (2 + b) ≤ a + (a + a * b) : add_le_add_left (add_le_add a2 (decidable.le_mul_of_one_le_left b0 (one_le_two.trans a2))) a ... ≤ a * (2 + b) : by rw [mul_add, mul_two, add_assoc] lemma add_le_mul_two_add {a b : α} : 2 ≤ a → 0 ≤ b → a + (2 + b) ≤ a * (2 + b) := by classical; exact decidable.add_le_mul_two_add -- See Note [decidable namespace] protected lemma decidable.one_le_mul_of_one_le_of_one_le [@decidable_rel α (≤)] {a b : α} (a1 : 1 ≤ a) (b1 : 1 ≤ b) : (1 : α) ≤ a * b := (mul_one (1 : α)).symm.le.trans (decidable.mul_le_mul a1 b1 zero_le_one (zero_le_one.trans a1)) lemma one_le_mul_of_one_le_of_one_le {a b : α} : 1 ≤ a → 1 ≤ b → (1 : α) ≤ a * b := by classical; exact decidable.one_le_mul_of_one_le_of_one_le /-- Pullback an `ordered_semiring` under an injective map. -/ def function.injective.ordered_semiring {β : Type*} [has_zero β] [has_one β] [has_add β] [has_mul β] (f : β → α) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : ordered_semiring β := { zero_le_one := show f 0 ≤ f 1, by simp only [zero, one, zero_le_one], mul_lt_mul_of_pos_left := λ a b c ab c0, show f (c * a) < f (c * b), begin rw [mul, mul], refine mul_lt_mul_of_pos_left ab _, rwa ← zero, end, mul_lt_mul_of_pos_right := λ a b c ab c0, show f (a * c) < f (b * c), begin rw [mul, mul], refine mul_lt_mul_of_pos_right ab _, rwa ← zero, end, ..hf.ordered_cancel_add_comm_monoid f zero add, ..hf.semiring f zero one add mul } section variable [nontrivial α] lemma bit1_pos (h : 0 ≤ a) : 0 < bit1 a := lt_add_of_le_of_pos (add_nonneg h h) zero_lt_one lemma lt_add_one (a : α) : a < a + 1 := lt_add_of_le_of_pos le_rfl zero_lt_one lemma lt_one_add (a : α) : a < 1 + a := by { rw [add_comm], apply lt_add_one } end lemma bit1_pos' (h : 0 < a) : 0 < bit1 a := begin nontriviality, exact bit1_pos h.le, end -- See Note [decidable namespace] protected lemma decidable.one_lt_mul [@decidable_rel α (≤)] (ha : 1 ≤ a) (hb : 1 < b) : 1 < a * b := begin nontriviality, exact (one_mul (1 : α)) ▸ decidable.mul_lt_mul' ha hb zero_le_one (zero_lt_one.trans_le ha) end lemma one_lt_mul : 1 ≤ a → 1 < b → 1 < a * b := by classical; exact decidable.one_lt_mul -- See Note [decidable namespace] protected lemma decidable.mul_le_one [@decidable_rel α (≤)] (ha : a ≤ 1) (hb' : 0 ≤ b) (hb : b ≤ 1) : a * b ≤ 1 := begin rw ← one_mul (1 : α), apply decidable.mul_le_mul; {assumption <|> apply zero_le_one} end lemma mul_le_one : a ≤ 1 → 0 ≤ b → b ≤ 1 → a * b ≤ 1 := by classical; exact decidable.mul_le_one -- See Note [decidable namespace] protected lemma decidable.one_lt_mul_of_le_of_lt [@decidable_rel α (≤)] (ha : 1 ≤ a) (hb : 1 < b) : 1 < a * b := begin nontriviality, calc 1 = 1 * 1 : by rw one_mul ... < a * b : decidable.mul_lt_mul' ha hb zero_le_one (zero_lt_one.trans_le ha) end lemma one_lt_mul_of_le_of_lt : 1 ≤ a → 1 < b → 1 < a * b := by classical; exact decidable.one_lt_mul_of_le_of_lt -- See Note [decidable namespace] protected lemma decidable.one_lt_mul_of_lt_of_le [@decidable_rel α (≤)] (ha : 1 < a) (hb : 1 ≤ b) : 1 < a * b := begin nontriviality, calc 1 = 1 * 1 : by rw one_mul ... < a * b : decidable.mul_lt_mul ha hb zero_lt_one $ zero_le_one.trans ha.le end lemma one_lt_mul_of_lt_of_le : 1 < a → 1 ≤ b → 1 < a * b := by classical; exact decidable.one_lt_mul_of_lt_of_le -- See Note [decidable namespace] protected lemma decidable.mul_le_of_le_one_right [@decidable_rel α (≤)] (ha : 0 ≤ a) (hb1 : b ≤ 1) : a * b ≤ a := calc a * b ≤ a * 1 : decidable.mul_le_mul_of_nonneg_left hb1 ha ... = a : mul_one a lemma mul_le_of_le_one_right : 0 ≤ a → b ≤ 1 → a * b ≤ a := by classical; exact decidable.mul_le_of_le_one_right -- See Note [decidable namespace] protected lemma decidable.mul_le_of_le_one_left [@decidable_rel α (≤)] (hb : 0 ≤ b) (ha1 : a ≤ 1) : a * b ≤ b := calc a * b ≤ 1 * b : decidable.mul_le_mul ha1 le_rfl hb zero_le_one ... = b : one_mul b lemma mul_le_of_le_one_left : 0 ≤ b → a ≤ 1 → a * b ≤ b := by classical; exact decidable.mul_le_of_le_one_left -- See Note [decidable namespace] protected lemma decidable.mul_lt_one_of_nonneg_of_lt_one_left [@decidable_rel α (≤)] (ha0 : 0 ≤ a) (ha : a < 1) (hb : b ≤ 1) : a * b < 1 := calc a * b ≤ a : decidable.mul_le_of_le_one_right ha0 hb ... < 1 : ha lemma mul_lt_one_of_nonneg_of_lt_one_left : 0 ≤ a → a < 1 → b ≤ 1 → a * b < 1 := by classical; exact decidable.mul_lt_one_of_nonneg_of_lt_one_left -- See Note [decidable namespace] protected lemma decidable.mul_lt_one_of_nonneg_of_lt_one_right [@decidable_rel α (≤)] (ha : a ≤ 1) (hb0 : 0 ≤ b) (hb : b < 1) : a * b < 1 := calc a * b ≤ b : decidable.mul_le_of_le_one_left hb0 ha ... < 1 : hb lemma mul_lt_one_of_nonneg_of_lt_one_right : a ≤ 1 → 0 ≤ b → b < 1 → a * b < 1 := by classical; exact decidable.mul_lt_one_of_nonneg_of_lt_one_right end ordered_semiring section ordered_comm_semiring /-- An `ordered_comm_semiring α` is a commutative semiring `α` with a partial order such that multiplication with a positive number and addition are monotone. -/ @[protect_proj] class ordered_comm_semiring (α : Type u) extends ordered_semiring α, comm_semiring α /-- Pullback an `ordered_comm_semiring` under an injective map. -/ def function.injective.ordered_comm_semiring [ordered_comm_semiring α] {β : Type*} [has_zero β] [has_one β] [has_add β] [has_mul β] (f : β → α) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : ordered_comm_semiring β := { ..hf.comm_semiring f zero one add mul, ..hf.ordered_semiring f zero one add mul } end ordered_comm_semiring /-- A `linear_ordered_semiring α` is a nontrivial semiring `α` with a linear order such that multiplication with a positive number and addition are monotone. -/ -- It's not entirely clear we should assume `nontrivial` at this point; -- it would be reasonable to explore changing this, -- but be warned that the instances involving `domain` may cause -- typeclass search loops. @[protect_proj] class linear_ordered_semiring (α : Type u) extends ordered_semiring α, linear_order α, nontrivial α section linear_ordered_semiring variables [linear_ordered_semiring α] {a b c d : α} -- `norm_num` expects the lemma stating `0 < 1` to have a single typeclass argument -- (see `norm_num.prove_pos_nat`). -- Rather than working out how to relax that assumption, -- we provide a synonym for `zero_lt_one` (which needs both `ordered_semiring α` and `nontrivial α`) -- with only a `linear_ordered_semiring` typeclass argument. lemma zero_lt_one' : 0 < (1 : α) := zero_lt_one lemma lt_of_mul_lt_mul_left (h : c * a < c * b) (hc : 0 ≤ c) : a < b := by haveI := @linear_order.decidable_le α _; exact lt_of_not_ge (assume h1 : b ≤ a, have h2 : c * b ≤ c * a, from decidable.mul_le_mul_of_nonneg_left h1 hc, h2.not_lt h) lemma lt_of_mul_lt_mul_right (h : a * c < b * c) (hc : 0 ≤ c) : a < b := by haveI := @linear_order.decidable_le α _; exact lt_of_not_ge (assume h1 : b ≤ a, have h2 : b * c ≤ a * c, from decidable.mul_le_mul_of_nonneg_right h1 hc, h2.not_lt h) lemma le_of_mul_le_mul_left (h : c * a ≤ c * b) (hc : 0 < c) : a ≤ b := le_of_not_gt (assume h1 : b < a, have h2 : c * b < c * a, from mul_lt_mul_of_pos_left h1 hc, h2.not_le h) lemma le_of_mul_le_mul_right (h : a * c ≤ b * c) (hc : 0 < c) : a ≤ b := le_of_not_gt (assume h1 : b < a, have h2 : b * c < a * c, from mul_lt_mul_of_pos_right h1 hc, h2.not_le h) lemma pos_and_pos_or_neg_and_neg_of_mul_pos (hab : 0 < a * b) : (0 < a ∧ 0 < b) ∨ (a < 0 ∧ b < 0) := begin haveI := @linear_order.decidable_le α _, rcases lt_trichotomy 0 a with (ha|rfl|ha), { refine or.inl ⟨ha, lt_imp_lt_of_le_imp_le (λ hb, _) hab⟩, exact decidable.mul_nonpos_of_nonneg_of_nonpos ha.le hb }, { rw [zero_mul] at hab, exact hab.false.elim }, { refine or.inr ⟨ha, lt_imp_lt_of_le_imp_le (λ hb, _) hab⟩, exact decidable.mul_nonpos_of_nonpos_of_nonneg ha.le hb } end lemma nonneg_and_nonneg_or_nonpos_and_nonpos_of_mul_nnonneg (hab : 0 ≤ a * b) : (0 ≤ a ∧ 0 ≤ b) ∨ (a ≤ 0 ∧ b ≤ 0) := begin haveI := @linear_order.decidable_le α _, refine decidable.or_iff_not_and_not.2 _, simp only [not_and, not_le], intros ab nab, apply not_lt_of_le hab _, rcases lt_trichotomy 0 a with (ha|rfl|ha), exacts [mul_neg_of_pos_of_neg ha (ab ha.le), ((ab le_rfl).asymm (nab le_rfl)).elim, mul_neg_of_neg_of_pos ha (nab ha.le)] end lemma pos_of_mul_pos_left (h : 0 < a * b) (ha : 0 ≤ a) : 0 < b := ((pos_and_pos_or_neg_and_neg_of_mul_pos h).resolve_right $ λ h, h.1.not_le ha).2 lemma pos_of_mul_pos_right (h : 0 < a * b) (hb : 0 ≤ b) : 0 < a := ((pos_and_pos_or_neg_and_neg_of_mul_pos h).resolve_right $ λ h, h.2.not_le hb).1 @[simp] lemma inv_of_pos [invertible a] : 0 < ⅟a ↔ 0 < a := begin have : 0 < a * ⅟a, by simp only [mul_inv_of_self, zero_lt_one], exact ⟨λ h, pos_of_mul_pos_right this h.le, λ h, pos_of_mul_pos_left this h.le⟩ end @[simp] lemma inv_of_nonpos [invertible a] : ⅟a ≤ 0 ↔ a ≤ 0 := by simp only [← not_lt, inv_of_pos] lemma nonneg_of_mul_nonneg_left (h : 0 ≤ a * b) (h1 : 0 < a) : 0 ≤ b := le_of_not_gt (assume h2 : b < 0, (mul_neg_of_pos_of_neg h1 h2).not_le h) lemma nonneg_of_mul_nonneg_right (h : 0 ≤ a * b) (h1 : 0 < b) : 0 ≤ a := le_of_not_gt (assume h2 : a < 0, (mul_neg_of_neg_of_pos h2 h1).not_le h) @[simp] lemma inv_of_nonneg [invertible a] : 0 ≤ ⅟a ↔ 0 ≤ a := begin have : 0 < a * ⅟a, by simp only [mul_inv_of_self, zero_lt_one], exact ⟨λ h, (pos_of_mul_pos_right this h).le, λ h, (pos_of_mul_pos_left this h).le⟩ end @[simp] lemma inv_of_lt_zero [invertible a] : ⅟a < 0 ↔ a < 0 := by simp only [← not_le, inv_of_nonneg] @[simp] lemma inv_of_le_one [invertible a] (h : 1 ≤ a) : ⅟a ≤ 1 := by haveI := @linear_order.decidable_le α _; exact mul_inv_of_self a ▸ decidable.le_mul_of_one_le_left (inv_of_nonneg.2 $ zero_le_one.trans h) h lemma neg_of_mul_neg_left (h : a * b < 0) (h1 : 0 ≤ a) : b < 0 := by haveI := @linear_order.decidable_le α _; exact lt_of_not_ge (assume h2 : b ≥ 0, (decidable.mul_nonneg h1 h2).not_lt h) lemma neg_of_mul_neg_right (h : a * b < 0) (h1 : 0 ≤ b) : a < 0 := by haveI := @linear_order.decidable_le α _; exact lt_of_not_ge (assume h2 : a ≥ 0, (decidable.mul_nonneg h2 h1).not_lt h) lemma nonpos_of_mul_nonpos_left (h : a * b ≤ 0) (h1 : 0 < a) : b ≤ 0 := le_of_not_gt (assume h2 : b > 0, (mul_pos h1 h2).not_le h) lemma nonpos_of_mul_nonpos_right (h : a * b ≤ 0) (h1 : 0 < b) : a ≤ 0 := le_of_not_gt (assume h2 : a > 0, (mul_pos h2 h1).not_le h) @[simp] lemma mul_le_mul_left (h : 0 < c) : c * a ≤ c * b ↔ a ≤ b := by haveI := @linear_order.decidable_le α _; exact ⟨λ h', le_of_mul_le_mul_left h' h, λ h', decidable.mul_le_mul_of_nonneg_left h' h.le⟩ @[simp] lemma mul_le_mul_right (h : 0 < c) : a * c ≤ b * c ↔ a ≤ b := by haveI := @linear_order.decidable_le α _; exact ⟨λ h', le_of_mul_le_mul_right h' h, λ h', decidable.mul_le_mul_of_nonneg_right h' h.le⟩ @[simp] lemma mul_lt_mul_left (h : 0 < c) : c * a < c * b ↔ a < b := by haveI := @linear_order.decidable_le α _; exact ⟨lt_imp_lt_of_le_imp_le $ λ h', decidable.mul_le_mul_of_nonneg_left h' h.le, λ h', mul_lt_mul_of_pos_left h' h⟩ @[simp] lemma mul_lt_mul_right (h : 0 < c) : a * c < b * c ↔ a < b := by haveI := @linear_order.decidable_le α _; exact ⟨lt_imp_lt_of_le_imp_le $ λ h', decidable.mul_le_mul_of_nonneg_right h' h.le, λ h', mul_lt_mul_of_pos_right h' h⟩ @[simp] lemma zero_le_mul_left (h : 0 < c) : 0 ≤ c * b ↔ 0 ≤ b := by { convert mul_le_mul_left h, simp } @[simp] lemma zero_le_mul_right (h : 0 < c) : 0 ≤ b * c ↔ 0 ≤ b := by { convert mul_le_mul_right h, simp } @[simp] lemma zero_lt_mul_left (h : 0 < c) : 0 < c * b ↔ 0 < b := by { convert mul_lt_mul_left h, simp } @[simp] lemma zero_lt_mul_right (h : 0 < c) : 0 < b * c ↔ 0 < b := by { convert mul_lt_mul_right h, simp } lemma add_le_mul_of_left_le_right (a2 : 2 ≤ a) (ab : a ≤ b) : a + b ≤ a * b := have 0 < b, from calc 0 < 2 : zero_lt_two ... ≤ a : a2 ... ≤ b : ab, calc a + b ≤ b + b : add_le_add_right ab b ... = 2 * b : (two_mul b).symm ... ≤ a * b : (mul_le_mul_right this).mpr a2 lemma add_le_mul_of_right_le_left (b2 : 2 ≤ b) (ba : b ≤ a) : a + b ≤ a * b := have 0 < a, from calc 0 < 2 : zero_lt_two ... ≤ b : b2 ... ≤ a : ba, calc a + b ≤ a + a : add_le_add_left ba a ... = a * 2 : (mul_two a).symm ... ≤ a * b : (mul_le_mul_left this).mpr b2 lemma add_le_mul (a2 : 2 ≤ a) (b2 : 2 ≤ b) : a + b ≤ a * b := if hab : a ≤ b then add_le_mul_of_left_le_right a2 hab else add_le_mul_of_right_le_left b2 (le_of_not_le hab) lemma add_le_mul' (a2 : 2 ≤ a) (b2 : 2 ≤ b) : a + b ≤ b * a := (le_of_eq (add_comm _ _)).trans (add_le_mul b2 a2) section variables [nontrivial α] @[simp] lemma bit0_le_bit0 : bit0 a ≤ bit0 b ↔ a ≤ b := by rw [bit0, bit0, ← two_mul, ← two_mul, mul_le_mul_left (zero_lt_two : 0 < (2:α))] @[simp] lemma bit0_lt_bit0 : bit0 a < bit0 b ↔ a < b := by rw [bit0, bit0, ← two_mul, ← two_mul, mul_lt_mul_left (zero_lt_two : 0 < (2:α))] @[simp] lemma bit1_le_bit1 : bit1 a ≤ bit1 b ↔ a ≤ b := (add_le_add_iff_right 1).trans bit0_le_bit0 @[simp] lemma bit1_lt_bit1 : bit1 a < bit1 b ↔ a < b := (add_lt_add_iff_right 1).trans bit0_lt_bit0 @[simp] lemma one_le_bit1 : (1 : α) ≤ bit1 a ↔ 0 ≤ a := by rw [bit1, le_add_iff_nonneg_left, bit0, ← two_mul, zero_le_mul_left (zero_lt_two : 0 < (2:α))] @[simp] lemma one_lt_bit1 : (1 : α) < bit1 a ↔ 0 < a := by rw [bit1, lt_add_iff_pos_left, bit0, ← two_mul, zero_lt_mul_left (zero_lt_two : 0 < (2:α))] @[simp] lemma zero_le_bit0 : (0 : α) ≤ bit0 a ↔ 0 ≤ a := by rw [bit0, ← two_mul, zero_le_mul_left (zero_lt_two : 0 < (2:α))] @[simp] lemma zero_lt_bit0 : (0 : α) < bit0 a ↔ 0 < a := by rw [bit0, ← two_mul, zero_lt_mul_left (zero_lt_two : 0 < (2:α))] end lemma le_mul_iff_one_le_left (hb : 0 < b) : b ≤ a * b ↔ 1 ≤ a := suffices 1 * b ≤ a * b ↔ 1 ≤ a, by rwa one_mul at this, mul_le_mul_right hb lemma lt_mul_iff_one_lt_left (hb : 0 < b) : b < a * b ↔ 1 < a := suffices 1 * b < a * b ↔ 1 < a, by rwa one_mul at this, mul_lt_mul_right hb lemma le_mul_iff_one_le_right (hb : 0 < b) : b ≤ b * a ↔ 1 ≤ a := suffices b * 1 ≤ b * a ↔ 1 ≤ a, by rwa mul_one at this, mul_le_mul_left hb lemma lt_mul_iff_one_lt_right (hb : 0 < b) : b < b * a ↔ 1 < a := suffices b * 1 < b * a ↔ 1 < a, by rwa mul_one at this, mul_lt_mul_left hb theorem mul_nonneg_iff_right_nonneg_of_pos (ha : 0 < a) : 0 ≤ b * a ↔ 0 ≤ b := by haveI := @linear_order.decidable_le α _; exact ⟨λ h, nonneg_of_mul_nonneg_right h ha, λ h, decidable.mul_nonneg h ha.le⟩ lemma mul_le_iff_le_one_left (hb : 0 < b) : a * b ≤ b ↔ a ≤ 1 := ⟨ λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_left hb).2 h.not_lt), λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_left hb).1 h.not_lt) ⟩ lemma mul_lt_iff_lt_one_left (hb : 0 < b) : a * b < b ↔ a < 1 := ⟨ λ h, lt_of_not_ge (mt (le_mul_iff_one_le_left hb).2 h.not_le), λ h, lt_of_not_ge (mt (le_mul_iff_one_le_left hb).1 h.not_le) ⟩ lemma mul_le_iff_le_one_right (hb : 0 < b) : b * a ≤ b ↔ a ≤ 1 := ⟨ λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_right hb).2 h.not_lt), λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_right hb).1 h.not_lt) ⟩ lemma mul_lt_iff_lt_one_right (hb : 0 < b) : b * a < b ↔ a < 1 := ⟨ λ h, lt_of_not_ge (mt (le_mul_iff_one_le_right hb).2 h.not_le), λ h, lt_of_not_ge (mt (le_mul_iff_one_le_right hb).1 h.not_le) ⟩ lemma nonpos_of_mul_nonneg_left (h : 0 ≤ a * b) (hb : b < 0) : a ≤ 0 := le_of_not_gt (λ ha, absurd h (mul_neg_of_pos_of_neg ha hb).not_le) lemma nonpos_of_mul_nonneg_right (h : 0 ≤ a * b) (ha : a < 0) : b ≤ 0 := le_of_not_gt (λ hb, absurd h (mul_neg_of_neg_of_pos ha hb).not_le) lemma neg_of_mul_pos_left (h : 0 < a * b) (hb : b ≤ 0) : a < 0 := by haveI := @linear_order.decidable_le α _; exact lt_of_not_ge (λ ha, absurd h (decidable.mul_nonpos_of_nonneg_of_nonpos ha hb).not_lt) lemma neg_of_mul_pos_right (h : 0 < a * b) (ha : a ≤ 0) : b < 0 := by haveI := @linear_order.decidable_le α _; exact lt_of_not_ge (λ hb, absurd h (decidable.mul_nonpos_of_nonpos_of_nonneg ha hb).not_lt) @[priority 100] -- see Note [lower instance priority] instance linear_ordered_semiring.to_no_top_order {α : Type*} [linear_ordered_semiring α] : no_top_order α := ⟨assume a, ⟨a + 1, lt_add_of_pos_right _ zero_lt_one⟩⟩ /-- Pullback a `linear_ordered_semiring` under an injective map. -/ def function.injective.linear_ordered_semiring {β : Type*} [has_zero β] [has_one β] [has_add β] [has_mul β] [nontrivial β] (f : β → α) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : linear_ordered_semiring β := { ..linear_order.lift f hf, ..‹nontrivial β›, ..hf.ordered_semiring f zero one add mul } end linear_ordered_semiring section mono variables {β : Type*} [linear_ordered_semiring α] [preorder β] {f g : β → α} {a : α} lemma monotone_mul_left_of_nonneg (ha : 0 ≤ a) : monotone (λ x, a*x) := by haveI := @linear_order.decidable_le α _; exact assume b c b_le_c, decidable.mul_le_mul_of_nonneg_left b_le_c ha lemma monotone_mul_right_of_nonneg (ha : 0 ≤ a) : monotone (λ x, x*a) := by haveI := @linear_order.decidable_le α _; exact assume b c b_le_c, decidable.mul_le_mul_of_nonneg_right b_le_c ha lemma monotone.mul_const (hf : monotone f) (ha : 0 ≤ a) : monotone (λ x, (f x) * a) := (monotone_mul_right_of_nonneg ha).comp hf lemma monotone.const_mul (hf : monotone f) (ha : 0 ≤ a) : monotone (λ x, a * (f x)) := (monotone_mul_left_of_nonneg ha).comp hf lemma monotone.mul (hf : monotone f) (hg : monotone g) (hf0 : ∀ x, 0 ≤ f x) (hg0 : ∀ x, 0 ≤ g x) : monotone (λ x, f x * g x) := by haveI := @linear_order.decidable_le α _; exact λ x y h, decidable.mul_le_mul (hf h) (hg h) (hg0 x) (hf0 y) lemma strict_mono_mul_left_of_pos (ha : 0 < a) : strict_mono (λ x, a * x) := assume b c b_lt_c, (mul_lt_mul_left ha).2 b_lt_c lemma strict_mono_mul_right_of_pos (ha : 0 < a) : strict_mono (λ x, x * a) := assume b c b_lt_c, (mul_lt_mul_right ha).2 b_lt_c lemma strict_mono.mul_const (hf : strict_mono f) (ha : 0 < a) : strict_mono (λ x, (f x) * a) := (strict_mono_mul_right_of_pos ha).comp hf lemma strict_mono.const_mul (hf : strict_mono f) (ha : 0 < a) : strict_mono (λ x, a * (f x)) := (strict_mono_mul_left_of_pos ha).comp hf lemma strict_mono.mul_monotone (hf : strict_mono f) (hg : monotone g) (hf0 : ∀ x, 0 ≤ f x) (hg0 : ∀ x, 0 < g x) : strict_mono (λ x, f x * g x) := by haveI := @linear_order.decidable_le α _; exact λ x y h, decidable.mul_lt_mul (hf h) (hg h.le) (hg0 x) (hf0 y) lemma monotone.mul_strict_mono (hf : monotone f) (hg : strict_mono g) (hf0 : ∀ x, 0 < f x) (hg0 : ∀ x, 0 ≤ g x) : strict_mono (λ x, f x * g x) := by haveI := @linear_order.decidable_le α _; exact λ x y h, decidable.mul_lt_mul' (hf h.le) (hg h) (hg0 x) (hf0 y) lemma strict_mono.mul (hf : strict_mono f) (hg : strict_mono g) (hf0 : ∀ x, 0 ≤ f x) (hg0 : ∀ x, 0 ≤ g x) : strict_mono (λ x, f x * g x) := by haveI := @linear_order.decidable_le α _; exact λ x y h, decidable.mul_lt_mul'' (hf h) (hg h) (hf0 x) (hg0 x) end mono section linear_ordered_semiring variables [linear_ordered_semiring α] {a b c : α} lemma mul_max_of_nonneg (b c : α) (ha : 0 ≤ a) : a * max b c = max (a * b) (a * c) := (monotone_mul_left_of_nonneg ha).map_max lemma mul_min_of_nonneg (b c : α) (ha : 0 ≤ a) : a * min b c = min (a * b) (a * c) := (monotone_mul_left_of_nonneg ha).map_min lemma max_mul_of_nonneg (a b : α) (hc : 0 ≤ c) : max a b * c = max (a * c) (b * c) := (monotone_mul_right_of_nonneg hc).map_max lemma min_mul_of_nonneg (a b : α) (hc : 0 ≤ c) : min a b * c = min (a * c) (b * c) := (monotone_mul_right_of_nonneg hc).map_min end linear_ordered_semiring /-- An `ordered_ring α` is a ring `α` with a partial order such that multiplication with a positive number and addition are monotone. -/ @[protect_proj] class ordered_ring (α : Type u) extends ring α, ordered_add_comm_group α := (zero_le_one : 0 ≤ (1 : α)) (mul_pos : ∀ a b : α, 0 < a → 0 < b → 0 < a * b) section ordered_ring variables [ordered_ring α] {a b c : α} -- See Note [decidable namespace] protected lemma decidable.ordered_ring.mul_nonneg [@decidable_rel α (≤)] {a b : α} (h₁ : 0 ≤ a) (h₂ : 0 ≤ b) : 0 ≤ a * b := begin by_cases ha : a ≤ 0, { simp [le_antisymm ha h₁] }, by_cases hb : b ≤ 0, { simp [le_antisymm hb h₂] }, exact (le_not_le_of_lt (ordered_ring.mul_pos a b (h₁.lt_of_not_le ha) (h₂.lt_of_not_le hb))).1, end lemma ordered_ring.mul_nonneg : 0 ≤ a → 0 ≤ b → 0 ≤ a * b := by classical; exact decidable.ordered_ring.mul_nonneg -- See Note [decidable namespace] protected lemma decidable.ordered_ring.mul_le_mul_of_nonneg_left [@decidable_rel α (≤)] (h₁ : a ≤ b) (h₂ : 0 ≤ c) : c * a ≤ c * b := begin rw [← sub_nonneg, ← mul_sub], exact decidable.ordered_ring.mul_nonneg h₂ (sub_nonneg.2 h₁), end lemma ordered_ring.mul_le_mul_of_nonneg_left : a ≤ b → 0 ≤ c → c * a ≤ c * b := by classical; exact decidable.ordered_ring.mul_le_mul_of_nonneg_left -- See Note [decidable namespace] protected lemma decidable.ordered_ring.mul_le_mul_of_nonneg_right [@decidable_rel α (≤)] (h₁ : a ≤ b) (h₂ : 0 ≤ c) : a * c ≤ b * c := begin rw [← sub_nonneg, ← sub_mul], exact decidable.ordered_ring.mul_nonneg (sub_nonneg.2 h₁) h₂, end lemma ordered_ring.mul_le_mul_of_nonneg_right : a ≤ b → 0 ≤ c → a * c ≤ b * c := by classical; exact decidable.ordered_ring.mul_le_mul_of_nonneg_right lemma ordered_ring.mul_lt_mul_of_pos_left (h₁ : a < b) (h₂ : 0 < c) : c * a < c * b := begin rw [← sub_pos, ← mul_sub], exact ordered_ring.mul_pos _ _ h₂ (sub_pos.2 h₁), end lemma ordered_ring.mul_lt_mul_of_pos_right (h₁ : a < b) (h₂ : 0 < c) : a * c < b * c := begin rw [← sub_pos, ← sub_mul], exact ordered_ring.mul_pos _ _ (sub_pos.2 h₁) h₂, end @[priority 100] -- see Note [lower instance priority] instance ordered_ring.to_ordered_semiring : ordered_semiring α := { mul_zero := mul_zero, zero_mul := zero_mul, add_left_cancel := @add_left_cancel α _, le_of_add_le_add_left := @le_of_add_le_add_left α _ _ _, mul_lt_mul_of_pos_left := @ordered_ring.mul_lt_mul_of_pos_left α _, mul_lt_mul_of_pos_right := @ordered_ring.mul_lt_mul_of_pos_right α _, ..‹ordered_ring α› } -- See Note [decidable namespace] protected lemma decidable.mul_le_mul_of_nonpos_left [@decidable_rel α (≤)] {a b c : α} (h : b ≤ a) (hc : c ≤ 0) : c * a ≤ c * b := have -c ≥ 0, from neg_nonneg_of_nonpos hc, have -c * b ≤ -c * a, from decidable.mul_le_mul_of_nonneg_left h this, have -(c * b) ≤ -(c * a), by rwa [← neg_mul_eq_neg_mul, ← neg_mul_eq_neg_mul] at this, le_of_neg_le_neg this lemma mul_le_mul_of_nonpos_left {a b c : α} : b ≤ a → c ≤ 0 → c * a ≤ c * b := by classical; exact decidable.mul_le_mul_of_nonpos_left -- See Note [decidable namespace] protected lemma decidable.mul_le_mul_of_nonpos_right [@decidable_rel α (≤)] {a b c : α} (h : b ≤ a) (hc : c ≤ 0) : a * c ≤ b * c := have -c ≥ 0, from neg_nonneg_of_nonpos hc, have b * -c ≤ a * -c, from decidable.mul_le_mul_of_nonneg_right h this, have -(b * c) ≤ -(a * c), by rwa [← neg_mul_eq_mul_neg, ← neg_mul_eq_mul_neg] at this, le_of_neg_le_neg this lemma mul_le_mul_of_nonpos_right {a b c : α} : b ≤ a → c ≤ 0 → a * c ≤ b * c := by classical; exact decidable.mul_le_mul_of_nonpos_right -- See Note [decidable namespace] protected lemma decidable.mul_nonneg_of_nonpos_of_nonpos [@decidable_rel α (≤)] {a b : α} (ha : a ≤ 0) (hb : b ≤ 0) : 0 ≤ a * b := have 0 * b ≤ a * b, from decidable.mul_le_mul_of_nonpos_right ha hb, by rwa zero_mul at this lemma mul_nonneg_of_nonpos_of_nonpos {a b : α} : a ≤ 0 → b ≤ 0 → 0 ≤ a * b := by classical; exact decidable.mul_nonneg_of_nonpos_of_nonpos lemma mul_lt_mul_of_neg_left {a b c : α} (h : b < a) (hc : c < 0) : c * a < c * b := have -c > 0, from neg_pos_of_neg hc, have -c * b < -c * a, from mul_lt_mul_of_pos_left h this, have -(c * b) < -(c * a), by rwa [← neg_mul_eq_neg_mul, ← neg_mul_eq_neg_mul] at this, lt_of_neg_lt_neg this lemma mul_lt_mul_of_neg_right {a b c : α} (h : b < a) (hc : c < 0) : a * c < b * c := have -c > 0, from neg_pos_of_neg hc, have b * -c < a * -c, from mul_lt_mul_of_pos_right h this, have -(b * c) < -(a * c), by rwa [← neg_mul_eq_mul_neg, ← neg_mul_eq_mul_neg] at this, lt_of_neg_lt_neg this lemma mul_pos_of_neg_of_neg {a b : α} (ha : a < 0) (hb : b < 0) : 0 < a * b := have 0 * b < a * b, from mul_lt_mul_of_neg_right ha hb, by rwa zero_mul at this /-- Pullback an `ordered_ring` under an injective map. -/ def function.injective.ordered_ring {β : Type*} [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] (f : β → α) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (- x) = - f x) (sub : ∀ x y, f (x - y) = f x - f y) : ordered_ring β := { mul_pos := λ a b a0 b0, show f 0 < f (a * b), by { rw [zero, mul], apply mul_pos; rwa ← zero }, ..hf.ordered_semiring f zero one add mul, ..hf.ring f zero one add mul neg sub } end ordered_ring section ordered_comm_ring /-- An `ordered_comm_ring α` is a commutative ring `α` with a partial order such that multiplication with a positive number and addition are monotone. -/ @[protect_proj] class ordered_comm_ring (α : Type u) extends ordered_ring α, ordered_comm_semiring α, comm_ring α /-- Pullback an `ordered_comm_ring` under an injective map. -/ def function.injective.ordered_comm_ring [ordered_comm_ring α] {β : Type*} [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] (f : β → α) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (- x) = - f x) (sub : ∀ x y, f (x - y) = f x - f y) : ordered_comm_ring β := { ..hf.ordered_comm_semiring f zero one add mul, ..hf.ordered_ring f zero one add mul neg sub, ..hf.comm_ring f zero one add mul neg sub } end ordered_comm_ring /-- A `linear_ordered_ring α` is a ring `α` with a linear order such that multiplication with a positive number and addition are monotone. -/ @[protect_proj] class linear_ordered_ring (α : Type u) extends ordered_ring α, linear_order α, nontrivial α @[priority 100] -- see Note [lower instance priority] instance linear_ordered_ring.to_linear_ordered_add_comm_group [s : linear_ordered_ring α] : linear_ordered_add_comm_group α := { .. s } section linear_ordered_ring variables [linear_ordered_ring α] {a b c : α} @[priority 100] -- see Note [lower instance priority] instance linear_ordered_ring.to_linear_ordered_semiring : linear_ordered_semiring α := { mul_zero := mul_zero, zero_mul := zero_mul, add_left_cancel := @add_left_cancel α _, le_of_add_le_add_left := @le_of_add_le_add_left α _ _ _, mul_lt_mul_of_pos_left := @mul_lt_mul_of_pos_left α _, mul_lt_mul_of_pos_right := @mul_lt_mul_of_pos_right α _, le_total := linear_ordered_ring.le_total, ..‹linear_ordered_ring α› } @[priority 100] -- see Note [lower instance priority] instance linear_ordered_ring.to_domain : domain α := { eq_zero_or_eq_zero_of_mul_eq_zero := begin intros a b hab, refine decidable.or_iff_not_and_not.2 (λ h, _), revert hab, cases lt_or_gt_of_ne h.1 with ha ha; cases lt_or_gt_of_ne h.2 with hb hb, exacts [(mul_pos_of_neg_of_neg ha hb).ne.symm, (mul_neg_of_neg_of_pos ha hb).ne, (mul_neg_of_pos_of_neg ha hb).ne, (mul_pos ha hb).ne.symm] end, .. ‹linear_ordered_ring α› } @[simp] lemma abs_one : abs (1 : α) = 1 := abs_of_pos zero_lt_one @[simp] lemma abs_two : abs (2 : α) = 2 := abs_of_pos zero_lt_two lemma abs_mul (a b : α) : abs (a * b) = abs a * abs b := begin haveI := @linear_order.decidable_le α _, rw [abs_eq (decidable.mul_nonneg (abs_nonneg a) (abs_nonneg b))], cases le_total a 0 with ha ha; cases le_total b 0 with hb hb; simp only [abs_of_nonpos, abs_of_nonneg, true_or, or_true, eq_self_iff_true, neg_mul_eq_neg_mul_symm, mul_neg_eq_neg_mul_symm, neg_neg, *] end /-- `abs` as a `monoid_with_zero_hom`. -/ def abs_hom : monoid_with_zero_hom α α := ⟨abs, abs_zero, abs_one, abs_mul⟩ @[simp] 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) @[simp] lemma abs_mul_self (a : α) : abs (a * a) = a * a := by rw [abs_mul, abs_mul_abs_self] lemma mul_pos_iff : 0 < a * b ↔ 0 < a ∧ 0 < b ∨ a < 0 ∧ b < 0 := ⟨pos_and_pos_or_neg_and_neg_of_mul_pos, λ h, h.elim (and_imp.2 mul_pos) (and_imp.2 mul_pos_of_neg_of_neg)⟩ lemma mul_neg_iff : a * b < 0 ↔ 0 < a ∧ b < 0 ∨ a < 0 ∧ 0 < b := by rw [← neg_pos, neg_mul_eq_mul_neg, mul_pos_iff, neg_pos, neg_lt_zero] lemma mul_nonneg_iff : 0 ≤ a * b ↔ 0 ≤ a ∧ 0 ≤ b ∨ a ≤ 0 ∧ b ≤ 0 := by haveI := @linear_order.decidable_le α _; exact ⟨nonneg_and_nonneg_or_nonpos_and_nonpos_of_mul_nnonneg, λ h, h.elim (and_imp.2 decidable.mul_nonneg) (and_imp.2 decidable.mul_nonneg_of_nonpos_of_nonpos)⟩ lemma mul_nonpos_iff : a * b ≤ 0 ↔ 0 ≤ a ∧ b ≤ 0 ∨ a ≤ 0 ∧ 0 ≤ b := by rw [← neg_nonneg, neg_mul_eq_mul_neg, mul_nonneg_iff, neg_nonneg, neg_nonpos] lemma mul_self_nonneg (a : α) : 0 ≤ a * a := abs_mul_self a ▸ abs_nonneg _ @[simp] lemma neg_le_self_iff : -a ≤ a ↔ 0 ≤ a := by simp [neg_le_iff_add_nonneg, ← two_mul, mul_nonneg_iff, zero_le_one, (@zero_lt_two α _ _).not_le] @[simp] lemma neg_lt_self_iff : -a < a ↔ 0 < a := by simp [neg_lt_iff_pos_add, ← two_mul, mul_pos_iff, zero_lt_one, (@zero_lt_two α _ _).not_lt] @[simp] lemma le_neg_self_iff : a ≤ -a ↔ a ≤ 0 := calc a ≤ -a ↔ -(-a) ≤ -a : by rw neg_neg ... ↔ 0 ≤ -a : neg_le_self_iff ... ↔ a ≤ 0 : neg_nonneg @[simp] lemma lt_neg_self_iff : a < -a ↔ a < 0 := calc a < -a ↔ -(-a) < -a : by rw neg_neg ... ↔ 0 < -a : neg_lt_self_iff ... ↔ a < 0 : neg_pos @[simp] lemma abs_eq_self : abs a = a ↔ 0 ≤ a := by simp [abs] @[simp] lemma abs_eq_neg_self : abs a = -a ↔ a ≤ 0 := by simp [abs] lemma gt_of_mul_lt_mul_neg_left (h : c * a < c * b) (hc : c ≤ 0) : b < a := have nhc : 0 ≤ -c, from neg_nonneg_of_nonpos hc, have h2 : -(c * b) < -(c * a), from neg_lt_neg h, have h3 : (-c) * b < (-c) * a, from calc (-c) * b = - (c * b) : by rewrite neg_mul_eq_neg_mul ... < -(c * a) : h2 ... = (-c) * a : by rewrite neg_mul_eq_neg_mul, lt_of_mul_lt_mul_left h3 nhc lemma neg_one_lt_zero : -1 < (0:α) := neg_lt_zero.2 zero_lt_one lemma le_of_mul_le_of_one_le {a b c : α} (h : a * c ≤ b) (hb : 0 ≤ b) (hc : 1 ≤ c) : a ≤ b := by haveI := @linear_order.decidable_le α _; exact have h' : a * c ≤ b * c, from calc a * c ≤ b : h ... = b * 1 : by rewrite mul_one ... ≤ b * c : decidable.mul_le_mul_of_nonneg_left hc hb, le_of_mul_le_mul_right h' (zero_lt_one.trans_le hc) lemma nonneg_le_nonneg_of_sq_le_sq {a b : α} (hb : 0 ≤ b) (h : a * a ≤ b * b) : a ≤ b := by haveI := @linear_order.decidable_le α _; exact le_of_not_gt (λhab, (decidable.mul_self_lt_mul_self hb hab).not_le h) lemma mul_self_le_mul_self_iff {a b : α} (h1 : 0 ≤ a) (h2 : 0 ≤ b) : a ≤ b ↔ a * a ≤ b * b := by haveI := @linear_order.decidable_le α _; exact ⟨decidable.mul_self_le_mul_self h1, nonneg_le_nonneg_of_sq_le_sq h2⟩ lemma mul_self_lt_mul_self_iff {a b : α} (h1 : 0 ≤ a) (h2 : 0 ≤ b) : a < b ↔ a * a < b * b := by haveI := @linear_order.decidable_le α _; exact ((@decidable.strict_mono_incr_on_mul_self α _ _).lt_iff_lt h1 h2).symm lemma mul_self_inj {a b : α} (h1 : 0 ≤ a) (h2 : 0 ≤ b) : a * a = b * b ↔ a = b := by haveI := @linear_order.decidable_le α _; exact (@decidable.strict_mono_incr_on_mul_self α _ _).inj_on.eq_iff h1 h2 @[simp] lemma mul_le_mul_left_of_neg {a b c : α} (h : c < 0) : c * a ≤ c * b ↔ b ≤ a := by haveI := @linear_order.decidable_le α _; exact ⟨le_imp_le_of_lt_imp_lt $ λ h', mul_lt_mul_of_neg_left h' h, λ h', decidable.mul_le_mul_of_nonpos_left h' h.le⟩ @[simp] lemma mul_le_mul_right_of_neg {a b c : α} (h : c < 0) : a * c ≤ b * c ↔ b ≤ a := by haveI := @linear_order.decidable_le α _; exact ⟨le_imp_le_of_lt_imp_lt $ λ h', mul_lt_mul_of_neg_right h' h, λ h', decidable.mul_le_mul_of_nonpos_right h' h.le⟩ @[simp] lemma mul_lt_mul_left_of_neg {a b c : α} (h : c < 0) : c * a < c * b ↔ b < a := lt_iff_lt_of_le_iff_le (mul_le_mul_left_of_neg h) @[simp] lemma mul_lt_mul_right_of_neg {a b c : α} (h : c < 0) : a * c < b * c ↔ b < a := lt_iff_lt_of_le_iff_le (mul_le_mul_right_of_neg h) lemma sub_one_lt (a : α) : a - 1 < a := sub_lt_iff_lt_add.2 (lt_add_one a) lemma mul_self_pos {a : α} (ha : a ≠ 0) : 0 < a * a := by rcases lt_trichotomy a 0 with h|h|h; [exact mul_pos_of_neg_of_neg h h, exact (ha h).elim, exact mul_pos h h] lemma mul_self_le_mul_self_of_le_of_neg_le {x y : α} (h₁ : x ≤ y) (h₂ : -x ≤ y) : x * x ≤ y * y := begin haveI := @linear_order.decidable_le α _, rw [← abs_mul_abs_self x], exact decidable.mul_self_le_mul_self (abs_nonneg x) (abs_le.2 ⟨neg_le.2 h₂, h₁⟩) end lemma nonneg_of_mul_nonpos_left {a b : α} (h : a * b ≤ 0) (hb : b < 0) : 0 ≤ a := le_of_not_gt (λ ha, absurd h (mul_pos_of_neg_of_neg ha hb).not_le) lemma nonneg_of_mul_nonpos_right {a b : α} (h : a * b ≤ 0) (ha : a < 0) : 0 ≤ b := le_of_not_gt (λ hb, absurd h (mul_pos_of_neg_of_neg ha hb).not_le) lemma pos_of_mul_neg_left {a b : α} (h : a * b < 0) (hb : b ≤ 0) : 0 < a := by haveI := @linear_order.decidable_le α _; exact lt_of_not_ge (λ ha, absurd h (decidable.mul_nonneg_of_nonpos_of_nonpos ha hb).not_lt) lemma pos_of_mul_neg_right {a b : α} (h : a * b < 0) (ha : a ≤ 0) : 0 < b := by haveI := @linear_order.decidable_le α _; exact lt_of_not_ge (λ hb, absurd h (decidable.mul_nonneg_of_nonpos_of_nonpos ha hb).not_lt) /-- The sum of two squares is zero iff both elements are zero. -/ lemma mul_self_add_mul_self_eq_zero {x y : α} : x * x + y * y = 0 ↔ x = 0 ∧ y = 0 := by rw [add_eq_zero_iff', mul_self_eq_zero, mul_self_eq_zero]; apply mul_self_nonneg lemma eq_zero_of_mul_self_add_mul_self_eq_zero (h : a * a + b * b = 0) : a = 0 := (mul_self_add_mul_self_eq_zero.mp h).left lemma abs_eq_iff_mul_self_eq : abs a = abs b ↔ a * a = b * b := begin rw [← abs_mul_abs_self, ← abs_mul_abs_self b], exact (mul_self_inj (abs_nonneg a) (abs_nonneg b)).symm, end lemma abs_lt_iff_mul_self_lt : abs a < abs b ↔ a * a < b * b := begin rw [← abs_mul_abs_self, ← abs_mul_abs_self b], exact mul_self_lt_mul_self_iff (abs_nonneg a) (abs_nonneg b) end lemma abs_le_iff_mul_self_le : abs a ≤ abs b ↔ a * a ≤ b * b := begin rw [← abs_mul_abs_self, ← abs_mul_abs_self b], exact mul_self_le_mul_self_iff (abs_nonneg a) (abs_nonneg b) end lemma abs_le_one_iff_mul_self_le_one : abs a ≤ 1 ↔ a * a ≤ 1 := by simpa only [abs_one, one_mul] using @abs_le_iff_mul_self_le α _ a 1 /-- Pullback a `linear_ordered_ring` under an injective map. -/ def function.injective.linear_ordered_ring {β : Type*} [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] [nontrivial β] (f : β → α) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) : linear_ordered_ring β := { ..linear_order.lift f hf, ..‹nontrivial β›, ..hf.ordered_ring f zero one add mul neg sub } end linear_ordered_ring /-- A `linear_ordered_comm_ring α` is a commutative ring `α` with a linear order such that multiplication with a positive number and addition are monotone. -/ @[protect_proj] class linear_ordered_comm_ring (α : Type u) extends linear_ordered_ring α, comm_monoid α @[priority 100] -- see Note [lower instance priority] instance linear_ordered_comm_ring.to_ordered_comm_ring [d : linear_ordered_comm_ring α] : ordered_comm_ring α := -- One might hope that `{ ..linear_ordered_ring.to_linear_ordered_semiring, ..d }` -- achieved the same result here. -- Unfortunately with that definition we see mismatched instances in `algebra.star.chsh`. let s : linear_ordered_semiring α := @linear_ordered_ring.to_linear_ordered_semiring α _ in { zero_mul := @linear_ordered_semiring.zero_mul α s, mul_zero := @linear_ordered_semiring.mul_zero α s, add_left_cancel := @linear_ordered_semiring.add_left_cancel α s, le_of_add_le_add_left := @linear_ordered_semiring.le_of_add_le_add_left α s, mul_lt_mul_of_pos_left := @linear_ordered_semiring.mul_lt_mul_of_pos_left α s, mul_lt_mul_of_pos_right := @linear_ordered_semiring.mul_lt_mul_of_pos_right α s, ..d } @[priority 100] -- see Note [lower instance priority] instance linear_ordered_comm_ring.to_integral_domain [s : linear_ordered_comm_ring α] : integral_domain α := { ..linear_ordered_ring.to_domain, ..s } @[priority 100] -- see Note [lower instance priority] instance linear_ordered_comm_ring.to_linear_ordered_semiring [d : linear_ordered_comm_ring α] : linear_ordered_semiring α := -- One might hope that `{ ..linear_ordered_ring.to_linear_ordered_semiring, ..d }` -- achieved the same result here. -- Unfortunately with that definition we see mismatched `preorder ℝ` instances in -- `topology.metric_space.basic`. let s : linear_ordered_semiring α := @linear_ordered_ring.to_linear_ordered_semiring α _ in { zero_mul := @linear_ordered_semiring.zero_mul α s, mul_zero := @linear_ordered_semiring.mul_zero α s, add_left_cancel := @linear_ordered_semiring.add_left_cancel α s, le_of_add_le_add_left := @linear_ordered_semiring.le_of_add_le_add_left α s, mul_lt_mul_of_pos_left := @linear_ordered_semiring.mul_lt_mul_of_pos_left α s, mul_lt_mul_of_pos_right := @linear_ordered_semiring.mul_lt_mul_of_pos_right α s, ..d } section linear_ordered_comm_ring variables [linear_ordered_comm_ring α] {a b c d : α} lemma max_mul_mul_le_max_mul_max (b c : α) (ha : 0 ≤ a) (hd: 0 ≤ d) : max (a * b) (d * c) ≤ max a c * max d b := by haveI := @linear_order.decidable_le α _; exact have ba : b * a ≤ max d b * max c a, from decidable.mul_le_mul (le_max_right d b) (le_max_right c a) ha (le_trans hd (le_max_left d b)), have cd : c * d ≤ max a c * max b d, from decidable.mul_le_mul (le_max_right a c) (le_max_right b d) hd (le_trans ha (le_max_left a c)), max_le (by simpa [mul_comm, max_comm] using ba) (by simpa [mul_comm, max_comm] using cd) lemma abs_sub_sq (a b : α) : abs (a - b) * abs (a - b) = a * a + b * b - (1 + 1) * a * b := begin rw abs_mul_abs_self, simp only [mul_add, add_comm, add_left_comm, mul_comm, sub_eq_add_neg, mul_one, mul_neg_eq_neg_mul_symm, neg_add_rev, neg_neg], end @[simp] lemma abs_dvd (a b : α) : abs a ∣ b ↔ a ∣ b := by { cases abs_choice a with h h; simp only [h, neg_dvd] } lemma abs_dvd_self (a : α) : abs a ∣ a := (abs_dvd a a).mpr (dvd_refl a) @[simp] lemma dvd_abs (a b : α) : a ∣ abs b ↔ a ∣ b := by { cases abs_choice b with h h; simp only [h, dvd_neg] } lemma self_dvd_abs (a : α) : a ∣ abs a := (dvd_abs a a).mpr (dvd_refl a) lemma abs_dvd_abs (a b : α) : abs a ∣ abs b ↔ a ∣ b := (abs_dvd _ _).trans (dvd_abs _ _) lemma even_abs {a : α} : even (abs a) ↔ even a := dvd_abs _ _ /-- Pullback a `linear_ordered_comm_ring` under an injective map. -/ def function.injective.linear_ordered_comm_ring {β : Type*} [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] [nontrivial β] (f : β → α) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) : linear_ordered_comm_ring β := { ..linear_order.lift f hf, ..‹nontrivial β›, ..hf.ordered_comm_ring f zero one add mul neg sub } end linear_ordered_comm_ring /-- Extend `nonneg_add_comm_group` to support ordered rings specified by their nonnegative elements -/ class nonneg_ring (α : Type*) extends ring α, nonneg_add_comm_group α := (one_nonneg : nonneg 1) (mul_nonneg : ∀ {a b}, nonneg a → nonneg b → nonneg (a * b)) (mul_pos : ∀ {a b}, pos a → pos b → pos (a * b)) /-- Extend `nonneg_add_comm_group` to support linearly ordered rings specified by their nonnegative elements -/ class linear_nonneg_ring (α : Type*) extends domain α, nonneg_add_comm_group α := (one_pos : pos 1) (mul_nonneg : ∀ {a b}, nonneg a → nonneg b → nonneg (a * b)) (nonneg_total : ∀ a, nonneg a ∨ nonneg (-a)) [dec_nonneg : decidable_pred nonneg] namespace nonneg_ring open nonneg_add_comm_group variable [nonneg_ring α] /-- `to_linear_nonneg_ring` shows that a `nonneg_ring` with a total order is a `domain`, hence a `linear_nonneg_ring`. -/ def to_linear_nonneg_ring [nontrivial α] [decidable_pred (@nonneg α _)] (nonneg_total : ∀ a : α, nonneg a ∨ nonneg (-a)) : linear_nonneg_ring α := { one_pos := (pos_iff 1).mpr ⟨one_nonneg, λ h, zero_ne_one (nonneg_antisymm one_nonneg h).symm⟩, nonneg_total := nonneg_total, eq_zero_or_eq_zero_of_mul_eq_zero := suffices ∀ {a} b : α, nonneg a → a * b = 0 → a = 0 ∨ b = 0, from λ a b, (nonneg_total a).elim (this b) (λ na, by simpa using this b na), suffices ∀ {a b : α}, nonneg a → nonneg b → a * b = 0 → a = 0 ∨ b = 0, from λ a b na, (nonneg_total b).elim (this na) (λ nb, by simpa using this na nb), λ a b na nb z, decidable.by_cases (λ nna : nonneg (-a), or.inl (nonneg_antisymm na nna)) (λ pa, decidable.by_cases (λ nnb : nonneg (-b), or.inr (nonneg_antisymm nb nnb)) (λ pb, absurd z $ ne_of_gt $ pos_def.1 $ mul_pos ((pos_iff _).2 ⟨na, pa⟩) ((pos_iff _).2 ⟨nb, pb⟩))), ..‹nontrivial α›, ..‹nonneg_ring α› } end nonneg_ring namespace linear_nonneg_ring open nonneg_add_comm_group variable [linear_nonneg_ring α] @[priority 100] -- see Note [lower instance priority] instance to_nonneg_ring : nonneg_ring α := { one_nonneg := ((pos_iff _).mp one_pos).1, mul_pos := λ a b pa pb, let ⟨a1, a2⟩ := (pos_iff a).1 pa, ⟨b1, b2⟩ := (pos_iff b).1 pb in have ab : nonneg (a * b), from mul_nonneg a1 b1, (pos_iff _).2 ⟨ab, λ hn, have a * b = 0, from nonneg_antisymm ab hn, (eq_zero_or_eq_zero_of_mul_eq_zero _ _ this).elim (ne_of_gt (pos_def.1 pa)) (ne_of_gt (pos_def.1 pb))⟩, ..‹linear_nonneg_ring α› } /-- Construct `linear_order` from `linear_nonneg_ring`. This is not an instance because we don't use it in `mathlib`. -/ local attribute [instance] def to_linear_order [decidable_pred (nonneg : α → Prop)] : linear_order α := { le_total := nonneg_total_iff.1 nonneg_total, decidable_le := by apply_instance, decidable_lt := by apply_instance, ..‹linear_nonneg_ring α›, ..(infer_instance : ordered_add_comm_group α) } /-- Construct `linear_ordered_ring` from `linear_nonneg_ring`. This is not an instance because we don't use it in `mathlib`. -/ local attribute [instance] def to_linear_ordered_ring [decidable_pred (nonneg : α → Prop)] : linear_ordered_ring α := { mul_pos := by simp [pos_def.symm]; exact @nonneg_ring.mul_pos _ _, zero_le_one := le_of_lt $ lt_of_not_ge $ λ (h : nonneg (0 - 1)), begin rw [zero_sub] at h, have := mul_nonneg h h, simp at this, exact zero_ne_one (nonneg_antisymm this h).symm end, ..‹linear_nonneg_ring α›, ..(infer_instance : ordered_add_comm_group α), ..(infer_instance : linear_order α) } /-- Convert a `linear_nonneg_ring` with a commutative multiplication and decidable non-negativity into a `linear_ordered_comm_ring` -/ def to_linear_ordered_comm_ring [decidable_pred (@nonneg α _)] [comm : @is_commutative α (*)] : linear_ordered_comm_ring α := { mul_comm := is_commutative.comm, ..@linear_nonneg_ring.to_linear_ordered_ring _ _ _ } end linear_nonneg_ring /-- A canonically ordered commutative semiring is an ordered, commutative semiring in which `a ≤ b` iff there exists `c` with `b = a + c`. This is satisfied by the natural numbers, for example, but not the integers or other ordered groups. -/ @[protect_proj] class canonically_ordered_comm_semiring (α : Type*) extends canonically_ordered_add_monoid α, comm_semiring α := (eq_zero_or_eq_zero_of_mul_eq_zero : ∀ a b : α, a * b = 0 → a = 0 ∨ b = 0) namespace canonically_ordered_semiring variables [canonically_ordered_comm_semiring α] {a b : α} open canonically_ordered_add_monoid (le_iff_exists_add) @[priority 100] -- see Note [lower instance priority] instance canonically_ordered_comm_semiring.to_no_zero_divisors : no_zero_divisors α := ⟨canonically_ordered_comm_semiring.eq_zero_or_eq_zero_of_mul_eq_zero⟩ lemma mul_le_mul {a b c d : α} (hab : a ≤ b) (hcd : c ≤ d) : a * c ≤ b * d := begin rcases (le_iff_exists_add _ _).1 hab with ⟨b, rfl⟩, rcases (le_iff_exists_add _ _).1 hcd with ⟨d, rfl⟩, suffices : a * c ≤ a * c + (a * d + b * c + b * d), by simpa [mul_add, add_mul, add_assoc], exact (le_iff_exists_add _ _).2 ⟨_, rfl⟩ end lemma mul_le_mul_left' {b c : α} (h : b ≤ c) (a : α) : a * b ≤ a * c := mul_le_mul le_rfl h lemma mul_le_mul_right' {b c : α} (h : b ≤ c) (a : α) : b * a ≤ c * a := mul_le_mul h le_rfl /-- A version of `zero_lt_one : 0 < 1` for a `canonically_ordered_comm_semiring`. -/ lemma zero_lt_one [nontrivial α] : (0:α) < 1 := (zero_le 1).lt_of_ne zero_ne_one lemma mul_pos : 0 < a * b ↔ (0 < a) ∧ (0 < b) := by simp only [pos_iff_ne_zero, ne.def, mul_eq_zero, not_or_distrib] end canonically_ordered_semiring namespace with_top instance [nonempty α] : nontrivial (with_top α) := option.nontrivial variable [decidable_eq α] section has_mul variables [has_zero α] [has_mul α] instance : mul_zero_class (with_top α) := { zero := 0, mul := λm n, if m = 0 ∨ n = 0 then 0 else m.bind (λa, n.bind $ λb, ↑(a * b)), zero_mul := assume a, if_pos $ or.inl rfl, mul_zero := assume a, if_pos $ or.inr rfl } lemma mul_def {a b : with_top α} : a * b = if a = 0 ∨ b = 0 then 0 else a.bind (λa, b.bind $ λb, ↑(a * b)) := rfl @[simp] lemma mul_top {a : with_top α} (h : a ≠ 0) : a * ⊤ = ⊤ := by cases a; simp [mul_def, h]; refl @[simp] lemma top_mul {a : with_top α} (h : a ≠ 0) : ⊤ * a = ⊤ := by cases a; simp [mul_def, h]; refl @[simp] lemma top_mul_top : (⊤ * ⊤ : with_top α) = ⊤ := top_mul top_ne_zero end has_mul section mul_zero_class variables [mul_zero_class α] @[norm_cast] lemma coe_mul {a b : α} : (↑(a * b) : with_top α) = a * b := decidable.by_cases (assume : a = 0, by simp [this]) $ assume ha, decidable.by_cases (assume : b = 0, by simp [this]) $ assume hb, by { simp [*, mul_def], refl } lemma mul_coe {b : α} (hb : b ≠ 0) : ∀{a : with_top α}, a * b = a.bind (λa:α, ↑(a * b)) | none := show (if (⊤:with_top α) = 0 ∨ (b:with_top α) = 0 then 0 else ⊤ : with_top α) = ⊤, by simp [hb] | (some a) := show ↑a * ↑b = ↑(a * b), from coe_mul.symm @[simp] lemma mul_eq_top_iff {a b : with_top α} : a * b = ⊤ ↔ (a ≠ 0 ∧ b = ⊤) ∨ (a = ⊤ ∧ b ≠ 0) := begin cases a; cases b; simp only [none_eq_top, some_eq_coe], { simp [← coe_mul] }, { suffices : ⊤ * (b : with_top α) = ⊤ ↔ b ≠ 0, by simpa, by_cases hb : b = 0; simp [hb] }, { suffices : (a : with_top α) * ⊤ = ⊤ ↔ a ≠ 0, by simpa, by_cases ha : a = 0; simp [ha] }, { simp [← coe_mul] } end end mul_zero_class section no_zero_divisors variables [mul_zero_class α] [no_zero_divisors α] instance : no_zero_divisors (with_top α) := ⟨λ a b, by cases a; cases b; dsimp [mul_def]; split_ifs; simp [*, none_eq_top, some_eq_coe, mul_eq_zero] at *⟩ end no_zero_divisors variables [canonically_ordered_comm_semiring α] private lemma comm (a b : with_top α) : a * b = b * a := begin by_cases ha : a = 0, { simp [ha] }, by_cases hb : b = 0, { simp [hb] }, simp [ha, hb, mul_def, option.bind_comm a b, mul_comm] end private lemma distrib' (a b c : with_top α) : (a + b) * c = a * c + b * c := begin cases c, { show (a + b) * ⊤ = a * ⊤ + b * ⊤, by_cases ha : a = 0; simp [ha] }, { show (a + b) * c = a * c + b * c, by_cases hc : c = 0, { simp [hc] }, simp [mul_coe hc], cases a; cases b, repeat { refl <|> exact congr_arg some (add_mul _ _ _) } } end private lemma assoc (a b c : with_top α) : (a * b) * c = a * (b * c) := begin cases a, { by_cases hb : b = 0; by_cases hc : c = 0; simp [*, none_eq_top] }, cases b, { by_cases ha : a = 0; by_cases hc : c = 0; simp [*, none_eq_top, some_eq_coe] }, cases c, { by_cases ha : a = 0; by_cases hb : b = 0; simp [*, none_eq_top, some_eq_coe] }, simp [some_eq_coe, coe_mul.symm, mul_assoc] end -- `nontrivial α` is needed here as otherwise -- we have `1 * ⊤ = ⊤` but also `= 0 * ⊤ = 0`. private lemma one_mul' [nontrivial α] : ∀a : with_top α, 1 * a = a | none := show ((1:α) : with_top α) * ⊤ = ⊤, by simp [-with_top.coe_one] | (some a) := show ((1:α) : with_top α) * a = a, by simp [coe_mul.symm, -with_top.coe_one] instance [nontrivial α] : canonically_ordered_comm_semiring (with_top α) := { one := (1 : α), right_distrib := distrib', left_distrib := assume a b c, by rw [comm, distrib', comm b, comm c]; refl, mul_assoc := assoc, mul_comm := comm, one_mul := one_mul', mul_one := assume a, by rw [comm, one_mul'], .. with_top.add_comm_monoid, .. with_top.mul_zero_class, .. with_top.canonically_ordered_add_monoid, .. with_top.no_zero_divisors, .. with_top.nontrivial } lemma mul_lt_top [nontrivial α] {a b : with_top α} (ha : a < ⊤) (hb : b < ⊤) : a * b < ⊤ := begin lift a to α using ne_top_of_lt ha, lift b to α using ne_top_of_lt hb, simp only [← coe_mul, coe_lt_top] end end with_top
ef011cec675741f1f6fceca4ac325712a9d5f6ed
2c096fdfecf64e46ea7bc6ce5521f142b5926864
/src/Lean/Server/Watchdog.lean
871ccbfa8b66ba1b5a9fa9f01632369e018b0cb3
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
Kha/lean4
1005785d2c8797ae266a303968848e5f6ce2fe87
b99e11346948023cd6c29d248cd8f3e3fb3474cf
refs/heads/master
1,693,355,498,027
1,669,080,461,000
1,669,113,138,000
184,748,176
0
0
Apache-2.0
1,665,995,520,000
1,556,884,930,000
Lean
UTF-8
Lean
false
false
34,409
lean
/- Copyright (c) 2020 Marc Huisinga. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Marc Huisinga, Wojciech Nawrocki -/ import Init.System.IO import Init.Data.ByteArray import Lean.Data.RBMap import Lean.Elab.Import import Lean.Util.Paths import Lean.Data.FuzzyMatching import Lean.Data.Json import Lean.Data.Lsp import Lean.Server.Utils import Lean.Server.Requests import Lean.Server.References /-! For general server architecture, see `README.md`. This module implements the watchdog process. ## Watchdog state Most LSP clients only send us file diffs, so to facilitate sending entire file contents to freshly restarted workers, the watchdog needs to maintain the current state of each file. It can also use this state to detect changes to the header and thus restart the corresponding worker, freeing its imports. TODO(WN): We may eventually want to keep track of approximately (since this isn't knowable exactly) where in the file a worker crashed. Then on restart, we tell said worker to only parse up to that point and query the user about how to proceed (continue OR allow the user to fix the bug and then continue OR ..). Without this, if the crash is deterministic, users may be confused about why the server seemingly stopped working for a single file. ## Watchdog <-> worker communication The watchdog process and its file worker processes communicate via LSP. If the necessity arises, we might add non-standard commands similarly based on JSON-RPC. Most requests and notifications are forwarded to the corresponding file worker process, with the exception of these notifications: - textDocument/didOpen: Launch the file worker, create the associated watchdog state and launch a task to asynchronously receive LSP packets from the worker (e.g. request responses). - textDocument/didChange: Update the local file state. If the header was mutated, signal a shutdown to the file worker by closing the I/O channels. Then restart the file worker. Otherwise, forward the `didChange` notification. - textDocument/didClose: Signal a shutdown to the file worker and remove the associated watchdog state. Moreover, we don't implement the full protocol at this level: - Upon starting, the `initialize` request is forwarded to the worker, but it must not respond with its server capabilities. Consequently, the watchdog will not send an `initialized` notification to the worker. - After `initialize`, the watchdog sends the corresponding `didOpen` notification with the full current state of the file. No additional `didOpen` notifications will be forwarded to the worker process. - `$/cancelRequest` notifications are forwarded to all file workers. - File workers are always terminated with an `exit` notification, without previously receiving a `shutdown` request. Similarly, they never receive a `didClose` notification. ## Watchdog <-> client communication The watchdog itself should implement the LSP standard as closely as possible. However we reserve the right to add non-standard extensions in case they're needed, for example to communicate tactic state. -/ namespace Lean.Server.Watchdog open IO open Lsp open JsonRpc open System.Uri section Utils structure OpenDocument where meta : DocumentMeta headerAst : Syntax def workerCfg : Process.StdioConfig := { stdin := Process.Stdio.piped stdout := Process.Stdio.piped -- We pass workers' stderr through to the editor. stderr := Process.Stdio.inherit } /-- Events that worker-specific tasks signal to the main thread. -/ inductive WorkerEvent where /-- A synthetic event signalling that the grouped edits should be processed. -/ | processGroupedEdits | terminated | crashed (e : IO.Error) | ioError (e : IO.Error) inductive WorkerState where /-- The watchdog can detect a crashed file worker in two places: When trying to send a message to the file worker and when reading a request reply. In the latter case, the forwarding task terminates and delegates a `crashed` event to the main task. Then, in both cases, the file worker has its state set to `crashed` and requests that are in-flight are errored. Upon receiving the next packet for that file worker, the file worker is restarted and the packet is forwarded to it. If the crash was detected while writing a packet, we queue that packet until the next packet for the file worker arrives. -/ | crashed (queuedMsgs : Array JsonRpc.Message) | running abbrev PendingRequestMap := RBMap RequestID JsonRpc.Message compare private def parseHeaderAst (input : String) : IO Syntax := do let inputCtx := Parser.mkInputContext input "<input>" let (stx, _, _) ← Parser.parseHeader inputCtx return stx end Utils section FileWorker /-- A group of edits which will be processed at a future instant. -/ structure GroupedEdits where /-- When to process the edits. -/ applyTime : Nat params : DidChangeTextDocumentParams /-- Signals when `applyTime` has been reached. -/ signalTask : Task WorkerEvent /-- We should not reorder messages when delaying edits, so we queue other messages since the last request here. -/ queuedMsgs : Array JsonRpc.Message structure FileWorker where doc : OpenDocument proc : Process.Child workerCfg commTask : Task WorkerEvent state : WorkerState -- This should not be mutated outside of namespace FileWorker, as it is used as shared mutable state /-- The pending requests map contains all requests that have been received from the LSP client, but were not answered yet. This includes the queued messages in the grouped edits. -/ pendingRequestsRef : IO.Ref PendingRequestMap groupedEditsRef : IO.Ref (Option GroupedEdits) namespace FileWorker def stdin (fw : FileWorker) : FS.Stream := FS.Stream.ofHandle fw.proc.stdin def stdout (fw : FileWorker) : FS.Stream := FS.Stream.ofHandle fw.proc.stdout def erasePendingRequest (fw : FileWorker) (id : RequestID) : IO Unit := fw.pendingRequestsRef.modify fun pendingRequests => pendingRequests.erase id def errorPendingRequests (fw : FileWorker) (hError : FS.Stream) (code : ErrorCode) (msg : String) : IO Unit := do let pendingRequests ← fw.pendingRequestsRef.modifyGet (fun pendingRequests => (pendingRequests, RBMap.empty)) for ⟨id, _⟩ in pendingRequests do hError.writeLspResponseError { id := id, code := code, message := msg } partial def runEditsSignalTask (fw : FileWorker) : IO (Task WorkerEvent) := do -- check `applyTime` in a loop since it might have been postponed by a subsequent edit notification let rec loopAction : IO WorkerEvent := do let now ← monoMsNow let some ge ← fw.groupedEditsRef.get | throwServerError "Internal error: empty grouped edits reference in signal task" if ge.applyTime ≤ now then return WorkerEvent.processGroupedEdits else IO.sleep <| UInt32.ofNat <| ge.applyTime - now loopAction let t ← IO.asTask loopAction return t.map fun | Except.ok ev => ev | Except.error e => WorkerEvent.ioError e end FileWorker end FileWorker section ServerM abbrev FileWorkerMap := RBMap DocumentUri FileWorker compare structure ServerContext where hIn : FS.Stream hOut : FS.Stream hLog : FS.Stream /-- Command line arguments. -/ args : List String fileWorkersRef : IO.Ref FileWorkerMap /-- We store these to pass them to workers. -/ initParams : InitializeParams editDelay : Nat workerPath : System.FilePath srcSearchPath : System.SearchPath references : IO.Ref References abbrev ServerM := ReaderT ServerContext IO def updateFileWorkers (val : FileWorker) : ServerM Unit := do (←read).fileWorkersRef.modify (fun fileWorkers => fileWorkers.insert val.doc.meta.uri val) def findFileWorker? (uri : DocumentUri) : ServerM (Option FileWorker) := return (← (←read).fileWorkersRef.get).find? uri def findFileWorker! (uri : DocumentUri) : ServerM FileWorker := do let some fw ← findFileWorker? uri | throwServerError s!"cannot find open document '{uri}'" return fw def eraseFileWorker (uri : DocumentUri) : ServerM Unit := do let s ← read s.fileWorkersRef.modify (fun fileWorkers => fileWorkers.erase uri) if let some path := fileUriToPath? uri then if let some module ← searchModuleNameOfFileName path s.srcSearchPath then s.references.modify fun refs => refs.removeWorkerRefs module def log (msg : String) : ServerM Unit := do let st ← read st.hLog.putStrLn msg st.hLog.flush def handleIleanInfoUpdate (fw : FileWorker) (params : LeanIleanInfoParams) : ServerM Unit := do let s ← read if let some path := fileUriToPath? fw.doc.meta.uri then if let some module ← searchModuleNameOfFileName path s.srcSearchPath then s.references.modify fun refs => refs.updateWorkerRefs module params.version params.references def handleIleanInfoFinal (fw : FileWorker) (params : LeanIleanInfoParams) : ServerM Unit := do let s ← read if let some path := fileUriToPath? fw.doc.meta.uri then if let some module ← searchModuleNameOfFileName path s.srcSearchPath then s.references.modify fun refs => refs.finalizeWorkerRefs module params.version params.references /-- Creates a Task which forwards a worker's messages into the output stream until an event which must be handled in the main watchdog thread (e.g. an I/O error) happens. -/ private partial def forwardMessages (fw : FileWorker) : ServerM (Task WorkerEvent) := do let o := (←read).hOut let rec loop : ServerM WorkerEvent := do try let msg ← fw.stdout.readLspMessage -- Re. `o.writeLspMessage msg`: -- Writes to Lean I/O channels are atomic, so these won't trample on each other. match msg with | Message.response id _ => do fw.erasePendingRequest id o.writeLspMessage msg | Message.responseError id _ _ _ => do fw.erasePendingRequest id o.writeLspMessage msg | Message.notification "$/lean/ileanInfoUpdate" params => if let some params := params then if let Except.ok params := FromJson.fromJson? <| ToJson.toJson params then handleIleanInfoUpdate fw params | Message.notification "$/lean/ileanInfoFinal" params => if let some params := params then if let Except.ok params := FromJson.fromJson? <| ToJson.toJson params then handleIleanInfoFinal fw params | _ => o.writeLspMessage msg catch err => -- If writeLspMessage from above errors we will block here, but the main task will -- quit eventually anyways if that happens let exitCode ← fw.proc.wait if exitCode = 0 then -- Worker was terminated fw.errorPendingRequests o ErrorCode.contentModified (s!"The file worker for {fw.doc.meta.uri} has been terminated. Either the header has changed," ++ " or the file was closed, or the server is shutting down.") -- one last message to clear the diagnostics for this file so that stale errors -- do not remain in the editor forever. publishDiagnostics fw.doc.meta #[] o return WorkerEvent.terminated else -- Worker crashed fw.errorPendingRequests o (if exitCode = 1 then ErrorCode.workerExited else ErrorCode.workerCrashed) s!"Server process for {fw.doc.meta.uri} crashed, {if exitCode = 1 then "see stderr for exception" else "likely due to a stack overflow or a bug"}." publishProgressAtPos fw.doc.meta 0 o (kind := LeanFileProgressKind.fatalError) return WorkerEvent.crashed err loop let task ← IO.asTask (loop $ ←read) Task.Priority.dedicated return task.map fun | Except.ok ev => ev | Except.error e => WorkerEvent.ioError e def startFileWorker (m : DocumentMeta) : ServerM Unit := do publishProgressAtPos m 0 (← read).hOut let st ← read let headerAst ← parseHeaderAst m.text.source let workerProc ← Process.spawn { toStdioConfig := workerCfg cmd := st.workerPath.toString args := #["--worker"] ++ st.args.toArray ++ #[m.uri] } let pendingRequestsRef ← IO.mkRef (RBMap.empty : PendingRequestMap) -- The task will never access itself, so this is fine let fw : FileWorker := { doc := ⟨m, headerAst⟩ proc := workerProc commTask := Task.pure WorkerEvent.terminated state := WorkerState.running pendingRequestsRef := pendingRequestsRef groupedEditsRef := ← IO.mkRef none } let commTask ← forwardMessages fw let fw : FileWorker := { fw with commTask := commTask } fw.stdin.writeLspRequest ⟨0, "initialize", st.initParams⟩ fw.stdin.writeLspNotification { method := "textDocument/didOpen" param := { textDocument := { uri := m.uri languageId := "lean" version := m.version text := m.text.source } : DidOpenTextDocumentParams } } updateFileWorkers fw def terminateFileWorker (uri : DocumentUri) : ServerM Unit := do let fw ← findFileWorker! uri try fw.stdin.writeLspMessage (Message.notification "exit" none) catch _ => /- The file worker must have crashed just when we were about to terminate it! That's fine - just forget about it then. (on didClose we won't need the crashed file worker anymore, when the header changed we'll start a new one right after anyways and when we're shutting down the server it's over either way.) -/ return eraseFileWorker uri def handleCrash (uri : DocumentUri) (queuedMsgs : Array JsonRpc.Message) : ServerM Unit := do updateFileWorkers { ←findFileWorker! uri with state := WorkerState.crashed queuedMsgs } /-- Tries to write a message, sets the state of the FileWorker to `crashed` if it does not succeed and restarts the file worker if the `crashed` flag was already set. Just logs an error if there is no FileWorker at this `uri`. Messages that couldn't be sent can be queued up via the queueFailedMessage flag and will be discharged after the FileWorker is restarted. -/ def tryWriteMessage (uri : DocumentUri) (msg : JsonRpc.Message) (queueFailedMessage := true) (restartCrashedWorker := false) : ServerM Unit := do let some fw ← findFileWorker? uri | do (←read).hLog.putStrLn s!"Cannot send message to unknown document '{uri}':\n{(toJson msg).compress}" return let pendingEdit ← fw.groupedEditsRef.modifyGet fun | some ge => (true, some { ge with queuedMsgs := ge.queuedMsgs.push msg }) | none => (false, none) if pendingEdit then return match fw.state with | WorkerState.crashed queuedMsgs => let mut queuedMsgs := queuedMsgs if queueFailedMessage then queuedMsgs := queuedMsgs.push msg if !restartCrashedWorker then return -- restart the crashed FileWorker eraseFileWorker uri startFileWorker fw.doc.meta let newFw ← findFileWorker! uri let mut crashedMsgs := #[] -- try to discharge all queued msgs, tracking the ones that we can't discharge for msg in queuedMsgs do try newFw.stdin.writeLspMessage msg catch _ => crashedMsgs := crashedMsgs.push msg if ¬ crashedMsgs.isEmpty then handleCrash uri crashedMsgs | WorkerState.running => let initialQueuedMsgs := if queueFailedMessage then #[msg] else #[] try fw.stdin.writeLspMessage msg catch _ => handleCrash uri initialQueuedMsgs end ServerM section RequestHandling open FuzzyMatching def findDefinitions (p : TextDocumentPositionParams) : ServerM <| Array Location := do let mut definitions := #[] if let some path := fileUriToPath? p.textDocument.uri then let srcSearchPath := (← read).srcSearchPath if let some module ← searchModuleNameOfFileName path srcSearchPath then let references ← (← read).references.get for ident in references.findAt module p.position do if let some definition ← references.definitionOf? ident srcSearchPath then definitions := definitions.push definition return definitions def handleReference (p : ReferenceParams) : ServerM (Array Location) := do let mut result := #[] if let some path := fileUriToPath? p.textDocument.uri then let srcSearchPath := (← read).srcSearchPath if let some module ← searchModuleNameOfFileName path srcSearchPath then let references ← (← read).references.get for ident in references.findAt module p.position do let identRefs ← references.referringTo module ident srcSearchPath p.context.includeDeclaration result := result.append identRefs return result def handleWorkspaceSymbol (p : WorkspaceSymbolParams) : ServerM (Array SymbolInformation) := do if p.query.isEmpty then return #[] let references ← (← read).references.get let srcSearchPath := (← read).srcSearchPath let symbols ← references.definitionsMatching srcSearchPath (maxAmount? := none) fun name => let name := privateToUserName? name |>.getD name if let some score := fuzzyMatchScoreWithThreshold? p.query name.toString then some (name.toString, score) else none return symbols |>.qsort (fun ((_, s1), _) ((_, s2), _) => s1 > s2) |>.extract 0 100 -- max amount |>.map fun ((name, _), location) => { name, kind := SymbolKind.constant, location } end RequestHandling section NotificationHandling def handleDidOpen (p : DidOpenTextDocumentParams) : ServerM Unit := let doc := p.textDocument /- NOTE(WN): `toFileMap` marks line beginnings as immediately following "\n", which should be enough to handle both LF and CRLF correctly. This is because LSP always refers to characters by (line, column), so if we get the line number correct it shouldn't matter that there is a CR there. -/ startFileWorker ⟨doc.uri, doc.version, doc.text.toFileMap⟩ def handleEdits (fw : FileWorker) : ServerM Unit := do let some ge ← fw.groupedEditsRef.modifyGet (·, none) | throwServerError "Internal error: empty grouped edits reference" let doc := ge.params.textDocument let changes := ge.params.contentChanges let oldDoc := fw.doc let some newVersion ← pure doc.version? | throwServerError "Expected version number" if newVersion <= oldDoc.meta.version then throwServerError "Got outdated version number" if changes.isEmpty then return let newDocText := foldDocumentChanges changes oldDoc.meta.text let newMeta : DocumentMeta := ⟨doc.uri, newVersion, newDocText⟩ let newHeaderAst ← parseHeaderAst newDocText.source if newHeaderAst != oldDoc.headerAst then terminateFileWorker doc.uri startFileWorker newMeta else let newDoc : OpenDocument := ⟨newMeta, oldDoc.headerAst⟩ updateFileWorkers { fw with doc := newDoc } tryWriteMessage doc.uri (Notification.mk "textDocument/didChange" ge.params) (restartCrashedWorker := true) for msg in ge.queuedMsgs do tryWriteMessage doc.uri msg def handleDidClose (p : DidCloseTextDocumentParams) : ServerM Unit := terminateFileWorker p.textDocument.uri def handleDidChangeWatchedFiles (p : DidChangeWatchedFilesParams) : ServerM Unit := do let references := (← read).references let oleanSearchPath ← Lean.searchPathRef.get let ileans ← oleanSearchPath.findAllWithExt "ilean" for change in p.changes do if let some path := fileUriToPath? change.uri then if let FileChangeType.Deleted := change.type then references.modify (fun r => r.removeIlean path) else if ileans.contains path then let ilean ← Ilean.load path if let FileChangeType.Changed := change.type then references.modify (fun r => r.removeIlean path |>.addIlean path ilean) else references.modify (fun r => r.addIlean path ilean) def handleCancelRequest (p : CancelParams) : ServerM Unit := do let fileWorkers ← (←read).fileWorkersRef.get for ⟨uri, fw⟩ in fileWorkers do -- Cancelled requests still require a response, so they can't be removed -- from the pending requests map. if (← fw.pendingRequestsRef.get).contains p.id then tryWriteMessage uri (Notification.mk "$/cancelRequest" p) (queueFailedMessage := false) def forwardNotification {α : Type} [ToJson α] [FileSource α] (method : String) (params : α) : ServerM Unit := tryWriteMessage (fileSource params) (Notification.mk method params) (queueFailedMessage := true) end NotificationHandling section MessageHandling def parseParams (paramType : Type) [FromJson paramType] (params : Json) : ServerM paramType := match fromJson? params with | Except.ok parsed => pure parsed | Except.error inner => throwServerError s!"Got param with wrong structure: {params.compress}\n{inner}" def forwardRequestToWorker (id : RequestID) (method : String) (params : Json) : ServerM Unit := do let uri: DocumentUri ← -- This request is handled specially. if method == "$/lean/rpc/connect" then let ps ← parseParams Lsp.RpcConnectParams params pure <| fileSource ps else match (← routeLspRequest method params) with | Except.error e => (←read).hOut.writeLspResponseError <| e.toLspResponseError id return | Except.ok uri => pure uri let some fw ← findFileWorker? uri /- Clients may send requests to closed files, which we respond to with an error. For example, VSCode sometimes sends requests just after closing a file, and RPC clients may also do so, e.g. due to remaining timers. -/ | do (←read).hOut.writeLspResponseError { id := id /- Some clients (VSCode) also send requests *before* opening a file. We reply with `contentModified` as that does not display a "request failed" popup. -/ code := ErrorCode.contentModified message := s!"Cannot process request to closed file '{uri}'" } return let r := Request.mk id method params fw.pendingRequestsRef.modify (·.insert id r) tryWriteMessage uri r def handleRequest (id : RequestID) (method : String) (params : Json) : ServerM Unit := do let handle α β [FromJson α] [ToJson β] (handler : α → ServerM β) : ServerM Unit := do let hOut := (← read).hOut try let params ← parseParams α params let result ← handler params hOut.writeLspResponse ⟨id, result⟩ catch -- TODO Do fancier error handling, like in file worker? | e => hOut.writeLspResponseError { id := id code := ErrorCode.internalError message := s!"Failed to process request {id}: {e}" } -- If a definition is in a different, modified file, the ilean data should -- have the correct location while the olean still has outdated info from -- the last compilation. This is easier than catching the client's reply and -- fixing the definition's location afterwards, but it doesn't work for -- go-to-type-definition. if method == "textDocument/definition" || method == "textDocument/declaration" then let params ← parseParams TextDocumentPositionParams params let definitions ← findDefinitions params if !definitions.isEmpty then (← read).hOut.writeLspResponse ⟨id, definitions⟩ return match method with | "textDocument/references" => handle ReferenceParams (Array Location) handleReference | "workspace/symbol" => handle WorkspaceSymbolParams (Array SymbolInformation) handleWorkspaceSymbol | _ => forwardRequestToWorker id method params def handleNotification (method : String) (params : Json) : ServerM Unit := do let handle := (fun α [FromJson α] (handler : α → ServerM Unit) => parseParams α params >>= handler) match method with | "textDocument/didOpen" => handle DidOpenTextDocumentParams handleDidOpen /- NOTE: textDocument/didChange is handled in the main loop. -/ | "textDocument/didClose" => handle DidCloseTextDocumentParams handleDidClose | "workspace/didChangeWatchedFiles" => handle DidChangeWatchedFilesParams handleDidChangeWatchedFiles | "$/cancelRequest" => handle CancelParams handleCancelRequest | "$/lean/rpc/connect" => handle RpcConnectParams (forwardNotification method) | "$/lean/rpc/release" => handle RpcReleaseParams (forwardNotification method) | "$/lean/rpc/keepAlive" => handle RpcKeepAliveParams (forwardNotification method) | _ => if !"$/".isPrefixOf method then -- implementation-dependent notifications can be safely ignored (←read).hLog.putStrLn s!"Got unsupported notification: {method}" end MessageHandling section MainLoop def shutdown : ServerM Unit := do let fileWorkers ← (←read).fileWorkersRef.get for ⟨uri, _⟩ in fileWorkers do terminateFileWorker uri for ⟨_, fw⟩ in fileWorkers do discard <| IO.wait fw.commTask inductive ServerEvent where | workerEvent (fw : FileWorker) (ev : WorkerEvent) | clientMsg (msg : JsonRpc.Message) | clientError (e : IO.Error) def runClientTask : ServerM (Task ServerEvent) := do let st ← read let readMsgAction : IO ServerEvent := do /- Runs asynchronously. -/ let msg ← st.hIn.readLspMessage pure <| ServerEvent.clientMsg msg let clientTask := (← IO.asTask readMsgAction).map fun | Except.ok ev => ev | Except.error e => ServerEvent.clientError e return clientTask partial def mainLoop (clientTask : Task ServerEvent) : ServerM Unit := do let st ← read let workers ← st.fileWorkersRef.get let mut workerTasks := #[] for (_, fw) in workers do if let WorkerState.running := fw.state then workerTasks := workerTasks.push <| fw.commTask.map (ServerEvent.workerEvent fw) if let some ge ← fw.groupedEditsRef.get then workerTasks := workerTasks.push <| ge.signalTask.map (ServerEvent.workerEvent fw) let ev ← IO.waitAny (clientTask :: workerTasks.toList) match ev with | ServerEvent.clientMsg msg => match msg with | Message.request id "shutdown" _ => shutdown st.hOut.writeLspResponse ⟨id, Json.null⟩ | Message.request id method (some params) => handleRequest id method (toJson params) mainLoop (←runClientTask) | Message.response .. => -- TODO: handle client responses mainLoop (←runClientTask) | Message.responseError _ _ e .. => throwServerError s!"Unhandled response error: {e}" | Message.notification "textDocument/didChange" (some params) => let p ← parseParams DidChangeTextDocumentParams (toJson params) let fw ← findFileWorker! p.textDocument.uri let now ← monoMsNow /- We wait `editDelay`ms since last edit before applying the changes. -/ let applyTime := now + st.editDelay let queuedMsgs? ← fw.groupedEditsRef.modifyGet fun | some ge => (some ge.queuedMsgs, some { ge with applyTime := applyTime params.textDocument := p.textDocument params.contentChanges := ge.params.contentChanges ++ p.contentChanges -- drain now-outdated messages and respond with `contentModified` below queuedMsgs := #[] }) | none => (none, some { applyTime := applyTime params := p /- This is overwritten just below. -/ signalTask := Task.pure WorkerEvent.processGroupedEdits queuedMsgs := #[] }) match queuedMsgs? with | some queuedMsgs => for msg in queuedMsgs do match msg with | JsonRpc.Message.request id _ _ => fw.erasePendingRequest id (← read).hOut.writeLspResponseError { id := id code := ErrorCode.contentModified message := "File changed." } | _ => pure () -- notifications do not need to be cancelled | _ => let t ← fw.runEditsSignalTask fw.groupedEditsRef.modify (Option.map fun ge => { ge with signalTask := t } ) mainLoop (←runClientTask) | Message.notification method (some params) => handleNotification method (toJson params) mainLoop (←runClientTask) | _ => throwServerError "Got invalid JSON-RPC message" | ServerEvent.clientError e => throw e | ServerEvent.workerEvent fw ev => match ev with | WorkerEvent.processGroupedEdits => handleEdits fw mainLoop clientTask | WorkerEvent.ioError e => throwServerError s!"IO error while processing events for {fw.doc.meta.uri}: {e}" | WorkerEvent.crashed _ => handleCrash fw.doc.meta.uri #[] mainLoop clientTask | WorkerEvent.terminated => throwServerError "Internal server error: got termination event for worker that should have been removed" end MainLoop def mkLeanServerCapabilities : ServerCapabilities := { textDocumentSync? := some { openClose := true change := TextDocumentSyncKind.incremental willSave := false willSaveWaitUntil := false save? := none } -- refine completionProvider? := some { triggerCharacters? := some #["."] } hoverProvider := true declarationProvider := true definitionProvider := true typeDefinitionProvider := true referencesProvider := true workspaceSymbolProvider := true documentHighlightProvider := true documentSymbolProvider := true foldingRangeProvider := true semanticTokensProvider? := some { legend := { tokenTypes := SemanticTokenType.names tokenModifiers := SemanticTokenModifier.names } full := true range := true } codeActionProvider? := some { resolveProvider? := true, codeActionKinds? := some #["quickfix", "refactor"] } } def initAndRunWatchdogAux : ServerM Unit := do let st ← read try discard $ st.hIn.readLspNotificationAs "initialized" InitializedParams let clientTask ← runClientTask mainLoop clientTask catch err => shutdown throw err /- NOTE(WN): It looks like instead of sending the `exit` notification, VSCode just closes the stream. In that case, pretend we got an `exit`. -/ let Message.notification "exit" none ← try st.hIn.readLspMessage catch _ => pure (Message.notification "exit" none) | throwServerError "Got `shutdown` request, expected an `exit` notification" def findWorkerPath : IO System.FilePath := do let mut workerPath ← IO.appPath if let some path := (←IO.getEnv "LEAN_SYSROOT") then workerPath := System.FilePath.mk path / "bin" / "lean" |>.withExtension System.FilePath.exeExtension if let some path := (←IO.getEnv "LEAN_WORKER_PATH") then workerPath := System.FilePath.mk path return workerPath def loadReferences : IO References := do let oleanSearchPath ← Lean.searchPathRef.get let mut refs := References.empty for path in ← oleanSearchPath.findAllWithExt "ilean" do try refs := refs.addIlean path (← Ilean.load path) catch _ => -- could be a race with the build system, for example -- ilean load errors should not be fatal, but we *should* log them -- when we add logging to the server pure () return refs def initAndRunWatchdog (args : List String) (i o e : FS.Stream) : IO Unit := do let workerPath ← findWorkerPath let srcSearchPath ← initSrcSearchPath (← getBuildDir) let references ← IO.mkRef (← loadReferences) let fileWorkersRef ← IO.mkRef (RBMap.empty : FileWorkerMap) let i ← maybeTee "wdIn.txt" false i let o ← maybeTee "wdOut.txt" true o let e ← maybeTee "wdErr.txt" true e let initRequest ← i.readLspRequestAs "initialize" InitializeParams o.writeLspResponse { id := initRequest.id result := { capabilities := mkLeanServerCapabilities serverInfo? := some { name := "Lean 4 Server" version? := "0.1.1" } : InitializeResult } } o.writeLspRequest { id := RequestID.str "register_ilean_watcher" method := "client/registerCapability" param := some { registrations := #[ { id := "ilean_watcher" method := "workspace/didChangeWatchedFiles" registerOptions := some <| toJson { watchers := #[ { globPattern := "**/*.ilean" } ] : DidChangeWatchedFilesRegistrationOptions } } ] : RegistrationParams } } ReaderT.run initAndRunWatchdogAux { hIn := i hOut := o hLog := e args := args fileWorkersRef := fileWorkersRef initParams := initRequest.param editDelay := initRequest.param.initializationOptions? |>.bind InitializationOptions.editDelay? |>.getD 200 workerPath srcSearchPath references : ServerContext } @[export lean_server_watchdog_main] def watchdogMain (args : List String) : IO UInt32 := do let i ← IO.getStdin let o ← IO.getStdout let e ← IO.getStderr try initAndRunWatchdog args i o e return 0 catch err => e.putStrLn s!"Watchdog error: {err}" return 1 end Lean.Server.Watchdog
100ed46e710148f83a2fa27699634e0b6bd0f6e8
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/data/sigma/basic.lean
ff7ddbacfa6888b344555e3beb55faae2714a154
[ "Apache-2.0" ]
permissive
fpvandoorn/mathlib
b21ab4068db079cbb8590b58fda9cc4bc1f35df4
b3433a51ea8bc07c4159c1073838fc0ee9b8f227
refs/heads/master
1,624,791,089,608
1,556,715,231,000
1,556,715,231,000
165,722,980
5
0
Apache-2.0
1,552,657,455,000
1,547,494,646,000
Lean
UTF-8
Lean
false
false
3,155
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl -/ section sigma variables {α : Type*} {β : α → Type*} instance [inhabited α] [inhabited (β (default α))] : inhabited (sigma β) := ⟨⟨default α, default (β (default α))⟩⟩ instance [h₁ : decidable_eq α] [h₂ : ∀a, decidable_eq (β a)] : decidable_eq (sigma β) | ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ := match a₁, b₁, a₂, b₂, h₁ a₁ a₂ with | _, b₁, _, b₂, is_true (eq.refl a) := match b₁, b₂, h₂ a b₁ b₂ with | _, _, is_true (eq.refl b) := is_true rfl | b₁, b₂, is_false n := is_false (assume h, sigma.no_confusion h (λe₁ e₂, n $ eq_of_heq e₂)) end | a₁, _, a₂, _, is_false n := is_false (assume h, sigma.no_confusion h (λe₁ e₂, n e₁)) end @[simp] theorem sigma.mk.inj_iff {a₁ a₂ : α} {b₁ : β a₁} {b₂ : β a₂} : sigma.mk a₁ b₁ = ⟨a₂, b₂⟩ ↔ (a₁ = a₂ ∧ b₁ == b₂) := ⟨sigma.mk.inj, λ ⟨h₁, h₂⟩, by congr; assumption⟩ @[simp] theorem sigma.forall {p : (Σ a, β a) → Prop} : (∀ x, p x) ↔ (∀ a b, p ⟨a, b⟩) := ⟨assume h a b, h ⟨a, b⟩, assume h ⟨a, b⟩, h a b⟩ @[simp] theorem sigma.exists {p : (Σ a, β a) → Prop} : (∃ x, p x) ↔ (∃ a b, p ⟨a, b⟩) := ⟨assume ⟨⟨a, b⟩, h⟩, ⟨a, b, h⟩, assume ⟨a, b, h⟩, ⟨⟨a, b⟩, h⟩⟩ variables {α₁ : Type*} {α₂ : Type*} {β₁ : α₁ → Type*} {β₂ : α₂ → Type*} /-- Map the left and right components of a sigma -/ def sigma.map (f₁ : α₁ → α₂) (f₂ : Πa, β₁ a → β₂ (f₁ a)) : sigma β₁ → sigma β₂ | ⟨a, b⟩ := ⟨f₁ a, f₂ a b⟩ end sigma section psigma variables {α : Sort*} {β : α → Sort*} instance [inhabited α] [inhabited (β (default α))] : inhabited (psigma β) := ⟨⟨default α, default (β (default α))⟩⟩ instance [h₁ : decidable_eq α] [h₂ : ∀a, decidable_eq (β a)] : decidable_eq (psigma β) | ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ := match a₁, b₁, a₂, b₂, h₁ a₁ a₂ with | _, b₁, _, b₂, is_true (eq.refl a) := match b₁, b₂, h₂ a b₁ b₂ with | _, _, is_true (eq.refl b) := is_true rfl | b₁, b₂, is_false n := is_false (assume h, psigma.no_confusion h (λe₁ e₂, n $ eq_of_heq e₂)) end | a₁, _, a₂, _, is_false n := is_false (assume h, psigma.no_confusion h (λe₁ e₂, n e₁)) end theorem psigma.mk.inj_iff {a₁ a₂ : α} {b₁ : β a₁} {b₂ : β a₂} : @psigma.mk α β a₁ b₁ = @psigma.mk α β a₂ b₂ ↔ (a₁ = a₂ ∧ b₁ == b₂) := iff.intro psigma.mk.inj $ assume ⟨h₁, h₂⟩, match a₁, a₂, b₁, b₂, h₁, h₂ with _, _, _, _, eq.refl a, heq.refl b := rfl end variables {α₁ : Sort*} {α₂ : Sort*} {β₁ : α₁ → Sort*} {β₂ : α₂ → Sort*} /-- Map the left and right components of a sigma -/ def psigma.map (f₁ : α₁ → α₂) (f₂ : Πa, β₁ a → β₂ (f₁ a)) : psigma β₁ → psigma β₂ | ⟨a, b⟩ := ⟨f₁ a, f₂ a b⟩ end psigma