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
1b00cb01fa66cea297106dedb5102dfbba83600b
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/add_decl.lean
fd0471499365620ced6280b22c2e965d6680b9cc
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
1,465
lean
prelude import init.meta.tactic open tactic expr /- inductive foo (α : Type) | constr : foo -/ run_cmd do α ← mk_local_def `α `(Type), let c : expr := (@const tt `foo []).app α, env ← get_env, env.add_ginductive options.mk [] [α] [((`foo, `(Type)), [⟨`foo.constr, c, default⟩])] ff >>= set_env #print foo /- mutual inductive odd, even (α : Type) (zero : α) (succ : α → α) with odd : α → Prop | succ {n} : even n → odd (succ n) with even : α → Prop | zero : even zero | succ {n} : odd n → even (succ n) -/ run_cmd do env ← get_env, α ← mk_local_def `α `(Type), zero ← mk_local_def `zero α, succ ← mk_local_def `succ `((%%α : Type) → (%%α : Type)), let odd : expr := (@const tt `odd []).app α zero succ, let even : expr := (@const tt `even []).app α zero succ, let pred := `((%%α : Type) → Prop), n ← mk_local' `n binder_info.implicit α, let odd_succ_ty := `((%%(even n) : Prop) → (%%(odd (succ n)) : Prop)).bind_pi n, let even_succ_ty := `((%%(odd n) : Prop) → (%%(even (succ n)) : Prop)).bind_pi n, pp odd_succ_ty >>= trace, env.add_ginductive options.mk [] [α, zero, succ] [ ((`odd, `((%%α : Type) → Prop)), [⟨`odd.succ, odd_succ_ty, default⟩]), ((`even, `((%%α : Type) → Prop)), [⟨`even.zero, even zero, default⟩, ⟨`even.succ, even_succ_ty, default⟩])] ff >>= set_env #print prefix odd #print prefix even
4ff8d08cac5e38add575979d78af8b03fb2898b7
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/Reparen.lean
1683203355121d4506e264564ab02c92faa0c9a1
[ "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
2,270
lean
import Lean.Parser /-! Reprint file after removing all parentheses and then passing it through the parenthesizer -/ open Lean open Std.Format open Std def unparenAux (parens body : Syntax) : Syntax := match parens.getHeadInfo, body.getHeadInfo, body.getTailInfo, parens.getTailInfo with | SourceInfo.original lead _ _ _, SourceInfo.original _ pos trail pos', SourceInfo.original endLead endPos _ endPos', SourceInfo.original _ _ endTrail _ => body.setHeadInfo (SourceInfo.original lead pos trail pos') |>.setTailInfo (SourceInfo.original endLead endPos endTrail endPos') | _, _, _, _ => body partial def unparen : Syntax → Syntax -- don't remove parentheses in syntax quotations, they might be semantically significant | stx => if stx.isOfKind `Lean.Parser.Term.stxQuot then stx else match stx with | `(($stx')) => unparenAux stx $ unparen stx' | `(level|($stx')) => unparenAux stx $ unparen stx' | _ => stx.modifyArgs $ Array.map unparen 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.testParseFile env args.head!; let header := stx.raw.getArg 0; let some s ← pure header.reprint | throw $ IO.userError "header reprint failed"; IO.print s; let cmds := (stx.raw.getArg 1).getArgs; cmds.forM $ fun cmd => do let cmd := unparen cmd; let (cmd, _) ← (tryFinally (PrettyPrinter.parenthesizeCommand cmd) printTraces).toIO { options := Options.empty.setBool `trace.PrettyPrinter.parenthesize debug, fileName := "", fileMap := default } { env := env }; let some s ← pure cmd.reprint | throw $ IO.userError "cmd reprint failed"; IO.print s #eval main ["../../../src/Init/Prelude.lean"] def check (stx : Syntax) : CoreM Unit := do let stx' := unparen stx; let stx' ← PrettyPrinter.parenthesizeTerm stx'; let f ← PrettyPrinter.formatTerm stx'; IO.println f; if (stx != stx') then throwError "reparenthesization failed" open Lean syntax:80 term " ^~ " term:80 : term syntax:70 term " *~ " term:71 : term #eval check $ Unhygienic.run `(((1 + 2) *~ 3) ^~ 4) #eval check $ Unhygienic.run `(opaque foo (a := (by exact 1)) : True)
191e53c02082e08b17ec74ecde3c87dc506329e8
8c9f90127b78cbeb5bb17fd6b5db1db2ffa3cbc4
/existsExercise.lean
5f4e00958b015d5f3985281ed48eb25cf742e863
[]
no_license
picrin/lean
420f4d08bb3796b911d56d0938e4410e1da0e072
3d10c509c79704aa3a88ebfb24d08b30ce1137cc
refs/heads/master
1,611,166,610,726
1,536,671,438,000
1,536,671,438,000
60,029,899
0
0
null
null
null
null
UTF-8
Lean
false
false
8,633
lean
open classical variables (A : Type) (p q : A → Prop) variable a : A variable r : Prop lemma doubleNegate {r : Prop} : r → ¬ ¬ r := assume (Hr : r) (nHr : ¬ r), nHr Hr lemma doubleNegateRev {r : Prop} : ¬ ¬ r → r := assume (Hr : ¬ ¬ r), have J : r ∨ ¬ r, from em r, or.elim J (λ (H : r), H) (λ (H : ¬ r), false.elim (Hr H)) lemma compose {p q r : Prop} : (p → q) → (q → r) → (p → r) := λ (H : (p → q)), λ (H1 : (q → r)), λ (Hp : p), H1 (H Hp) lemma existsNotForall : (∃ x, p x) → ¬ (∀ x, ¬ p x) := assume Hexists : (∃ x, p x), assume Hforall : ((∀ x, ¬ p x)), exists.elim Hexists (assume a : A, Hforall a) #check exists.elim lemma existsFalseNotForall : (∃ x, ¬ p x) → ¬ (∀ x, p x) := assume H : (∃ x, ¬ p x), assume H1 : (∀ x, p x), have H1Rewr : (∀ x, ¬ ¬ p x), from (λ (x : A), doubleNegate (H1 x)), have flema : (∃ x, ¬ p x) → ¬ (∀ x, ¬ ¬ p x), from (existsNotForall A (λ (a : A), ¬ p a)), have notForall : ¬ (∀ x, ¬ ¬ p x), from flema H, show false, from notForall H1Rewr lemma notForallExists : ¬ (∀ x, p x) → (∃ x, ¬ p x) := assume H : (∀ x, p x) → false, have S1 : Π y, p y ∨ ¬ p y, from assume (y : A), em (p y), have S3 : Π y, p y ∨ (∃ x, ¬ p x), from assume (y : A), or.elim (S1 y) (λ (Hp : p y), or.intro_left (∃ x, ¬ p x) Hp) (λ (Hnp : ¬ p y), or.intro_right (p y) (exists.intro y Hnp)), show (∃ x, ¬ p x), from by_contradiction (assume Hnexist : ¬ (∃ x, ¬ p x), have S4 : Π y, p y, from assume (y : A), or.elim (S3 y) (λ (Hp : p y), Hp) (λ (Hexists : (∃ x, ¬ p x)), false.elim (Hnexist Hexists)), show false, from H S4) theorem distributiveForAll : (∀ (x : A), r ∨ p x) ↔ (r ∨ ∀ (x : A), p x) := iff.intro (λ (H : (∀ (x : A), r ∨ p x)), show (r ∨ ∀ (x : A), p x), from or.elim (em r) (λ (Pr : r), or.intro_left (∀ (y : A), p y) (Pr)) (λ (Pnr : ¬r), or.intro_right r (λ (y : A), or.elim (H y) (λ (Pr : r), false.elim (Pnr Pr)) (λ (Ppy : p y), Ppy)))) (λ (H : (r ∨ ∀ (x : A), p x)), or.elim H (λ (Pr : r), ( λ (x : A), or.intro_left (p x) Pr)) (λ (PApx : (∀ (x : A), p x)), (λ (x : A), or.intro_right (r) (PApx x)))) example : (∃ x : A, r) → r := assume S1 : (∃ x : A, r), have S2 : (A → r → r), from (λ a : A, λ Hr : r, Hr), (exists.elim S1) S2 example : r → (∃ x : A, r) := λ (Hr : r), exists.intro a Hr example : (∃ x, p x ∧ r) ↔ (∃ x, p x) ∧ r := iff.intro (assume (HexistsTogether : (∃ x, p x ∧ r)), exists.elim HexistsTogether (assume a : A, (assume H : p a ∧ r, and.intro (exists.intro a (and.elim_left H)) (and.elim_right H)))) (assume (HexistSeparately : (∃ x, p x) ∧ r), exists.elim (and.elim_left HexistSeparately) (assume (x : A), assume (Hpx : p x), exists.intro x (and.intro Hpx (and.elim_right HexistSeparately)))) #check exists.elim example : (∃ x, p x ∨ q x) ↔ (∃ x, p x) ∨ (∃ x, q x) := iff.intro (assume (H : (∃ x, p x ∨ q x)), exists.elim H (assume x : A, assume Por : p x ∨ q x, (or.elim Por) (assume Hpx : p x, or.intro_left (∃ x, q x) (exists.intro x Hpx)) (assume Hqx : q x, or.intro_right (∃ x, p x) (exists.intro x Hqx)))) (assume (H : (∃ x, p x) ∨ (∃ x, q x)), or.elim H (assume (left : (∃ x, p x)), obtain (x : A) (Hpx : p x), from left, exists.intro x (or.intro_left (q x) Hpx)) (assume (right : (∃ x, q x)), obtain (x : A) (Hqx : q x), from right, exists.intro x (or.intro_right (p x) Hqx))) example : (∀ x, p x) ↔ ¬ (∃ x, ¬ p x) := iff.intro (assume (H : ∀ x, p x), (assume (H1 : (∃ x, ¬ p x)), obtain (x : A) (Pnx : ¬ p x), from H1, have p x, from H x, show false, from `¬ p x` `p x`)) (assume (H: ¬ (∃ x, ¬ p x)), (λ (x : A), show p x, from by_contradiction (λ (H1 : ¬ p x), (show false, from have H2 : (∃ x, ¬ p x), from exists.intro x H1, H H2)))) lemma existsEqNotForall : (∃ x, p x) ↔ ¬ (∀ x, ¬ p x) := iff.intro (assume H : (∃ x, p x), (λ (H1 : (∀ x, ¬ p x)), obtain (x : A) (Hpx : p x), from H, H1 x Hpx)) (assume H : ¬ (∀ x, ¬ p x), show (∃ x, p x), from have S1 : (∀ x, p x ∨ ¬ p x), from (λ (x : A), em (p x)), have S2 : (∀ x, (∃ y, p y) ∨ ¬ p x), from (λ (x : A), or.elim (S1 x) (λ (Hpx : p x), or.intro_left (¬ p x) (exists.intro x Hpx)) (λ (Hnpx : ¬ p x), or.intro_right (∃ x, p x) Hnpx)), have S3 : ((∃ y, p y) ∨ (∀ x, ¬ p x)), from (iff.elim_left (distributiveForAll A (λ (x : A), ¬ p x) (∃ y, p y))) S2, show (∃ y, p y), from or.elim S3 (λ (Hexists : (∃ y, p y)), Hexists) (λ (HforallNot : (∀ x, ¬ p x)), false.elim(H HforallNot))) lemma contrapositive {p : Prop} {q : Prop} : (p → q) → (¬ q → ¬p) := assume (H : (p → q)), assume (S1 : ¬ q), assume (S2 : p), S1 (H S2) lemma iffContr {p : Prop} {q : Prop} : (p ↔ q) → (¬ p ↔ ¬ q) := (λ (H : p ↔ q), have p → q, from iff.elim_left H, have q → p, from iff.elim_right H, iff.intro (contrapositive `q → p`) (contrapositive `p → q`)) example : (¬ ∃ x, p x) ↔ (∀ x, ¬ p x) := iff.intro (λ (H : ¬ ∃ x, p x), (λ (x : A), λ (Hpx : p x), H (exists.intro x Hpx))) (have S1 : (∃ x, p x) → ¬ (∀ x, ¬ p x), from existsNotForall A p, have S2 : ¬ ¬ (∀ x, ¬ p x) → ¬ (∃ x, p x), from contrapositive S1, show (∀ x, ¬ p x) → ¬ (∃ x, p x), from compose (λ (H : (∀ x, ¬ p x)), doubleNegate H) (S2 : ¬ ¬ (∀ x, ¬ p x) → ¬ (∃ x, p x))) example : (∀ x, r → p x) → (r → ∀ x, p x) := (λ (H : (∀ x, r → p x)), λ (Pr : r), λ (x : A), H x Pr) example : (r → ∀ x, p x) → (∀ x, r → p x) := (λ (H : (r → ∀ x, p x)), λ (x : A), λ (Pr : r), (H Pr) x) example : (¬ ∀ x, p x) ↔ (∃ x, ¬ p x) := iff.intro (notForallExists A p) (existsFalseNotForall A p) example : (∀ x, p x → r) → (∃ x, p x) → r := assume (H : (∀ x, p x → r)), λ (H1 : (∃ x, p x)), obtain (x : A) (H2 : p x), from H1, H x H2 example : ((∃ x, p x) → r) → (∀ x, p x → r) := assume (H : (∃ x, p x) → r), λ (x : A), λ (Ppx : p x), H (exists.intro x Ppx) example : (∃ x, p x → r) → (∀ x, p x) → r := λ (H : (∃ x, p x → r)), λ (H1 : (∀ x, p x)), obtain (x : A) (Hpxr : p x → r), from H, Hpxr (H1 x) example : ((∀ x, p x) → r) → (∃ x, p x → r) := λ H : (∀ x, p x) → r, have S1 : ∀ x, (p x ∨ ¬ p x), from λ (x : A), em (p x), have S2 : ∀ x, (∃ x, ¬ p x) ∨ p x, from λ (x : A), or.elim (S1 x) (λ H : p x, or.intro_right (∃ x, ¬ p x) H) (λ H : ¬ p x, or.intro_left (p x) (exists.intro x H)), have S3 : ((∃ x, ¬ p x) ∨ ∀ x, p x), from (iff.elim_left (distributiveForAll A (λ x : A, p x) (∃ x, ¬ p x))) S2, or.elim S3 (λ S4 : (∃ x, ¬ p x), obtain (x : A) (Pnx : ¬ p x), from S4, exists.intro x (λ H : p x, false.elim (Pnx H))) (λ S5 : ∀ x, p x, exists.intro a ( λ H1 : p a, H S5)) example : (∃ x, r → p x) → (r → ∃ x, p x) := λ H : (∃ x, r → p x), obtain (x : A) (P : r → p x), from H, λ (Pr : r), exists.intro x (P Pr) example : (r → ∃ x, p x) → (∃ x, r → p x) := λ H : (r → ∃ x, p x), or.elim (em r) (λ Pr : r, obtain (x : A) (Ppx : p x), from (H Pr), exists.intro x (λ Pr : r, Ppx)) (λ Pnr : ¬r, have r → p a, from (λ Pr : r, false.elim (Pnr Pr)), exists.intro a `r → p a`)
c8ff0557a74f5917b3e82a15d8bb9ea9315ec432
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/hom/units.lean
47a65c30dcdf33a10ef48afbf9e8da6509ed5359
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
5,205
lean
/- Copyright (c) 2018 Johan Commelin All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Chris Hughes, Kevin Buzzard -/ import algebra.hom.group /-! # Lift monoid homomorphisms to group homomorphisms of their units subgroups. -/ universes u v w namespace units variables {M : Type u} {N : Type v} {P : Type w} [monoid M] [monoid N] [monoid P] /-- The group homomorphism on units induced by a `monoid_hom`. -/ @[to_additive "The `add_group` homomorphism on `add_unit`s induced by an `add_monoid_hom`."] def map (f : M →* N) : Mˣ →* Nˣ := monoid_hom.mk' (λ u, ⟨f u.val, f u.inv, by rw [← f.map_mul, u.val_inv, f.map_one], by rw [← f.map_mul, u.inv_val, f.map_one]⟩) (λ x y, ext (f.map_mul x y)) @[simp, to_additive] lemma coe_map (f : M →* N) (x : Mˣ) : ↑(map f x) = f x := rfl @[simp, to_additive] lemma coe_map_inv (f : M →* N) (u : Mˣ) : ↑(map f u)⁻¹ = f ↑u⁻¹ := rfl @[simp, to_additive] lemma map_comp (f : M →* N) (g : N →* P) : map (g.comp f) = (map g).comp (map f) := rfl variables (M) @[simp, to_additive] lemma map_id : map (monoid_hom.id M) = monoid_hom.id Mˣ := by ext; refl /-- Coercion `Mˣ → M` as a monoid homomorphism. -/ @[to_additive "Coercion `add_units M → M` as an add_monoid homomorphism."] def coe_hom : Mˣ →* M := ⟨coe, coe_one, coe_mul⟩ variable {M} @[simp, to_additive] lemma coe_hom_apply (x : Mˣ) : coe_hom M x = ↑x := rfl @[simp, norm_cast, to_additive] lemma coe_pow (u : Mˣ) (n : ℕ) : ((u ^ n : Mˣ) : M) = u ^ n := (units.coe_hom M).map_pow u n @[simp, norm_cast, to_additive] lemma coe_zpow {G} [group G] (u : Gˣ) (n : ℤ) : ((u ^ n : Gˣ) : G) = u ^ n := (units.coe_hom G).map_zpow u n /-- If a map `g : M → Nˣ` agrees with a homomorphism `f : M →* N`, then this map is a monoid homomorphism too. -/ @[to_additive "If a map `g : M → add_units N` agrees with a homomorphism `f : M →+ N`, then this map is an add_monoid homomorphism too."] def lift_right (f : M →* N) (g : M → Nˣ) (h : ∀ x, ↑(g x) = f x) : M →* Nˣ := { to_fun := g, map_one' := units.ext $ (h 1).symm ▸ f.map_one, map_mul' := λ x y, units.ext $ by simp only [h, coe_mul, f.map_mul] } @[simp, to_additive] lemma coe_lift_right {f : M →* N} {g : M → Nˣ} (h : ∀ x, ↑(g x) = f x) (x) : (lift_right f g h x : N) = f x := h x @[simp, to_additive] lemma mul_lift_right_inv {f : M →* N} {g : M → Nˣ} (h : ∀ x, ↑(g x) = f x) (x) : f x * ↑(lift_right f g h x)⁻¹ = 1 := by rw [units.mul_inv_eq_iff_eq_mul, one_mul, coe_lift_right] @[simp, to_additive] lemma lift_right_inv_mul {f : M →* N} {g : M → Nˣ} (h : ∀ x, ↑(g x) = f x) (x) : ↑(lift_right f g h x)⁻¹ * f x = 1 := by rw [units.inv_mul_eq_iff_eq_mul, mul_one, coe_lift_right] end units namespace monoid_hom /-- If `f` is a homomorphism from a group `G` to a monoid `M`, then its image lies in the units of `M`, and `f.to_hom_units` is the corresponding monoid homomorphism from `G` to `Mˣ`. -/ @[to_additive "If `f` is a homomorphism from an additive group `G` to an additive monoid `M`, then its image lies in the `add_units` of `M`, and `f.to_hom_units` is the corresponding homomorphism from `G` to `add_units M`."] def to_hom_units {G M : Type*} [group G] [monoid M] (f : G →* M) : G →* Mˣ := { to_fun := λ g, ⟨f g, f (g⁻¹), by rw [← f.map_mul, mul_inv_self, f.map_one], by rw [← f.map_mul, inv_mul_self, f.map_one]⟩, map_one' := units.ext (f.map_one), map_mul' := λ _ _, units.ext (f.map_mul _ _) } @[simp] lemma coe_to_hom_units {G M : Type*} [group G] [monoid M] (f : G →* M) (g : G): (f.to_hom_units g : M) = f g := rfl end monoid_hom section is_unit variables {M : Type*} {N : Type*} @[to_additive] lemma is_unit.map {F : Type*} [monoid M] [monoid N] [monoid_hom_class F M N] (f : F) {x : M} (h : is_unit x) : is_unit (f x) := by rcases h with ⟨y, rfl⟩; exact (units.map (f : M →* N) y).is_unit /-- If a homomorphism `f : M →* N` sends each element to an `is_unit`, then it can be lifted to `f : M →* Nˣ`. See also `units.lift_right` for a computable version. -/ @[to_additive "If a homomorphism `f : M →+ N` sends each element to an `is_add_unit`, then it can be lifted to `f : M →+ add_units N`. See also `add_units.lift_right` for a computable version."] noncomputable def is_unit.lift_right [monoid M] [monoid N] (f : M →* N) (hf : ∀ x, is_unit (f x)) : M →* Nˣ := units.lift_right f (λ x, (hf x).unit) $ λ x, rfl @[to_additive] lemma is_unit.coe_lift_right [monoid M] [monoid N] (f : M →* N) (hf : ∀ x, is_unit (f x)) (x) : (is_unit.lift_right f hf x : N) = f x := rfl @[simp, to_additive] lemma is_unit.mul_lift_right_inv [monoid M] [monoid N] (f : M →* N) (h : ∀ x, is_unit (f x)) (x) : f x * ↑(is_unit.lift_right f h x)⁻¹ = 1 := units.mul_lift_right_inv (λ y, rfl) x @[simp, to_additive] lemma is_unit.lift_right_inv_mul [monoid M] [monoid N] (f : M →* N) (h : ∀ x, is_unit (f x)) (x) : ↑(is_unit.lift_right f h x)⁻¹ * f x = 1 := units.lift_right_inv_mul (λ y, rfl) x end is_unit
39f3e2aad987ef9d3bce33aaae91217ab6148262
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/tactic/monotonicity/interactive.lean
48e9ab0f82b0588872fc836c0ab98fca287057e3
[ "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
23,531
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import tactic.monotonicity.basic import control.traversable import control.traversable.derive import data.dlist variables {a b c p : Prop} namespace tactic.interactive open lean lean.parser interactive open interactive.types open tactic local postfix `?`:9001 := optional local postfix *:9001 := many meta inductive mono_function (elab : bool := tt) | non_assoc : expr elab → list (expr elab) → list (expr elab) → mono_function | assoc : expr elab → option (expr elab) → option (expr elab) → mono_function | assoc_comm : expr elab → expr elab → mono_function meta instance : decidable_eq mono_function := by mk_dec_eq_instance meta def mono_function.to_tactic_format : mono_function → tactic format | (mono_function.non_assoc fn xs ys) := do fn' ← pp fn, xs' ← mmap pp xs, ys' ← mmap pp ys, return format!"{fn'} {xs'} _ {ys'}" | (mono_function.assoc fn xs ys) := do fn' ← pp fn, xs' ← pp xs, ys' ← pp ys, return format!"{fn'} {xs'} _ {ys'}" | (mono_function.assoc_comm fn xs) := do fn' ← pp fn, xs' ← pp xs, return format!"{fn'} _ {xs'}" meta instance has_to_tactic_format_mono_function : has_to_tactic_format mono_function := { to_tactic_format := mono_function.to_tactic_format } @[derive traversable] meta structure ac_mono_ctx' (rel : Type) := (to_rel : rel) (function : mono_function) (left right rel_def : expr) @[reducible] meta def ac_mono_ctx := ac_mono_ctx' (option (expr → expr → expr)) @[reducible] meta def ac_mono_ctx_ne := ac_mono_ctx' (expr → expr → expr) meta def ac_mono_ctx.to_tactic_format (ctx : ac_mono_ctx) : tactic format := do fn ← pp ctx.function, l ← pp ctx.left, r ← pp ctx.right, rel ← pp ctx.rel_def, return format!"{{ function := {fn}\n, left := {l}\n, right := {r}\n, rel_def := {rel} }" meta instance has_to_tactic_format_mono_ctx : has_to_tactic_format ac_mono_ctx := { to_tactic_format := ac_mono_ctx.to_tactic_format } meta def as_goal (e : expr) (tac : tactic unit) : tactic unit := do gs ← get_goals, set_goals [e], tac, set_goals gs open list (hiding map) functor dlist section config parameter opt : mono_cfg parameter asms : list expr meta def unify_with_instance (e : expr) : tactic unit := as_goal e $ apply_instance <|> apply_opt_param <|> apply_auto_param <|> tactic.solve_by_elim { lemmas := some asms } <|> reflexivity <|> applyc ``id <|> return () private meta def match_rule_head (p : expr) : list expr → expr → expr → tactic expr | vs e t := (unify t p >> mmap' unify_with_instance vs >> instantiate_mvars e) <|> do (expr.pi _ _ d b) ← return t | failed, v ← mk_meta_var d, match_rule_head (v::vs) (expr.app e v) (b.instantiate_var v) meta def pi_head : expr → tactic expr | (expr.pi n _ t b) := do v ← mk_meta_var t, pi_head (b.instantiate_var v) | e := return e meta def delete_expr (e : expr) : list expr → tactic (option (list expr)) | [] := return none | (x :: xs) := (compare opt e x >> return (some xs)) <|> (map (cons x) <$> delete_expr xs) meta def match_ac' : list expr → list expr → tactic (list expr × list expr × list expr) | es (x :: xs) := do es' ← delete_expr x es, match es' with | (some es') := do (c,l,r) ← match_ac' es' xs, return (x::c,l,r) | none := do (c,l,r) ← match_ac' es xs, return (c,l,x::r) end | es [] := do return ([],es,[]) meta def match_ac (l : list expr) (r : list expr) : tactic (list expr × list expr × list expr) := do (s',l',r') ← match_ac' l r, s' ← mmap instantiate_mvars s', l' ← mmap instantiate_mvars l', r' ← mmap instantiate_mvars r', return (s',l',r') meta def match_prefix : list expr → list expr → tactic (list expr × list expr × list expr) | (x :: xs) (y :: ys) := (do compare opt x y, prod.map ((::) x) id <$> match_prefix xs ys) <|> return ([],x :: xs,y :: ys) | xs ys := return ([],xs,ys) /-- `(prefix,left,right,suffix) ← match_assoc unif l r` finds the longest prefix and suffix common to `l` and `r` and returns them along with the differences -/ meta def match_assoc (l : list expr) (r : list expr) : tactic (list expr × list expr × list expr × list expr) := do (pre,l₁,r₁) ← match_prefix l r, (suf,l₂,r₂) ← match_prefix (reverse l₁) (reverse r₁), return (pre,reverse l₂,reverse r₂,reverse suf) meta def check_ac : expr → tactic (bool × bool × option (expr × expr × expr) × expr) | (expr.app (expr.app f x) y) := do t ← infer_type x, a ← try_core $ to_expr ``(is_associative %%t %%f) >>= mk_instance, c ← try_core $ to_expr ``(is_commutative %%t %%f) >>= mk_instance, i ← try_core (do v ← mk_meta_var t, l_inst_p ← to_expr ``(is_left_id %%t %%f %%v), r_inst_p ← to_expr ``(is_right_id %%t %%f %%v), l_v ← mk_meta_var l_inst_p, r_v ← mk_meta_var r_inst_p , l_id ← mk_mapp `is_left_id.left_id [some t,f,v,some l_v], mk_instance l_inst_p >>= unify l_v, r_id ← mk_mapp `is_right_id.right_id [none,f,v,some r_v], mk_instance r_inst_p >>= unify r_v, v' ← instantiate_mvars v, return (l_id,r_id,v')), return (a.is_some,c.is_some,i,f) | _ := return (ff,ff,none,expr.var 1) meta def parse_assoc_chain' (f : expr) : expr → tactic (dlist expr) | e := (do (expr.app (expr.app f' x) y) ← return e, is_def_eq f f', (++) <$> parse_assoc_chain' x <*> parse_assoc_chain' y) <|> return (singleton e) meta def parse_assoc_chain (f : expr) : expr → tactic (list expr) := map dlist.to_list ∘ parse_assoc_chain' f meta def fold_assoc (op : expr) : option (expr × expr × expr) → list expr → option (expr × list expr) | _ (x::xs) := some (foldl (expr.app ∘ expr.app op) x xs, []) | none [] := none | (some (l_id,r_id,x₀)) [] := some (x₀,[l_id,r_id]) meta def fold_assoc1 (op : expr) : list expr → option expr | (x::xs) := some $ foldl (expr.app ∘ expr.app op) x xs | [] := none meta def same_function_aux : list expr → list expr → expr → expr → tactic (expr × list expr × list expr) | xs₀ xs₁ (expr.app f₀ a₀) (expr.app f₁ a₁) := same_function_aux (a₀ :: xs₀) (a₁ :: xs₁) f₀ f₁ | xs₀ xs₁ e₀ e₁ := is_def_eq e₀ e₁ >> return (e₀,xs₀,xs₁) meta def same_function : expr → expr → tactic (expr × list expr × list expr) := same_function_aux [] [] meta def parse_ac_mono_function (l r : expr) : tactic (expr × expr × list expr × mono_function) := do (full_f,ls,rs) ← same_function l r, (a,c,i,f) ← check_ac l, if a then if c then do (s,ls,rs) ← monad.join (match_ac <$> parse_assoc_chain f l <*> parse_assoc_chain f r), (l',l_id) ← fold_assoc f i ls, (r',r_id) ← fold_assoc f i rs, s' ← fold_assoc1 f s, return (l',r',l_id ++ r_id,mono_function.assoc_comm f s') else do -- a ∧ ¬ c (pre,ls,rs,suff) ← monad.join (match_assoc <$> parse_assoc_chain f l <*> parse_assoc_chain f r), (l',l_id) ← fold_assoc f i ls, (r',r_id) ← fold_assoc f i rs, let pre' := fold_assoc1 f pre, let suff' := fold_assoc1 f suff, return (l',r',l_id ++ r_id,mono_function.assoc f pre' suff') else do -- ¬ a (xs₀,x₀,x₁,xs₁) ← find_one_difference opt ls rs, return (x₀,x₁,[],mono_function.non_assoc full_f xs₀ xs₁) meta def parse_ac_mono_function' (l r : pexpr) := do l' ← to_expr l, r' ← to_expr r, parse_ac_mono_function l' r' meta def ac_monotonicity_goal : expr → tactic (expr × expr × list expr × ac_mono_ctx) | `(%%e₀ → %%e₁) := do (l,r,id_rs,f) ← parse_ac_mono_function e₀ e₁, t₀ ← infer_type e₀, t₁ ← infer_type e₁, rel_def ← to_expr ``(λ x₀ x₁, (x₀ : %%t₀) → (x₁ : %%t₁)), return (e₀, e₁, id_rs, { function := f , left := l, right := r , to_rel := some $ expr.pi `x binder_info.default , rel_def := rel_def }) | `(%%e₀ = %%e₁) := do (l,r,id_rs,f) ← parse_ac_mono_function e₀ e₁, t₀ ← infer_type e₀, t₁ ← infer_type e₁, rel_def ← to_expr ``(λ x₀ x₁, (x₀ : %%t₀) = (x₁ : %%t₁)), return (e₀, e₁, id_rs, { function := f , left := l, right := r , to_rel := none , rel_def := rel_def }) | (expr.app (expr.app rel e₀) e₁) := do (l,r,id_rs,f) ← parse_ac_mono_function e₀ e₁, return (e₀, e₁, id_rs, { function := f , left := l, right := r , to_rel := expr.app ∘ expr.app rel , rel_def := rel }) | _ := fail "invalid monotonicity goal" meta def bin_op_left (f : expr) : option expr → expr → expr | none e := e | (some e₀) e₁ := f.mk_app [e₀,e₁] meta def bin_op (f a b : expr) : expr := f.mk_app [a,b] meta def bin_op_right (f : expr) : expr → option expr → expr | e none := e | e₀ (some e₁) := f.mk_app [e₀,e₁] meta def mk_fun_app : mono_function → expr → expr | (mono_function.non_assoc f x y) z := f.mk_app (x ++ z :: y) | (mono_function.assoc f x y) z := bin_op_left f x (bin_op_right f z y) | (mono_function.assoc_comm f x) z := f.mk_app [z,x] meta inductive mono_law /- `assoc (l₀,r₀) (r₁,l₁)` gives first how to find rules to prove x+(y₀+z) R x+(y₁+z); if that fails, helps prove (x+y₀)+z R (x+y₁)+z -/ | assoc : expr × expr → expr × expr → mono_law /- `congr r` gives the rule to prove `x = y → f x = f y` -/ | congr : expr → mono_law | other : expr → mono_law meta def mono_law.to_tactic_format : mono_law → tactic format | (mono_law.other e) := do e ← pp e, return format!"other {e}" | (mono_law.congr r) := do e ← pp r, return format!"congr {e}" | (mono_law.assoc (x₀,x₁) (y₀,y₁)) := do x₀ ← pp x₀, x₁ ← pp x₁, y₀ ← pp y₀, y₁ ← pp y₁, return format!"assoc {x₀}; {x₁} | {y₀}; {y₁}" meta instance has_to_tactic_format_mono_law : has_to_tactic_format mono_law := { to_tactic_format := mono_law.to_tactic_format } meta def mk_rel (ctx : ac_mono_ctx_ne) (f : expr → expr) : expr := ctx.to_rel (f ctx.left) (f ctx.right) meta def mk_congr_args (fn : expr) (xs₀ xs₁ : list expr) (l r : expr) : tactic expr := do p ← mk_app `eq [fn.mk_app $ xs₀ ++ l :: xs₁,fn.mk_app $ xs₀ ++ r :: xs₁], prod.snd <$> solve_aux p (do iterate_exactly (xs₁.length) (applyc `congr_fun), applyc `congr_arg) meta def mk_congr_law (ctx : ac_mono_ctx) : tactic expr := match ctx.function with | (mono_function.assoc f x₀ x₁) := if (x₀ <|> x₁).is_some then mk_congr_args f x₀.to_monad x₁.to_monad ctx.left ctx.right else failed | (mono_function.assoc_comm f x₀) := mk_congr_args f [x₀] [] ctx.left ctx.right | (mono_function.non_assoc f x₀ x₁) := mk_congr_args f x₀ x₁ ctx.left ctx.right end meta def mk_pattern (ctx : ac_mono_ctx) : tactic mono_law := match (sequence ctx : option (ac_mono_ctx' _)) with | (some ctx) := match ctx.function with | (mono_function.assoc f (some x) (some y)) := return $ mono_law.assoc ( mk_rel ctx (λ i, bin_op f x (bin_op f i y)) , mk_rel ctx (λ i, bin_op f i y)) ( mk_rel ctx (λ i, bin_op f (bin_op f x i) y) , mk_rel ctx (λ i, bin_op f x i)) | (mono_function.assoc f (some x) none) := return $ mono_law.other $ mk_rel ctx (λ e, mk_fun_app ctx.function e) | (mono_function.assoc f none (some y)) := return $ mono_law.other $ mk_rel ctx (λ e, mk_fun_app ctx.function e) | (mono_function.assoc f none none) := none | _ := return $ mono_law.other $ mk_rel ctx (λ e, mk_fun_app ctx.function e) end | none := mono_law.congr <$> mk_congr_law ctx end meta def match_rule (pat : expr) (r : name) : tactic expr := do r' ← mk_const r, t ← infer_type r', t ← expr.dsimp t { fail_if_unchanged := ff } tt [] [ simp_arg_type.expr ``(monotone), simp_arg_type.expr ``(strict_mono)], match_rule_head pat [] r' t meta def find_lemma (pat : expr) : list name → tactic (list expr) | [] := return [] | (r :: rs) := do (cons <$> match_rule pat r <|> pure id) <*> find_lemma rs meta def match_chaining_rules (ls : list name) (x₀ x₁ : expr) : tactic (list expr) := do x' ← to_expr ``(%%x₁ → %%x₀), r₀ ← find_lemma x' ls, r₁ ← find_lemma x₁ ls, return (expr.app <$> r₀ <*> r₁) meta def find_rule (ls : list name) : mono_law → tactic (list expr) | (mono_law.assoc (x₀,x₁) (y₀,y₁)) := (match_chaining_rules ls x₀ x₁) <|> (match_chaining_rules ls y₀ y₁) | (mono_law.congr r) := return [r] | (mono_law.other p) := find_lemma p ls universes u v def apply_rel {α : Sort u} (R : α → α → Sort v) {x y : α} (x' y' : α) (h : R x y) (hx : x = x') (hy : y = y') : R x' y' := by { rw [← hx,← hy], apply h } meta def ac_refine (e : expr) : tactic unit := refine ``(eq.mp _ %%e) ; ac_refl meta def one_line (e : expr) : tactic format := do lbl ← pp e, asm ← infer_type e >>= pp, return format!"\t{asm}\n" meta def side_conditions (e : expr) : tactic format := do let vs := e.list_meta_vars, ts ← mmap one_line vs.tail, let r := e.get_app_fn.const_name, return format!"{r}:\n{format.join ts}" open monad /-- tactic-facing function, similar to `interactive.tactic.generalize` with the exception that meta variables -/ private meta def monotonicity.generalize' (h : name) (v : expr) (x : name) : tactic (expr × expr) := do tgt ← target, t ← infer_type v, tgt' ← do { ⟨tgt', _⟩ ← solve_aux tgt (tactic.generalize v x >> target), to_expr ``(λ y : %%t, Π x, y = x → %%(tgt'.binding_body.lift_vars 0 1)) } <|> to_expr ``(λ y : %%t, Π x, %%v = x → %%tgt), t ← head_beta (tgt' v) >>= assert h, swap, r ← mk_eq_refl v, solve1 $ tactic.exact (t v r), prod.mk <$> tactic.intro x <*> tactic.intro h private meta def hide_meta_vars (tac : list expr → tactic unit) : tactic unit := focus1 $ do tgt ← target >>= instantiate_mvars, tactic.change tgt, ctx ← local_context, let vs := tgt.list_meta_vars, vs' ← mmap (λ v, do h ← get_unused_name `h, x ← get_unused_name `x, prod.snd <$> monotonicity.generalize' h v x) vs, tac ctx; vs'.mmap' (try ∘ tactic.subst) meta def hide_meta_vars' (tac : itactic) : itactic := hide_meta_vars $ λ _, tac end config meta def solve_mvar (v : expr) (tac : tactic unit) : tactic unit := do gs ← get_goals, set_goals [v], target >>= instantiate_mvars >>= tactic.change, tac, done, set_goals $ gs def list.minimum_on {α β} [linear_order β] (f : α → β) : list α → list α | [] := [] | (x :: xs) := prod.snd $ xs.foldl (λ ⟨k,a⟩ b, let k' := f b in if k < k' then (k,a) else if k' < k then (k', [b]) else (k,b :: a)) (f x, [x]) open format mono_selection meta def best_match {β} (xs : list expr) (tac : expr → tactic β) : tactic unit := do t ← target, xs ← xs.mmap (λ x, try_core $ prod.mk x <$> solve_aux t (tac x >> get_goals)), let xs := xs.filter_map id, let r := list.minimum_on (list.length ∘ prod.fst ∘ prod.snd) xs, match r with | [(_,gs,pr)] := tactic.exact pr >> set_goals gs | [] := fail "no good match found" | _ := do lmms ← r.mmap (λ ⟨l,gs,_⟩, do ts ← gs.mmap infer_type, msg ← ts.mmap pp, pure $ foldl compose "\n\n" (list.intersperse "\n" $ to_fmt l.get_app_fn.const_name :: msg)), let msg := foldl compose "" lmms, fail format!"ambiguous match: {msg}\n\nTip: try asserting a side condition to distinguish between the lemmas" end meta def mono_aux (dir : parse side) : tactic unit := do t ← target >>= instantiate_mvars, ns ← get_monotonicity_lemmas t dir, asms ← local_context, rs ← find_lemma asms t ns, focus1 $ () <$ best_match rs (λ law, tactic.refine $ to_pexpr law) /-- - `mono` applies a monotonicity rule. - `mono*` applies monotonicity rules repetitively. - `mono with x ≤ y` or `mono with [0 ≤ x,0 ≤ y]` creates an assertion for the listed propositions. Those help to select the right monotonicity rule. - `mono left` or `mono right` is useful when proving strict orderings: for `x + y < w + z` could be broken down into either - left: `x ≤ w` and `y < z` or - right: `x < w` and `y ≤ z` - `mono using [rule1,rule2]` calls `simp [rule1,rule2]` before applying mono. - The general syntax is `mono '*'? ('with' hyp | 'with' [hyp1,hyp2])? ('using' [hyp1,hyp2])? mono_cfg? To use it, first import `tactic.monotonicity`. Here is an example of mono: ```lean example (x y z k : ℤ) (h : 3 ≤ (4 : ℤ)) (h' : z ≤ y) : (k + 3 + x) - y ≤ (k + 4 + x) - z := begin mono, -- unfold `(-)`, apply add_le_add { -- ⊢ k + 3 + x ≤ k + 4 + x mono, -- apply add_le_add, refl -- ⊢ k + 3 ≤ k + 4 mono }, { -- ⊢ -y ≤ -z mono /- apply neg_le_neg -/ } end ``` More succinctly, we can prove the same goal as: ```lean example (x y z k : ℤ) (h : 3 ≤ (4 : ℤ)) (h' : z ≤ y) : (k + 3 + x) - y ≤ (k + 4 + x) - z := by mono* ``` -/ meta def mono (many : parse (tk "*")?) (dir : parse side) (hyps : parse $ tk "with" *> pexpr_list_or_texpr <|> pure []) (simp_rules : parse $ tk "using" *> simp_arg_list <|> pure []) : tactic unit := do hyps ← hyps.mmap (λ p, to_expr p >>= mk_meta_var), hyps.mmap' (λ pr, do h ← get_unused_name `h, note h none pr), when (¬ simp_rules.empty) (simp_core { } failed tt simp_rules [] (loc.ns [none]) >> skip), if many.is_some then repeat $ mono_aux dir else mono_aux dir, gs ← get_goals, set_goals $ hyps ++ gs add_tactic_doc { name := "mono", category := doc_category.tactic, decl_names := [`tactic.interactive.mono], tags := ["monotonicity"] } /-- transforms a goal of the form `f x ≼ f y` into `x ≤ y` using lemmas marked as `monotonic`. Special care is taken when `f` is the repeated application of an associative operator and if the operator is commutative -/ meta def ac_mono_aux (cfg : mono_cfg := { mono_cfg . }) : tactic unit := hide_meta_vars $ λ asms, do try `[simp only [sub_eq_add_neg]], tgt ← target >>= instantiate_mvars, (l,r,id_rs,g) ← ac_monotonicity_goal cfg tgt <|> fail "monotonic context not found", ns ← get_monotonicity_lemmas tgt both, p ← mk_pattern g, rules ← find_rule asms ns p <|> fail "no applicable rules found", when (rules = []) (fail "no applicable rules found"), err ← format.join <$> mmap side_conditions rules, focus1 $ best_match rules (λ rule, do t₀ ← mk_meta_var `(Prop), v₀ ← mk_meta_var t₀, t₁ ← mk_meta_var `(Prop), v₁ ← mk_meta_var t₁, tactic.refine $ ``(apply_rel %%(g.rel_def) %%l %%r %%rule %%v₀ %%v₁), solve_mvar v₀ (try (any_of id_rs rewrite_target) >> ( done <|> refl <|> ac_refl <|> `[simp only [is_associative.assoc]]) ), solve_mvar v₁ (try (any_of id_rs rewrite_target) >> ( done <|> refl <|> ac_refl <|> `[simp only [is_associative.assoc]]) ), n ← num_goals, iterate_exactly (n-1) (try $ solve1 $ apply_instance <|> tactic.solve_by_elim { lemmas := some asms })) open sum nat /-- (repeat_until_or_at_most n t u): repeat tactic `t` at most n times or until u succeeds -/ meta def repeat_until_or_at_most : nat → tactic unit → tactic unit → tactic unit | 0 t _ := fail "too many applications" | (succ n) t u := u <|> (t >> repeat_until_or_at_most n t u) meta def repeat_until : tactic unit → tactic unit → tactic unit := repeat_until_or_at_most 100000 @[derive _root_.has_reflect, derive _root_.inhabited] inductive rep_arity : Type | one | exactly (n : ℕ) | many meta def repeat_or_not : rep_arity → tactic unit → option (tactic unit) → tactic unit | rep_arity.one tac none := tac | rep_arity.many tac none := repeat tac | (rep_arity.exactly n) tac none := iterate_exactly' n tac | rep_arity.one tac (some until) := tac >> until | rep_arity.many tac (some until) := repeat_until tac until | (rep_arity.exactly n) tac (some until) := iterate_exactly n tac >> until meta def assert_or_rule : lean.parser (pexpr ⊕ pexpr) := (tk ":=" *> inl <$> texpr <|> (tk ":" *> inr <$> texpr)) meta def arity : lean.parser rep_arity := rep_arity.many <$ tk "*" <|> rep_arity.exactly <$> (tk "^" *> small_nat) <|> pure rep_arity.one /-- `ac_mono` reduces the `f x ⊑ f y`, for some relation `⊑` and a monotonic function `f` to `x ≺ y`. `ac_mono*` unwraps monotonic functions until it can't. `ac_mono^k`, for some literal number `k` applies monotonicity `k` times. `ac_mono := h`, with `h` a hypothesis, unwraps monotonic functions and uses `h` to solve the remaining goal. Can be combined with `*` or `^k`: `ac_mono* := h` `ac_mono : p` asserts `p` and uses it to discharge the goal result unwrapping a series of monotonic functions. Can be combined with * or ^k: `ac_mono* : p` In the case where `f` is an associative or commutative operator, `ac_mono` will consider any possible permutation of its arguments and use the one the minimizes the difference between the left-hand side and the right-hand side. To use it, first import `tactic.monotonicity`. `ac_mono` can be used as follows: ```lean example (x y z k m n : ℕ) (h₀ : z ≥ 0) (h₁ : x ≤ y) : (m + x + n) * z + k ≤ z * (y + n + m) + k := begin ac_mono, -- ⊢ (m + x + n) * z ≤ z * (y + n + m) ac_mono, -- ⊢ m + x + n ≤ y + n + m ac_mono, end ``` As with `mono*`, `ac_mono*` solves the goal in one go and so does `ac_mono* := h₁`. The latter syntax becomes especially interesting in the following example: ```lean example (x y z k m n : ℕ) (h₀ : z ≥ 0) (h₁ : m + x + n ≤ y + n + m) : (m + x + n) * z + k ≤ z * (y + n + m) + k := by ac_mono* := h₁. ``` By giving `ac_mono` the assumption `h₁`, we are asking `ac_refl` to stop earlier than it would normally would. -/ meta def ac_mono (rep : parse arity) : parse assert_or_rule? → opt_param mono_cfg { mono_cfg . } → tactic unit | none opt := focus1 $ repeat_or_not rep (ac_mono_aux opt) none | (some (inl h)) opt := do focus1 $ repeat_or_not rep (ac_mono_aux opt) (some $ done <|> to_expr h >>= ac_refine) | (some (inr t)) opt := do h ← i_to_expr t >>= assert `h, tactic.swap, focus1 $ repeat_or_not rep (ac_mono_aux opt) (some $ done <|> ac_refine h) /- TODO(Simon): with `ac_mono := h` and `ac_mono : p` split the remaining gaol if the provided rule does not solve it completely. -/ add_tactic_doc { name := "ac_mono", category := doc_category.tactic, decl_names := [`tactic.interactive.ac_mono], tags := ["monotonicity"] } attribute [mono] and.imp or.imp end tactic.interactive
a097db1bf5242fc2cb4d8fe41b54ff3c0dccdd84
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/sites/whiskering.lean
c437b9d5be03c7de1be9cb462ef5609f25cb755e
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
4,358
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 category_theory.sites.sheaf /-! > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we construct the functor `Sheaf J A ⥤ Sheaf J B` between sheaf categories obtained by composition with a functor `F : A ⥤ B`. In order for the sheaf condition to be preserved, `F` must preserve the correct limits. The lemma `presheaf.is_sheaf.comp` says that composition with such an `F` indeed preserves the sheaf condition. The functor between sheaf categories is called `Sheaf_compose J F`. Given a natural transformation `η : F ⟶ G`, we obtain a natural transformation `Sheaf_compose J F ⟶ Sheaf_compose J G`, which we call `Sheaf_compose_map J η`. -/ namespace category_theory open category_theory.limits universes v₁ v₂ u₁ u₂ u₃ variables {C : Type u₁} [category.{v₁} C] variables {A : Type u₂} [category.{max v₁ u₁} A] variables {B : Type u₃} [category.{max v₁ u₁} B] variables {J : grothendieck_topology C} variables {U : C} (R : presieve U) variables (F : A ⥤ B) namespace grothendieck_topology.cover variables (P : Cᵒᵖ ⥤ A) {X : C} (S : J.cover X) /-- The multicospan associated to a cover `S : J.cover X` and a presheaf of the form `P ⋙ F` is isomorphic to the composition of the multicospan associated to `S` and `P`, composed with `F`. -/ def multicospan_comp : (S.index (P ⋙ F)).multicospan ≅ (S.index P).multicospan ⋙ F := nat_iso.of_components (λ t, match t with | walking_multicospan.left a := eq_to_iso rfl | walking_multicospan.right b := eq_to_iso rfl end) begin rintros (a|b) (a|b) (f|f|f), any_goals { dsimp, erw [functor.map_id, functor.map_id, category.id_comp] }, any_goals { dsimp, erw [category.comp_id, category.id_comp], refl } end @[simp] lemma multicospan_comp_app_left (a) : (S.multicospan_comp F P).app (walking_multicospan.left a) = eq_to_iso rfl := rfl @[simp] lemma multicospan_comp_app_right (b) : (S.multicospan_comp F P).app (walking_multicospan.right b) = eq_to_iso rfl := rfl @[simp] lemma multicospan_comp_hom_app_left (a) : (S.multicospan_comp F P).hom.app (walking_multicospan.left a) = eq_to_hom rfl := rfl @[simp] lemma multicospan_comp_hom_app_right (b) : (S.multicospan_comp F P).hom.app (walking_multicospan.right b) = eq_to_hom rfl := rfl @[simp] lemma multicospan_comp_hom_inv_left (P : Cᵒᵖ ⥤ A) {X : C} (S : J.cover X) (a) : (S.multicospan_comp F P).inv.app (walking_multicospan.left a) = eq_to_hom rfl := rfl @[simp] lemma multicospan_comp_hom_inv_right (P : Cᵒᵖ ⥤ A) {X : C} (S : J.cover X) (b) : (S.multicospan_comp F P).inv.app (walking_multicospan.right b) = eq_to_hom rfl := rfl /-- Mapping the multifork associated to a cover `S : J.cover X` and a presheaf `P` with respect to a functor `F` is isomorphic (upto a natural isomorphism of the underlying functors) to the multifork associated to `S` and `P ⋙ F`. -/ def map_multifork : F.map_cone (S.multifork P) ≅ (limits.cones.postcompose (S.multicospan_comp F P).hom).obj (S.multifork (P ⋙ F)) := cones.ext (eq_to_iso rfl) begin rintros (a|b), { dsimp, simpa }, { dsimp, simp, dsimp [multifork.of_ι], simpa } end end grothendieck_topology.cover variables [∀ (X : C) (S : J.cover X) (P : Cᵒᵖ ⥤ A), preserves_limit (S.index P).multicospan F] lemma presheaf.is_sheaf.comp {P : Cᵒᵖ ⥤ A} (hP : presheaf.is_sheaf J P) : presheaf.is_sheaf J (P ⋙ F) := begin rw presheaf.is_sheaf_iff_multifork at ⊢ hP, intros X S, obtain ⟨h⟩ := hP X S, replace h := is_limit_of_preserves F h, replace h := limits.is_limit.of_iso_limit h (S.map_multifork F P), exact ⟨limits.is_limit.postcompose_hom_equiv (S.multicospan_comp F P) _ h⟩, end variable (J) /-- Composing a sheaf with a functor preserving the appropriate limits yields a functor between sheaf categories. -/ @[simps] def Sheaf_compose : Sheaf J A ⥤ Sheaf J B := { obj := λ G, ⟨G.val ⋙ F, presheaf.is_sheaf.comp _ G.2⟩, map := λ G H η, ⟨whisker_right η.val _⟩, map_id' := λ G, Sheaf.hom.ext _ _ $ whisker_right_id _, map_comp' := λ G H W f g, Sheaf.hom.ext _ _ $ whisker_right_comp _ _ _ } end category_theory
8ee149c125f092c46064e8cf04e791bdae7c881c
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/analysis/asymptotic_equivalent.lean
6bb449a935368670fc2e2d3d9baa83103cb83795
[ "Apache-2.0" ]
permissive
hamdysalah1/mathlib
b915f86b2503feeae268de369f1b16932321f097
95454452f6b3569bf967d35aab8d852b1ddf8017
refs/heads/master
1,677,154,116,545
1,611,797,994,000
1,611,797,994,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,253
lean
/- Copyright (c) 2020 Anatole Dedecker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anatole Dedecker -/ import analysis.asymptotics import analysis.normed_space.ordered import analysis.normed_space.bounded_linear_maps /-! # Asymptotic equivalence In this file, we define the relation `is_equivalent u v l`, which means that `u-v` is little o of `v` along the filter `l`. Unlike `is_[oO]` relations, this one requires `u` and `v` to have the same codomaine `β`. While the definition only requires `β` to be a `normed_group`, most interesting properties require it to be a `normed_field`. ## Notations We introduce the notation `u ~[l] v := is_equivalent u v l`, which you can use by opening the `asymptotics` locale. ## Main results If `β` is a `normed_group` : - `_ ~[l] _` is an equivalence relation - Equivalent statements for `u ~[l] const _ c` : - If `c ≠ 0`, this is true iff `tendsto u l (𝓝 c)` (see `is_equivalent_const_iff_tendsto`) - For `c = 0`, this is true iff `u =ᶠ[l] 0` (see `is_equivalent_zero_iff_eventually_zero`) If `β` is a `normed_field` : - Alternative characterization of the relation (see `is_equivalent_iff_exists_eq_mul`) : `u ~[l] v ↔ ∃ (φ : α → β) (hφ : tendsto φ l (𝓝 1)), u =ᶠ[l] φ * v` - Provided some non-vanishing hypothesis, this can be seen as `u ~[l] v ↔ tendsto (u/v) l (𝓝 1)` (see `is_equivalent_iff_tendsto_one`) - For any constant `c`, `u ~[l] v` implies `tendsto u l (𝓝 c) ↔ tendsto v l (𝓝 c)` (see `is_equivalent.tendsto_nhds_iff`) - `*` and `/` are compatible with `_ ~[l] _` (see `is_equivalent.mul` and `is_equivalent.div`) If `β` is a `normed_linear_ordered_field` : - If `u ~[l] v`, we have `tendsto u l at_top ↔ tendsto v l at_top` (see `is_equivalent.tendsto_at_top_iff`) -/ namespace asymptotics open filter function open_locale topological_space section normed_group variables {α β : Type*} [normed_group β] /-- Two functions `u` and `v` are said to be asymptotically equivalent along a filter `l` when `u x - v x = o(v x)` as x converges along `l`. -/ def is_equivalent (u v : α → β) (l : filter α) := is_o (u - v) v l localized "notation u ` ~[`:50 l:50 `] `:0 v:50 := asymptotics.is_equivalent u v l" in asymptotics variables {u v w : α → β} {l : filter α} lemma is_equivalent.is_o (h : u ~[l] v) : is_o (u - v) v l := h lemma is_equivalent.is_O (h : u ~[l] v) : is_O u v l := (is_O.congr_of_sub h.is_O.symm).mp (is_O_refl _ _) lemma is_equivalent.is_O_symm (h : u ~[l] v) : is_O v u l := begin convert h.is_o.right_is_O_add, ext, simp end @[refl] lemma is_equivalent.refl : u ~[l] u := begin rw [is_equivalent, sub_self], exact is_o_zero _ _ end @[symm] lemma is_equivalent.symm (h : u ~[l] v) : v ~[l] u := (h.is_o.trans_is_O h.is_O_symm).symm @[trans] lemma is_equivalent.trans (huv : u ~[l] v) (hvw : v ~[l] w) : u ~[l] w := (huv.is_o.trans_is_O hvw.is_O).triangle hvw.is_o lemma is_equivalent_zero_iff_eventually_zero : u ~[l] 0 ↔ u =ᶠ[l] 0 := begin rw [is_equivalent, sub_zero], exact is_o_zero_right_iff end lemma is_equivalent_const_iff_tendsto {c : β} (h : c ≠ 0) : u ~[l] const _ c ↔ tendsto u l (𝓝 c) := begin rw [is_equivalent, is_o_const_iff h], split; intro h; [ { have := h.sub tendsto_const_nhds, rw zero_sub (-c) at this }, { have := h.sub tendsto_const_nhds, rw ← sub_self c} ]; convert this; try { ext }; simp end lemma is_equivalent.tendsto_const {c : β} (hu : u ~[l] const _ c) : tendsto u l (𝓝 c) := begin rcases (em $ c = 0) with ⟨rfl, h⟩, { exact (tendsto_congr' $ is_equivalent_zero_iff_eventually_zero.mp hu).mpr tendsto_const_nhds }, { exact (is_equivalent_const_iff_tendsto h).mp hu } end lemma is_equivalent.tendsto_nhds {c : β} (huv : u ~[l] v) (hu : tendsto u l (𝓝 c)) : tendsto v l (𝓝 c) := begin by_cases h : c = 0, { rw [h, ← is_o_one_iff ℝ] at *, convert (huv.symm.is_o.trans hu).add hu, simp }, { rw ← is_equivalent_const_iff_tendsto h at hu ⊢, exact huv.symm.trans hu } end lemma is_equivalent.tendsto_nhds_iff {c : β} (huv : u ~[l] v) : tendsto u l (𝓝 c) ↔ tendsto v l (𝓝 c) := ⟨huv.tendsto_nhds, huv.symm.tendsto_nhds⟩ end normed_group open_locale asymptotics section normed_field variables {α β : Type*} [normed_field β] {t u v w : α → β} {l : filter α} lemma is_equivalent_iff_exists_eq_mul : u ~[l] v ↔ ∃ (φ : α → β) (hφ : tendsto φ l (𝓝 1)), u =ᶠ[l] φ * v := begin rw [is_equivalent, is_o_iff_exists_eq_mul], split; rintros ⟨φ, hφ, h⟩; [use (φ + 1), use (φ - 1)]; split, { conv in (𝓝 _) { rw ← zero_add (1 : β) }, exact hφ.add (tendsto_const_nhds) }, { convert h.add (eventually_eq.refl l v); ext; simp [add_mul] }, { conv in (𝓝 _) { rw ← sub_self (1 : β) }, exact hφ.sub (tendsto_const_nhds) }, { convert h.sub (eventually_eq.refl l v); ext; simp [sub_mul] } end lemma is_equivalent.exists_eq_mul (huv : u ~[l] v) : ∃ (φ : α → β) (hφ : tendsto φ l (𝓝 1)), u =ᶠ[l] φ * v := is_equivalent_iff_exists_eq_mul.mp huv lemma is_equivalent_of_tendsto_one (hz : ∀ᶠ x in l, v x = 0 → u x = 0) (huv : tendsto (u/v) l (𝓝 1)) : u ~[l] v := begin rw is_equivalent_iff_exists_eq_mul, refine ⟨u/v, huv, hz.mono $ λ x hz', (div_mul_cancel_of_imp hz').symm⟩, end lemma is_equivalent_of_tendsto_one' (hz : ∀ x, v x = 0 → u x = 0) (huv : tendsto (u/v) l (𝓝 1)) : u ~[l] v := is_equivalent_of_tendsto_one (eventually_of_forall hz) huv lemma is_equivalent_iff_tendsto_one (hz : ∀ᶠ x in l, v x ≠ 0) : u ~[l] v ↔ tendsto (u/v) l (𝓝 1) := begin split, { intro hequiv, have := hequiv.is_o.tendsto_0, simp only [pi.sub_apply, sub_div] at this, have key : tendsto (λ x, v x / v x) l (𝓝 1), { exact (tendsto_congr' $ hz.mono $ λ x hnz, @div_self _ _ (v x) hnz).mpr tendsto_const_nhds }, convert this.add key, { ext, simp }, { norm_num } }, { exact is_equivalent_of_tendsto_one (hz.mono $ λ x hnvz hz, (hnvz hz).elim) } end end normed_field section smul lemma is_equivalent.smul {α E 𝕜 : Type*} [normed_field 𝕜] [normed_group E] [normed_space 𝕜 E] {a b : α → 𝕜} {u v : α → E} {l : filter α} (hab : a ~[l] b) (huv : u ~[l] v) : (λ x, a x • u x) ~[l] (λ x, b x • v x) := begin rcases hab.exists_eq_mul with ⟨φ, hφ, habφ⟩, have : (λ (x : α), a x • u x) - (λ (x : α), b x • v x) =ᶠ[l] λ x, b x • ((φ x • u x) - v x), { convert (habφ.comp₂ (•) $ eventually_eq.refl _ u).sub (eventually_eq.refl _ (λ x, b x • v x)), ext, rw [pi.mul_apply, mul_comm, mul_smul, ← smul_sub] }, refine (is_o_congr this.symm $ eventually_eq.rfl).mp ((is_O_refl b l).smul_is_o _), rcases huv.is_O.exists_pos with ⟨C, hC, hCuv⟩, rw is_equivalent at *, rw is_o_iff at *, rw is_O_with at hCuv, simp only [metric.tendsto_nhds, dist_eq_norm] at hφ, intros c hc, specialize hφ ((c/2)/C) (div_pos (by linarith) hC), specialize huv (show 0 < c/2, by linarith), refine hφ.mp (huv.mp $ hCuv.mono $ λ x hCuvx huvx hφx, _), have key := calc ∥φ x - 1∥ * ∥u x∥ ≤ (c/2) / C * ∥u x∥ : mul_le_mul_of_nonneg_right hφx.le (norm_nonneg $ u x) ... ≤ (c/2) / C * (C*∥v x∥) : mul_le_mul_of_nonneg_left hCuvx (div_pos (by linarith) hC).le ... = c/2 * ∥v x∥ : by {field_simp [hC.ne.symm], ring}, calc ∥((λ (x : α), φ x • u x) - v) x∥ = ∥(φ x - 1) • u x + (u x - v x)∥ : by simp [sub_smul, sub_add] ... ≤ ∥(φ x - 1) • u x∥ + ∥u x - v x∥ : norm_add_le _ _ ... = ∥φ x - 1∥ * ∥u x∥ + ∥u x - v x∥ : by rw norm_smul ... ≤ c / 2 * ∥v x∥ + ∥u x - v x∥ : add_le_add_right key _ ... ≤ c / 2 * ∥v x∥ + c / 2 * ∥v x∥ : add_le_add_left huvx _ ... = c * ∥v x∥ : by ring, end end smul section mul_inv variables {α β : Type*} [normed_field β] {t u v w : α → β} {l : filter α} lemma is_equivalent.mul (htu : t ~[l] u) (hvw : v ~[l] w) : t * v ~[l] u * w := htu.smul hvw lemma is_equivalent.inv (huv : u ~[l] v) : (λ x, (u x)⁻¹) ~[l] (λ x, (v x)⁻¹) := begin rw is_equivalent_iff_exists_eq_mul at *, rcases huv with ⟨φ, hφ, h⟩, rw ← inv_one, refine ⟨λ x, (φ x)⁻¹, tendsto.inv' hφ (by norm_num) , _⟩, convert h.inv, ext, simp [mul_inv'] end lemma is_equivalent.div (htu : t ~[l] u) (hvw : v ~[l] w) : (λ x, t x / v x) ~[l] (λ x, u x / w x) := htu.mul hvw.inv end mul_inv section normed_linear_ordered_field variables {α β : Type*} [normed_linear_ordered_field β] {u v : α → β} {l : filter α} lemma is_equivalent.tendsto_at_top [order_topology β] (huv : u ~[l] v) (hu : tendsto u l at_top) : tendsto v l at_top := let ⟨φ, hφ, h⟩ := huv.symm.exists_eq_mul in tendsto.congr' h.symm ((mul_comm u φ) ▸ (hu.at_top_mul zero_lt_one hφ)) lemma is_equivalent.tendsto_at_top_iff [order_topology β] (huv : u ~[l] v) : tendsto u l at_top ↔ tendsto v l at_top := ⟨huv.tendsto_at_top, huv.symm.tendsto_at_top⟩ end normed_linear_ordered_field end asymptotics
29cda2382b3321d21d4b6a95a687ceeaf2a411e5
3dd1b66af77106badae6edb1c4dea91a146ead30
/library/hott/inhabited.lean
cb609329b1943c0e58c3a1d84613a50ee742db62
[ "Apache-2.0" ]
permissive
silky/lean
79c20c15c93feef47bb659a2cc139b26f3614642
df8b88dca2f8da1a422cb618cd476ef5be730546
refs/heads/master
1,610,737,587,697
1,406,574,534,000
1,406,574,534,000
22,362,176
1
0
null
null
null
null
UTF-8
Lean
false
false
1,317
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 bool using logic inductive inhabited (A : Type) : Type := | inhabited_intro : A → inhabited A theorem inhabited_elim {A : Type} {B : Type} (H1 : inhabited A) (H2 : A → B) : B := inhabited_rec H2 H1 theorem inhabited_fun [instance] (A : Type) {B : Type} (H : inhabited B) : inhabited (A → B) := inhabited_elim H (take (b : B), inhabited_intro (λ a : A, b)) theorem inhabited_sum_left [instance] {A : Type} (B : Type) (H : inhabited A) : inhabited (A + B) := inhabited_elim H (λ a, inhabited_intro (inl B a)) theorem inhabited_sum_right [instance] (A : Type) {B : Type} (H : inhabited B) : inhabited (A + B) := inhabited_elim H (λ b, inhabited_intro (inr A b)) theorem inhabited_product [instance] {A : Type} {B : Type} (Ha : inhabited A) (Hb : inhabited B) : inhabited (A × B) := inhabited_elim Ha (λ a, (inhabited_elim Hb (λ b, inhabited_intro (a, b)))) theorem inhabited_bool [instance] : inhabited bool := inhabited_intro true theorem inhabited_unit [instance] : inhabited unit := inhabited_intro ⋆ theorem inhabited_sigma_pr1 {A : Type} {B : A → Type} (p : Σ x, B x) : inhabited A := inhabited_intro (dpr1 p)
8e5b11f677b743d4bfa3fe425e34a0395405df4d
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/category_theory/closed/ideal.lean
c759c15153fddfa7e82a07cac66a42b2ae582480
[ "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,837
lean
/- Copyright (c) 2021 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.limits.preserves.shapes.binary_products import category_theory.limits.constructions.finite_products_of_binary_products import category_theory.monad.limits import category_theory.adjunction.fully_faithful import category_theory.adjunction.reflective import category_theory.closed.cartesian import category_theory.subterminal /-! # Exponential ideals An exponential ideal of a cartesian closed category `C` is a subcategory `D ⊆ C` such that for any `B : D` and `A : C`, the exponential `A ⟹ B` is in `D`: resembling ring theoretic ideals. We define the notion here for inclusion functors `i : D ⥤ C` rather than explicit subcategories to preserve the principle of equivalence. We additionally show that if `C` is cartesian closed and `i : D ⥤ C` is a reflective functor, the following are equivalent. * The left adjoint to `i` preserves binary (equivalently, finite) products. * `i` is an exponential ideal. -/ universes v₁ v₂ u₁ u₂ noncomputable theory namespace category_theory open limits category section ideal variables {C : Type u₁} {D : Type u₂} [category.{v₁} C] [category.{v₁} D] {i : D ⥤ C} variables (i) [has_finite_products C] [cartesian_closed C] /-- The subcategory `D` of `C` expressed as an inclusion functor is an *exponential ideal* if `B ∈ D` implies `A ⟹ B ∈ D` for all `A`. -/ class exponential_ideal : Prop := (exp_closed : ∀ {B}, B ∈ i.ess_image → ∀ A, (A ⟹ B) ∈ i.ess_image) /-- To show `i` is an exponential ideal it suffices to show that `A ⟹ iB` is "in" `D` for any `A` in `C` and `B` in `D`. -/ lemma exponential_ideal.mk' (h : ∀ (B : D) (A : C), (A ⟹ i.obj B) ∈ i.ess_image) : exponential_ideal i := ⟨λ B hB A, begin rcases hB with ⟨B', ⟨iB'⟩⟩, exact functor.ess_image.of_iso ((exp A).map_iso iB') (h B' A), end⟩ /-- The entire category viewed as a subcategory is an exponential ideal. -/ instance : exponential_ideal (𝟭 C) := exponential_ideal.mk' _ (λ B A, ⟨_, ⟨iso.refl _⟩⟩) open cartesian_closed /-- The subcategory of subterminal objects is an exponential ideal. -/ instance : exponential_ideal (subterminal_inclusion C) := begin apply exponential_ideal.mk', intros B A, refine ⟨⟨A ⟹ B.1, λ Z g h, _⟩, ⟨iso.refl _⟩⟩, exact uncurry_injective (B.2 (cartesian_closed.uncurry g) (cartesian_closed.uncurry h)) end /-- If `D` is a reflective subcategory, the property of being an exponential ideal is equivalent to the presence of a natural isomorphism `i ⋙ exp A ⋙ left_adjoint i ⋙ i ≅ i ⋙ exp A`, that is: `(A ⟹ iB) ≅ i L (A ⟹ iB)`, naturally in `B`. The converse is given in `exponential_ideal.mk_of_iso`. -/ def exponential_ideal_reflective (A : C) [reflective i] [exponential_ideal i] : i ⋙ exp A ⋙ left_adjoint i ⋙ i ≅ i ⋙ exp A := begin symmetry, apply nat_iso.of_components _ _, { intro X, haveI := (exponential_ideal.exp_closed (i.obj_mem_ess_image X) A).unit_is_iso, apply as_iso ((adjunction.of_right_adjoint i).unit.app (A ⟹ i.obj X)) }, { simp } end /-- Given a natural isomorphism `i ⋙ exp A ⋙ left_adjoint i ⋙ i ≅ i ⋙ exp A`, we can show `i` is an exponential ideal. -/ lemma exponential_ideal.mk_of_iso [reflective i] (h : Π (A : C), i ⋙ exp A ⋙ left_adjoint i ⋙ i ≅ i ⋙ exp A) : exponential_ideal i := begin apply exponential_ideal.mk', intros B A, exact ⟨_, ⟨(h A).app B⟩⟩, end end ideal section variables {C : Type u₁} {D : Type u₂} [category.{v₁} C] [category.{v₁} D] variables (i : D ⥤ C) lemma reflective_products [has_finite_products C] [reflective i] : has_finite_products D := ⟨λ J 𝒥₁ 𝒥₂, by exactI has_limits_of_shape_of_reflective i⟩ local attribute [instance, priority 10] reflective_products open cartesian_closed variables [has_finite_products C] [reflective i] [cartesian_closed C] /-- If the reflector preserves binary products, the subcategory is an exponential ideal. This is the converse of `preserves_binary_products_of_exponential_ideal`. -/ @[priority 10] instance exponential_ideal_of_preserves_binary_products [preserves_limits_of_shape (discrete.{v₁} walking_pair) (left_adjoint i)] : exponential_ideal i := begin let ir := adjunction.of_right_adjoint i, let L : C ⥤ D := left_adjoint i, let η : 𝟭 C ⟶ L ⋙ i := ir.unit, let ε : i ⋙ L ⟶ 𝟭 D := ir.counit, apply exponential_ideal.mk', intros B A, let q : i.obj (L.obj (A ⟹ i.obj B)) ⟶ A ⟹ i.obj B, apply cartesian_closed.curry (ir.hom_equiv _ _ _), apply _ ≫ (ir.hom_equiv _ _).symm ((ev A).app (i.obj B)), refine prod_comparison L A _ ≫ limits.prod.map (𝟙 _) (ε.app _) ≫ inv (prod_comparison _ _ _), have : η.app (A ⟹ i.obj B) ≫ q = 𝟙 (A ⟹ i.obj B), { dsimp, rw [← curry_natural_left, curry_eq_iff, uncurry_id_eq_ev, ← ir.hom_equiv_naturality_left, ir.hom_equiv_apply_eq, assoc, assoc, prod_comparison_natural_assoc, L.map_id, ← prod.map_id_comp_assoc, ir.left_triangle_components, prod.map_id_id, id_comp], apply is_iso.hom_inv_id_assoc }, haveI : split_mono (η.app (A ⟹ i.obj B)) := ⟨_, this⟩, apply mem_ess_image_of_unit_split_mono, end variables [exponential_ideal i] /-- If `i` witnesses that `D` is a reflective subcategory and an exponential ideal, then `D` is itself cartesian closed. -/ def cartesian_closed_of_reflective : cartesian_closed D := { closed := λ B, { is_adj := { right := i ⋙ exp (i.obj B) ⋙ left_adjoint i, adj := begin apply adjunction.restrict_fully_faithful i i (exp.adjunction (i.obj B)), { symmetry, apply nat_iso.of_components _ _, { intro X, haveI := adjunction.right_adjoint_preserves_limits.{v₁ v₁} (adjunction.of_right_adjoint i), apply as_iso (prod_comparison i B X) }, { intros X Y f, dsimp, rw prod_comparison_natural, simp, } }, { apply (exponential_ideal_reflective i _).symm } end } } } -- It's annoying that I need to do this. local attribute [-instance] category_theory.preserves_limit_of_creates_limit_and_has_limit category_theory.preserves_limit_of_shape_of_creates_limits_of_shape_and_has_limits_of_shape /-- We construct a bijection between morphisms `L(A ⨯ B) ⟶ X` and morphisms `LA ⨯ LB ⟶ X`. This bijection has two key properties: * It is natural in `X`: See `bijection_natural`. * When `X = LA ⨯ LB`, then the backwards direction sends the identity morphism to the product comparison morphism: See `bijection_symm_apply_id`. Together these help show that `L` preserves binary products. This should be considered *internal implementation* towards `preserves_binary_products_of_exponential_ideal`. -/ noncomputable def bijection (A B : C) (X : D) : ((left_adjoint i).obj (A ⨯ B) ⟶ X) ≃ ((left_adjoint i).obj A ⨯ (left_adjoint i).obj B ⟶ X) := calc _ ≃ (A ⨯ B ⟶ i.obj X) : (adjunction.of_right_adjoint i).hom_equiv _ _ ... ≃ (B ⨯ A ⟶ i.obj X) : (limits.prod.braiding _ _).hom_congr (iso.refl _) ... ≃ (A ⟶ B ⟹ i.obj X) : (exp.adjunction _).hom_equiv _ _ ... ≃ (i.obj ((left_adjoint i).obj A) ⟶ B ⟹ i.obj X) : unit_comp_partial_bijective _ (exponential_ideal.exp_closed (i.obj_mem_ess_image _) _) ... ≃ (B ⨯ i.obj ((left_adjoint i).obj A) ⟶ i.obj X) : ((exp.adjunction _).hom_equiv _ _).symm ... ≃ (i.obj ((left_adjoint i).obj A) ⨯ B ⟶ i.obj X) : (limits.prod.braiding _ _).hom_congr (iso.refl _) ... ≃ (B ⟶ i.obj ((left_adjoint i).obj A) ⟹ i.obj X) : (exp.adjunction _).hom_equiv _ _ ... ≃ (i.obj ((left_adjoint i).obj B) ⟶ i.obj ((left_adjoint i).obj A) ⟹ i.obj X) : unit_comp_partial_bijective _ (exponential_ideal.exp_closed (i.obj_mem_ess_image _) _) ... ≃ (i.obj ((left_adjoint i).obj A) ⨯ i.obj ((left_adjoint i).obj B) ⟶ i.obj X) : ((exp.adjunction _).hom_equiv _ _).symm ... ≃ (i.obj ((left_adjoint i).obj A ⨯ (left_adjoint i).obj B) ⟶ i.obj X) : begin apply iso.hom_congr _ (iso.refl _), haveI : preserves_limits i := (adjunction.of_right_adjoint i).right_adjoint_preserves_limits, exact (preserves_limit_pair.iso _ _ _).symm, end ... ≃ ((left_adjoint i).obj A ⨯ (left_adjoint i).obj B ⟶ X) : (equiv_of_fully_faithful _).symm lemma bijection_symm_apply_id (A B : C) : (bijection i A B _).symm (𝟙 _) = prod_comparison _ _ _ := begin dsimp [bijection], rw [comp_id, comp_id, comp_id, i.map_id, comp_id, unit_comp_partial_bijective_symm_apply, unit_comp_partial_bijective_symm_apply, uncurry_natural_left, uncurry_curry, uncurry_natural_left, uncurry_curry, prod.lift_map_assoc, comp_id, prod.lift_map_assoc, comp_id, prod.comp_lift_assoc, prod.lift_snd, prod.lift_fst_assoc, prod.lift_fst_comp_snd_comp, ←adjunction.eq_hom_equiv_apply, adjunction.hom_equiv_unit, iso.comp_inv_eq, assoc, preserves_limit_pair.iso_hom], apply prod.hom_ext, { rw [limits.prod.map_fst, assoc, assoc, prod_comparison_fst, ←i.map_comp, prod_comparison_fst], apply (adjunction.of_right_adjoint i).unit.naturality }, { rw [limits.prod.map_snd, assoc, assoc, prod_comparison_snd, ←i.map_comp, prod_comparison_snd], apply (adjunction.of_right_adjoint i).unit.naturality }, end lemma bijection_natural (A B : C) (X X' : D) (f : ((left_adjoint i).obj (A ⨯ B) ⟶ X)) (g : X ⟶ X') : bijection i _ _ _ (f ≫ g) = bijection i _ _ _ f ≫ g := begin dsimp [bijection], apply i.map_injective, rw [i.image_preimage, i.map_comp, i.image_preimage, comp_id, comp_id, comp_id, comp_id, comp_id, comp_id, adjunction.hom_equiv_naturality_right, ← assoc, curry_natural_right _ (i.map g), unit_comp_partial_bijective_natural, uncurry_natural_right, ← assoc, curry_natural_right, unit_comp_partial_bijective_natural, uncurry_natural_right, assoc], end /-- The bijection allows us to show that `prod_comparison L A B` is an isomorphism, where the inverse is the forward map of the identity morphism. -/ lemma prod_comparison_iso (A B : C) : is_iso (prod_comparison (left_adjoint i) A B) := ⟨⟨bijection i _ _ _ (𝟙 _), by rw [←(bijection i _ _ _).injective.eq_iff, bijection_natural, ← bijection_symm_apply_id, equiv.apply_symm_apply, id_comp], by rw [←bijection_natural, id_comp, ←bijection_symm_apply_id, equiv.apply_symm_apply]⟩⟩ local attribute [instance] prod_comparison_iso /-- If a reflective subcategory is an exponential ideal, then the reflector preserves binary products. This is the converse of `exponential_ideal_of_preserves_binary_products`. -/ noncomputable def preserves_binary_products_of_exponential_ideal : preserves_limits_of_shape (discrete walking_pair) (left_adjoint i) := { preserves_limit := λ K, begin apply limits.preserves_limit_of_iso_diagram _ (diagram_iso_pair K).symm, apply preserves_limit_pair.of_iso_prod_comparison, end } /-- If a reflective subcategory is an exponential ideal, then the reflector preserves finite products. -/ noncomputable def preserves_finite_products_of_exponential_ideal (J : Type*) [fintype J] : preserves_limits_of_shape (discrete J) (left_adjoint i) := begin letI := preserves_binary_products_of_exponential_ideal i, letI := left_adjoint_preserves_terminal_of_reflective.{v₁} i, apply preserves_finite_products_of_preserves_binary_and_terminal (left_adjoint i) J, end end end category_theory
3ab835bd218aa13b1a77161cb9ab56a07f513e8a
b70031c8e2c5337b91d7e70f1e0c5f528f7b0e77
/src/ring_theory/noetherian.lean
5872d0a83528dac5afb94e6b28b8e9f187bc9fe1
[ "Apache-2.0" ]
permissive
molodiuc/mathlib
cae2ba3ef1601c1f42ca0b625c79b061b63fef5b
98ebe5a6739fbe254f9ee9d401882d4388f91035
refs/heads/master
1,674,237,127,059
1,606,353,533,000
1,606,353,533,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
27,750
lean
/- Copyright (c) 2018 Mario Carneiro and Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kevin Buzzard -/ import algebraic_geometry.prime_spectrum import data.multiset.finset_ops import linear_algebra.linear_independent import order.order_iso_nat import ring_theory.ideal.operations /-! # Noetherian rings and modules The following are equivalent for a module M over a ring R: 1. Every increasing chain of submodule M₁ ⊆ M₂ ⊆ M₃ ⊆ ⋯ eventually stabilises. 2. Every submodule is finitely generated. A module satisfying these equivalent conditions is said to be a *Noetherian* R-module. A ring is a *Noetherian ring* if it is Noetherian as a module over itself. ## Main definitions Let `R` be a ring and let `M` and `P` be `R`-modules. Let `N` be an `R`-submodule of `M`. * `fg N : Prop` is the assertion that `N` is finitely generated as an `R`-module. * `is_noetherian R M` is the proposition that `M` is a Noetherian `R`-module. It is a class, implemented as the predicate that all `R`-submodules of `M` are finitely generated. ## Main statements * `exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul` is Nakayama's lemma, in the following form: if N is a finitely generated submodule of an ambient R-module M and I is an ideal of R such that N ⊆ IN, then there exists r ∈ 1 + I such that rN = 0. * `is_noetherian_iff_well_founded` is the theorem that an R-module M is Noetherian iff `>` is well-founded on `submodule R M`. Note that the Hilbert basis theorem, that if a commutative ring R is Noetherian then so is R[X], is proved in `ring_theory.polynomial`. ## References * [M. F. Atiyah and I. G. Macdonald, *Introduction to commutative algebra*][atiyah-macdonald] * [samuel] ## Tags Noetherian, noetherian, Noetherian ring, Noetherian module, noetherian ring, noetherian module -/ open set open_locale big_operators namespace submodule variables {R : Type*} {M : Type*} [semiring R] [add_comm_monoid M] [semimodule R M] /-- A submodule of `M` is finitely generated if it is the span of a finite subset of `M`. -/ def fg (N : submodule R M) : Prop := ∃ S : finset M, submodule.span R ↑S = N theorem fg_def {N : submodule R M} : N.fg ↔ ∃ S : set M, finite S ∧ span R S = N := ⟨λ ⟨t, h⟩, ⟨_, finset.finite_to_set t, h⟩, begin rintro ⟨t', h, rfl⟩, rcases finite.exists_finset_coe h with ⟨t, rfl⟩, exact ⟨t, rfl⟩ end⟩ /-- Nakayama's Lemma. Atiyah-Macdonald 2.5, Eisenbud 4.7, Matsumura 2.2, Stacks 00DV -/ theorem exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul {R : Type*} [comm_ring R] {M : Type*} [add_comm_group M] [module R M] (I : ideal R) (N : submodule R M) (hn : N.fg) (hin : N ≤ I • N) : ∃ r : R, r - 1 ∈ I ∧ ∀ n ∈ N, r • n = (0 : M) := begin rw fg_def at hn, rcases hn with ⟨s, hfs, hs⟩, have : ∃ r : R, r - 1 ∈ I ∧ N ≤ (I • span R s).comap (linear_map.lsmul R M r) ∧ s ⊆ N, { refine ⟨1, _, _, _⟩, { rw sub_self, exact I.zero_mem }, { rw [hs], intros n hn, rw [mem_comap], change (1:R) • n ∈ I • N, rw one_smul, exact hin hn }, { rw [← span_le, hs], exact le_refl N } }, clear hin hs, revert this, refine set.finite.dinduction_on hfs (λ H, _) (λ i s his hfs ih H, _), { rcases H with ⟨r, hr1, hrn, hs⟩, refine ⟨r, hr1, λ n hn, _⟩, specialize hrn hn, rwa [mem_comap, span_empty, smul_bot, mem_bot] at hrn }, apply ih, rcases H with ⟨r, hr1, hrn, hs⟩, rw [← set.singleton_union, span_union, smul_sup] at hrn, rw [set.insert_subset] at hs, have : ∃ c : R, c - 1 ∈ I ∧ c • i ∈ I • span R s, { specialize hrn hs.1, rw [mem_comap, mem_sup] at hrn, rcases hrn with ⟨y, hy, z, hz, hyz⟩, change y + z = r • i at hyz, rw mem_smul_span_singleton at hy, rcases hy with ⟨c, hci, rfl⟩, use r-c, split, { rw [sub_right_comm], exact I.sub_mem hr1 hci }, { rw [sub_smul, ← hyz, add_sub_cancel'], exact hz } }, rcases this with ⟨c, hc1, hci⟩, refine ⟨c * r, _, _, hs.2⟩, { rw [← ideal.quotient.eq, ring_hom.map_one] at hr1 hc1 ⊢, rw [ring_hom.map_mul, hc1, hr1, mul_one] }, { intros n hn, specialize hrn hn, rw [mem_comap, mem_sup] at hrn, rcases hrn with ⟨y, hy, z, hz, hyz⟩, change y + z = r • n at hyz, rw mem_smul_span_singleton at hy, rcases hy with ⟨d, hdi, rfl⟩, change _ • _ ∈ I • span R s, rw [mul_smul, ← hyz, smul_add, smul_smul, mul_comm, mul_smul], exact add_mem _ (smul_mem _ _ hci) (smul_mem _ _ hz) } end theorem fg_bot : (⊥ : submodule R M).fg := ⟨∅, by rw [finset.coe_empty, span_empty]⟩ theorem fg_sup {N₁ N₂ : submodule R M} (hN₁ : N₁.fg) (hN₂ : N₂.fg) : (N₁ ⊔ N₂).fg := let ⟨t₁, ht₁⟩ := fg_def.1 hN₁, ⟨t₂, ht₂⟩ := fg_def.1 hN₂ in fg_def.2 ⟨t₁ ∪ t₂, ht₁.1.union ht₂.1, by rw [span_union, ht₁.2, ht₂.2]⟩ variables {P : Type*} [add_comm_monoid P] [semimodule R P] variables {f : M →ₗ[R] P} theorem fg_map {N : submodule R M} (hs : N.fg) : (N.map f).fg := let ⟨t, ht⟩ := fg_def.1 hs in fg_def.2 ⟨f '' t, ht.1.image _, by rw [span_image, ht.2]⟩ lemma fg_of_fg_map {R M P : Type*} [ring R] [add_comm_group M] [module R M] [add_comm_group P] [module R P] (f : M →ₗ[R] P) (hf : f.ker = ⊥) {N : submodule R M} (hfn : (N.map f).fg) : N.fg := let ⟨t, ht⟩ := hfn in ⟨t.preimage f $ λ x _ y _ h, linear_map.ker_eq_bot.1 hf h, linear_map.map_injective hf $ by { rw [map_span, finset.coe_preimage, set.image_preimage_eq_inter_range, set.inter_eq_self_of_subset_left, ht], rw [← linear_map.range_coe, ← span_le, ht, ← map_top], exact map_mono le_top }⟩ lemma fg_top {R M : Type*} [ring R] [add_comm_group M] [module R M] (N : submodule R M) : (⊤ : submodule R N).fg ↔ N.fg := ⟨λ h, N.range_subtype ▸ map_top N.subtype ▸ fg_map h, λ h, fg_of_fg_map N.subtype N.ker_subtype $ by rwa [map_top, range_subtype]⟩ lemma fg_of_linear_equiv (e : M ≃ₗ[R] P) (h : (⊤ : submodule R P).fg) : (⊤ : submodule R M).fg := e.symm.range ▸ map_top (e.symm : P →ₗ[R] M) ▸ fg_map h theorem fg_prod {sb : submodule R M} {sc : submodule R P} (hsb : sb.fg) (hsc : sc.fg) : (sb.prod sc).fg := let ⟨tb, htb⟩ := fg_def.1 hsb, ⟨tc, htc⟩ := fg_def.1 hsc in fg_def.2 ⟨linear_map.inl R M P '' tb ∪ linear_map.inr R M P '' tc, (htb.1.image _).union (htc.1.image _), by rw [linear_map.span_inl_union_inr, htb.2, htc.2]⟩ /-- If 0 → M' → M → M'' → 0 is exact and M' and M'' are finitely generated then so is M. -/ theorem fg_of_fg_map_of_fg_inf_ker {R M P : Type*} [ring R] [add_comm_group M] [module R M] [add_comm_group P] [module R P] (f : M →ₗ[R] P) {s : submodule R M} (hs1 : (s.map f).fg) (hs2 : (s ⊓ f.ker).fg) : s.fg := begin haveI := classical.dec_eq R, haveI := classical.dec_eq M, haveI := classical.dec_eq P, cases hs1 with t1 ht1, cases hs2 with t2 ht2, have : ∀ y ∈ t1, ∃ x ∈ s, f x = y, { intros y hy, have : y ∈ map f s, { rw ← ht1, exact subset_span hy }, rcases mem_map.1 this with ⟨x, hx1, hx2⟩, exact ⟨x, hx1, hx2⟩ }, have : ∃ g : P → M, ∀ y ∈ t1, g y ∈ s ∧ f (g y) = y, { choose g hg1 hg2, existsi λ y, if H : y ∈ t1 then g y H else 0, intros y H, split, { simp only [dif_pos H], apply hg1 }, { simp only [dif_pos H], apply hg2 } }, cases this with g hg, clear this, existsi t1.image g ∪ t2, rw [finset.coe_union, span_union, finset.coe_image], apply le_antisymm, { refine sup_le (span_le.2 $ image_subset_iff.2 _) (span_le.2 _), { intros y hy, exact (hg y hy).1 }, { intros x hx, have := subset_span hx, rw ht2 at this, exact this.1 } }, intros x hx, have : f x ∈ map f s, { rw mem_map, exact ⟨x, hx, rfl⟩ }, rw [← ht1,← set.image_id ↑t1, finsupp.mem_span_iff_total] at this, rcases this with ⟨l, hl1, hl2⟩, refine mem_sup.2 ⟨(finsupp.total M M R id).to_fun ((finsupp.lmap_domain R R g : (P →₀ R) → M →₀ R) l), _, x - finsupp.total M M R id ((finsupp.lmap_domain R R g : (P →₀ R) → M →₀ R) l), _, add_sub_cancel'_right _ _⟩, { rw [← set.image_id (g '' ↑t1), finsupp.mem_span_iff_total], refine ⟨_, _, rfl⟩, haveI : inhabited P := ⟨0⟩, rw [← finsupp.lmap_domain_supported _ _ g, mem_map], refine ⟨l, hl1, _⟩, refl, }, rw [ht2, mem_inf], split, { apply s.sub_mem hx, rw [finsupp.total_apply, finsupp.lmap_domain_apply, finsupp.sum_map_domain_index], refine s.sum_mem _, { intros y hy, exact s.smul_mem _ (hg y (hl1 hy)).1 }, { exact zero_smul _ }, { exact λ _ _ _, add_smul _ _ _ } }, { rw [linear_map.mem_ker, f.map_sub, ← hl2], rw [finsupp.total_apply, finsupp.total_apply, finsupp.lmap_domain_apply], rw [finsupp.sum_map_domain_index, finsupp.sum, finsupp.sum, f.map_sum], rw sub_eq_zero, refine finset.sum_congr rfl (λ y hy, _), unfold id, rw [f.map_smul, (hg y (hl1 hy)).2], { exact zero_smul _ }, { exact λ _ _ _, add_smul _ _ _ } } end end submodule /-- `is_noetherian R M` is the proposition that `M` is a Noetherian `R`-module, implemented as the predicate that all `R`-submodules of `M` are finitely generated. -/ class is_noetherian (R M) [semiring R] [add_comm_monoid M] [semimodule R M] : Prop := (noetherian : ∀ (s : submodule R M), s.fg) section variables {R : Type*} {M : Type*} {P : Type*} variables [ring R] [add_comm_group M] [add_comm_group P] variables [module R M] [module R P] open is_noetherian include R theorem is_noetherian_submodule {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, s ≤ N → s.fg := ⟨λ ⟨hn⟩, λ s hs, have s ≤ N.subtype.range, from (N.range_subtype).symm ▸ hs, linear_map.map_comap_eq_self this ▸ submodule.fg_map (hn _), λ h, ⟨λ s, submodule.fg_of_fg_map_of_fg_inf_ker N.subtype (h _ $ submodule.map_subtype_le _ _) $ by rw [submodule.ker_subtype, inf_bot_eq]; exact submodule.fg_bot⟩⟩ theorem is_noetherian_submodule_left {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, (N ⊓ s).fg := is_noetherian_submodule.trans ⟨λ H s, H _ inf_le_left, λ H s hs, (inf_of_le_right hs) ▸ H _⟩ theorem is_noetherian_submodule_right {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, (s ⊓ N).fg := is_noetherian_submodule.trans ⟨λ H s, H _ inf_le_right, λ H s hs, (inf_of_le_left hs) ▸ H _⟩ instance is_noetherian_submodule' [is_noetherian R M] (N : submodule R M) : is_noetherian R N := is_noetherian_submodule.2 $ λ _ _, is_noetherian.noetherian _ variable (M) theorem is_noetherian_of_surjective (f : M →ₗ[R] P) (hf : f.range = ⊤) [is_noetherian R M] : is_noetherian R P := ⟨λ s, have (s.comap f).map f = s, from linear_map.map_comap_eq_self $ hf.symm ▸ le_top, this ▸ submodule.fg_map $ noetherian _⟩ variable {M} theorem is_noetherian_of_linear_equiv (f : M ≃ₗ[R] P) [is_noetherian R M] : is_noetherian R P := is_noetherian_of_surjective _ f.to_linear_map f.range lemma is_noetherian_of_injective [is_noetherian R P] (f : M →ₗ[R] P) (hf : f.ker = ⊥) : is_noetherian R M := is_noetherian_of_linear_equiv (linear_equiv.of_injective f hf).symm lemma fg_of_injective [is_noetherian R P] {N : submodule R M} (f : M →ₗ[R] P) (hf : f.ker = ⊥) : N.fg := @@is_noetherian.noetherian _ _ _ (is_noetherian_of_injective f hf) N instance is_noetherian_prod [is_noetherian R M] [is_noetherian R P] : is_noetherian R (M × P) := ⟨λ s, submodule.fg_of_fg_map_of_fg_inf_ker (linear_map.snd R M P) (noetherian _) $ have s ⊓ linear_map.ker (linear_map.snd R M P) ≤ linear_map.range (linear_map.inl R M P), from λ x ⟨hx1, hx2⟩, ⟨x.1, trivial, prod.ext rfl $ eq.symm $ linear_map.mem_ker.1 hx2⟩, linear_map.map_comap_eq_self this ▸ submodule.fg_map (noetherian _)⟩ instance is_noetherian_pi {R ι : Type*} {M : ι → Type*} [ring R] [Π i, add_comm_group (M i)] [Π i, module R (M i)] [fintype ι] [∀ i, is_noetherian R (M i)] : is_noetherian R (Π i, M i) := begin haveI := classical.dec_eq ι, suffices : ∀ s : finset ι, is_noetherian R (Π i : (↑s : set ι), M i), { letI := this finset.univ, refine @is_noetherian_of_linear_equiv _ _ _ _ _ _ _ _ ⟨_, _, _, _, _, _⟩ (this finset.univ), { exact λ f i, f ⟨i, finset.mem_univ _⟩ }, { intros, ext, refl }, { intros, ext, refl }, { exact λ f i, f i.1 }, { intro, ext ⟨⟩, refl }, { intro, ext i, refl } }, intro s, induction s using finset.induction with a s has ih, { split, intro s, convert submodule.fg_bot, apply eq_bot_iff.2, intros x hx, refine (submodule.mem_bot R).2 _, ext i, cases i.2 }, refine @is_noetherian_of_linear_equiv _ _ _ _ _ _ _ _ ⟨_, _, _, _, _, _⟩ (@is_noetherian_prod _ (M a) _ _ _ _ _ _ _ ih), { exact λ f i, or.by_cases (finset.mem_insert.1 i.2) (λ h : i.1 = a, show M i.1, from (eq.rec_on h.symm f.1)) (λ h : i.1 ∈ s, show M i.1, from f.2 ⟨i.1, h⟩) }, { intros f g, ext i, unfold or.by_cases, cases i with i hi, rcases finset.mem_insert.1 hi with rfl | h, { change _ = _ + _, simp only [dif_pos], refl }, { change _ = _ + _, have : ¬i = a, { rintro rfl, exact has h }, simp only [dif_neg this, dif_pos h], refl } }, { intros c f, ext i, unfold or.by_cases, cases i with i hi, rcases finset.mem_insert.1 hi with rfl | h, { change _ = c • _, simp only [dif_pos], refl }, { change _ = c • _, have : ¬i = a, { rintro rfl, exact has h }, simp only [dif_neg this, dif_pos h], refl } }, { exact λ f, (f ⟨a, finset.mem_insert_self _ _⟩, λ i, f ⟨i.1, finset.mem_insert_of_mem i.2⟩) }, { intro f, apply prod.ext, { simp only [or.by_cases, dif_pos] }, { ext ⟨i, his⟩, have : ¬i = a, { rintro rfl, exact has his }, dsimp only [or.by_cases], change i ∈ s at his, rw [dif_neg this, dif_pos his] } }, { intro f, ext ⟨i, hi⟩, rcases finset.mem_insert.1 hi with rfl | h, { simp only [or.by_cases, dif_pos], refl }, { have : ¬i = a, { rintro rfl, exact has h }, simp only [or.by_cases, dif_neg this, dif_pos h], refl } } end end open is_noetherian submodule function theorem is_noetherian_iff_well_founded {R M} [ring R] [add_comm_group M] [module R M] : is_noetherian R M ↔ well_founded ((>) : submodule R M → submodule R M → Prop) := ⟨λ h, begin apply rel_embedding.well_founded_iff_no_descending_seq.2, swap, { apply is_strict_order.swap }, rintro ⟨⟨N, hN⟩⟩, let Q := ⨆ n, N n, resetI, rcases submodule.fg_def.1 (noetherian Q) with ⟨t, h₁, h₂⟩, have hN' : ∀ {a b}, a ≤ b → N a ≤ N b := λ a b, (strict_mono.le_iff_le (λ _ _, hN.1)).2, have : t ⊆ ⋃ i, (N i : set M), { rw [← submodule.coe_supr_of_directed N _], { show t ⊆ Q, rw ← h₂, apply submodule.subset_span }, { exact λ i j, ⟨max i j, hN' (le_max_left _ _), hN' (le_max_right _ _)⟩ } }, simp [subset_def] at this, choose f hf using show ∀ x : t, ∃ (i : ℕ), x.1 ∈ N i, { simpa }, cases h₁ with h₁, let A := finset.sup (@finset.univ t h₁) f, have : Q ≤ N A, { rw ← h₂, apply submodule.span_le.2, exact λ x h, hN' (finset.le_sup (@finset.mem_univ t h₁ _)) (hf ⟨x, h⟩) }, exact not_le_of_lt (hN.1 (nat.lt_succ_self A)) (le_trans (le_supr _ _) this) end, begin assume h, split, assume N, suffices : ∀ P ≤ N, ∃ s, finite s ∧ P ⊔ submodule.span R s = N, { rcases this ⊥ bot_le with ⟨s, hs, e⟩, exact submodule.fg_def.2 ⟨s, hs, by simpa using e⟩ }, refine λ P, h.induction P _, intros P IH PN, letI := classical.dec, by_cases h : ∀ x, x ∈ N → x ∈ P, { cases le_antisymm PN h, exact ⟨∅, by simp⟩ }, { simp [not_forall] at h, rcases h with ⟨x, h, h₂⟩, have : ¬P ⊔ submodule.span R {x} ≤ P, { intro hn, apply h₂, have := le_trans le_sup_right hn, exact submodule.span_le.1 this (mem_singleton x) }, rcases IH (P ⊔ submodule.span R {x}) ⟨@le_sup_left _ _ P _, this⟩ (sup_le PN (submodule.span_le.2 (by simpa))) with ⟨s, hs, hs₂⟩, refine ⟨insert x s, hs.insert x, _⟩, rw [← hs₂, sup_assoc, ← submodule.span_union], simp } end⟩ lemma well_founded_submodule_gt (R M) [ring R] [add_comm_group M] [module R M] : ∀ [is_noetherian R M], well_founded ((>) : submodule R M → submodule R M → Prop) := is_noetherian_iff_well_founded.mp lemma finite_of_linear_independent {R M} [comm_ring R] [nontrivial R] [add_comm_group M] [module R M] [is_noetherian R M] {s : set M} (hs : linear_independent R (coe : s → M)) : s.finite := begin refine classical.by_contradiction (λ hf, rel_embedding.well_founded_iff_no_descending_seq.1 (well_founded_submodule_gt R M) ⟨_⟩), have f : ℕ ↪ s, from @infinite.nat_embedding s ⟨λ f, hf ⟨f⟩⟩, have : ∀ n, (coe ∘ f) '' {m | m ≤ n} ⊆ s, { rintros n x ⟨y, hy₁, hy₂⟩, subst hy₂, exact (f y).2 }, have : ∀ a b : ℕ, a ≤ b ↔ span R ((coe ∘ f) '' {m | m ≤ a}) ≤ span R ((coe ∘ f) '' {m | m ≤ b}), { assume a b, rw [span_le_span_iff hs (this a) (this b), set.image_subset_image_iff (subtype.coe_injective.comp f.injective), set.subset_def], exact ⟨λ hab x (hxa : x ≤ a), le_trans hxa hab, λ hx, hx a (le_refl a)⟩ }, exact ⟨⟨λ n, span R ((coe ∘ f) '' {m | m ≤ n}), λ x y, by simp [le_antisymm_iff, (this _ _).symm] {contextual := tt}⟩, by dsimp [gt]; simp only [lt_iff_le_not_le, (this _ _).symm]; tauto⟩ end /-- A module is Noetherian iff every nonempty set of submodules has a maximal submodule among them. -/ theorem set_has_maximal_iff_noetherian {R M} [ring R] [add_comm_group M] [module R M] : (∀ a : set $ submodule R M, a.nonempty → ∃ M' ∈ a, ∀ I ∈ a, M' ≤ I → I = M') ↔ is_noetherian R M := by rw [is_noetherian_iff_well_founded, well_founded.well_founded_iff_has_max'] /-- If `∀ I > J, P I` implies `P J`, then `P` holds for all submodules. -/ lemma is_noetherian.induction {R M} [ring R] [add_comm_group M] [module R M] [is_noetherian R M] {P : submodule R M → Prop} (hgt : ∀ I, (∀ J > I, P J) → P I) (I : submodule R M) : P I := well_founded.recursion (well_founded_submodule_gt R M) I hgt /-- A ring is Noetherian if it is Noetherian as a module over itself, i.e. all its ideals are finitely generated. -/ @[class] def is_noetherian_ring (R) [ring R] : Prop := is_noetherian R R instance is_noetherian_ring.to_is_noetherian {R : Type*} [ring R] : ∀ [is_noetherian_ring R], is_noetherian R R := id @[priority 80] -- see Note [lower instance priority] instance ring.is_noetherian_of_fintype (R M) [fintype M] [ring R] [add_comm_group M] [module R M] : is_noetherian R M := by letI := classical.dec; exact ⟨assume s, ⟨to_finset s, by rw [set.coe_to_finset, submodule.span_eq]⟩⟩ theorem ring.is_noetherian_of_zero_eq_one {R} [ring R] (h01 : (0 : R) = 1) : is_noetherian_ring R := by haveI := subsingleton_of_zero_eq_one h01; haveI := fintype.of_subsingleton (0:R); exact ring.is_noetherian_of_fintype _ _ theorem is_noetherian_of_submodule_of_noetherian (R M) [ring R] [add_comm_group M] [module R M] (N : submodule R M) (h : is_noetherian R M) : is_noetherian R N := begin rw is_noetherian_iff_well_founded at h ⊢, exact order_embedding.well_founded (submodule.map_subtype.order_embedding N).dual h, end theorem is_noetherian_of_quotient_of_noetherian (R) [ring R] (M) [add_comm_group M] [module R M] (N : submodule R M) (h : is_noetherian R M) : is_noetherian R N.quotient := begin rw is_noetherian_iff_well_founded at h ⊢, exact order_embedding.well_founded (submodule.comap_mkq.order_embedding N).dual h, end theorem is_noetherian_of_fg_of_noetherian {R M} [ring R] [add_comm_group M] [module R M] (N : submodule R M) [is_noetherian_ring R] (hN : N.fg) : is_noetherian R N := let ⟨s, hs⟩ := hN in begin haveI := classical.dec_eq M, haveI := classical.dec_eq R, letI : is_noetherian R R := by apply_instance, have : ∀ x ∈ s, x ∈ N, from λ x hx, hs ▸ submodule.subset_span hx, refine @@is_noetherian_of_surjective ((↑s : set M) → R) _ _ _ (pi.semimodule _ _ _) _ _ _ is_noetherian_pi, { fapply linear_map.mk, { exact λ f, ⟨∑ i in s.attach, f i • i.1, N.sum_mem (λ c _, N.smul_mem _ $ this _ c.2)⟩ }, { intros f g, apply subtype.eq, change ∑ i in s.attach, (f i + g i) • _ = _, simp only [add_smul, finset.sum_add_distrib], refl }, { intros c f, apply subtype.eq, change ∑ i in s.attach, (c • f i) • _ = _, simp only [smul_eq_mul, mul_smul], exact finset.smul_sum.symm } }, rw linear_map.range_eq_top, rintro ⟨n, hn⟩, change n ∈ N at hn, rw [← hs, ← set.image_id ↑s, finsupp.mem_span_iff_total] at hn, rcases hn with ⟨l, hl1, hl2⟩, refine ⟨λ x, l x, subtype.ext _⟩, change ∑ i in s.attach, l i • (i : M) = n, rw [@finset.sum_attach M M s _ (λ i, l i • i), ← hl2, finsupp.total_apply, finsupp.sum, eq_comm], refine finset.sum_subset hl1 (λ x _ hx, _), rw [finsupp.not_mem_support_iff.1 hx, zero_smul] end lemma is_noetherian_of_fg_of_noetherian' {R M} [ring R] [add_comm_group M] [module R M] [is_noetherian_ring R] (h : (⊤ : submodule R M).fg) : is_noetherian R M := have is_noetherian R (⊤ : submodule R M), from is_noetherian_of_fg_of_noetherian _ h, by exactI is_noetherian_of_linear_equiv (linear_equiv.of_top (⊤ : submodule R M) rfl) /-- In a module over a noetherian ring, the submodule generated by finitely many vectors is noetherian. -/ theorem is_noetherian_span_of_finite (R) {M} [ring R] [add_comm_group M] [module R M] [is_noetherian_ring R] {A : set M} (hA : finite A) : is_noetherian R (submodule.span R A) := is_noetherian_of_fg_of_noetherian _ (submodule.fg_def.mpr ⟨A, hA, rfl⟩) theorem is_noetherian_ring_of_surjective (R) [comm_ring R] (S) [comm_ring S] (f : R →+* S) (hf : function.surjective f) [H : is_noetherian_ring R] : is_noetherian_ring S := begin rw [is_noetherian_ring, is_noetherian_iff_well_founded] at H ⊢, exact order_embedding.well_founded (ideal.order_embedding_of_surjective f hf).dual H, end section local attribute [instance] subset.comm_ring instance is_noetherian_ring_set_range {R} [comm_ring R] {S} [comm_ring S] (f : R →+* S) [is_noetherian_ring R] : is_noetherian_ring (set.range f) := is_noetherian_ring_of_surjective R (set.range f) (f.cod_restrict (set.range f) set.mem_range_self) set.surjective_onto_range end instance is_noetherian_ring_range {R} [comm_ring R] {S} [comm_ring S] (f : R →+* S) [is_noetherian_ring R] : is_noetherian_ring f.range := is_noetherian_ring_of_surjective R f.range (f.cod_restrict' f.range f.mem_range_self) f.surjective_onto_range theorem is_noetherian_ring_of_ring_equiv (R) [comm_ring R] {S} [comm_ring S] (f : R ≃+* S) [is_noetherian_ring R] : is_noetherian_ring S := is_noetherian_ring_of_surjective R S f.to_ring_hom f.to_equiv.surjective namespace submodule variables {R : Type*} {A : Type*} [comm_ring R] [ring A] [algebra R A] variables (M N : submodule R A) theorem fg_mul (hm : M.fg) (hn : N.fg) : (M * N).fg := let ⟨m, hfm, hm⟩ := fg_def.1 hm, ⟨n, hfn, hn⟩ := fg_def.1 hn in fg_def.2 ⟨m * n, hfm.mul hfn, span_mul_span R m n ▸ hm ▸ hn ▸ rfl⟩ lemma fg_pow (h : M.fg) (n : ℕ) : (M ^ n).fg := nat.rec_on n (⟨{1}, by simp [one_eq_span]⟩) (λ n ih, by simpa [pow_succ] using fg_mul _ _ h ih) end submodule section primes variables {R : Type*} [comm_ring R] [is_noetherian_ring R] /--In a noetherian ring, every ideal contains a product of prime ideals ([samuel, § 3.3, Lemma 3])-/ lemma exists_prime_spectrum_prod_le (I : ideal R) : ∃ (Z : multiset (prime_spectrum R)), multiset.prod (Z.map (coe : subtype _ → ideal R)) ≤ I := begin refine is_noetherian.induction (λ (M : ideal R) hgt, _) I, by_cases h_prM : M.is_prime, { use {⟨M, h_prM⟩}, rw [multiset.map_singleton, multiset.singleton_eq_singleton, multiset.prod_singleton, subtype.coe_mk], exact le_rfl }, by_cases htop : M = ⊤, { rw htop, exact ⟨0, le_top⟩ }, have lt_add : ∀ z ∉ M, M < M + span R {z}, { intros z hz, refine lt_of_le_of_ne le_sup_left (λ m_eq, hz _), rw m_eq, exact mem_sup_right (mem_span_singleton_self z) }, obtain ⟨x, hx, y, hy, hxy⟩ := (ideal.not_is_prime_iff.mp h_prM).resolve_left htop, let Jx := M + span R {x}, let Jy := M + span R {y}, obtain ⟨Wx, h_Wx⟩ := hgt (M + span R {x}) (lt_add _ hx), obtain ⟨Wy, h_Wy⟩ := hgt (M + span R {y}) (lt_add _ hy), use Wx + Wy, let W := Wx + Wy, rw [multiset.map_add, multiset.prod_add], apply le_trans (submodule.mul_le_mul h_Wx h_Wy), rw add_mul, apply sup_le (show M * (M + span R {y}) ≤ M, from ideal.mul_le_right), rw mul_add, apply sup_le (show span R {x} * M ≤ M, from ideal.mul_le_left), rwa [span_mul_span, singleton_mul_singleton, span_singleton_le_iff_mem], end variables {A : Type*} [integral_domain A] [is_noetherian_ring A] /--In a noetherian integral domain which is not a field, every non-zero ideal contains a non-zero product of prime ideals; in a field, the whole ring is a non-zero ideal containing only 0 as product or prime ideals ([samuel, § 3.3, Lemma 3]) -/ lemma exists_prime_spectrum_prod_le_and_ne_bot_of_domain (h_fA : ¬ is_field A) {I : ideal A} (h_nzI: I ≠ ⊥) : ∃ (Z : multiset (prime_spectrum A)), multiset.prod (Z.map (coe : subtype _ → ideal A)) ≤ I ∧ multiset.prod (Z.map (coe : subtype _ → ideal A)) ≠ ⊥ := begin revert h_nzI, refine is_noetherian.induction (λ (M : ideal A) hgt, _) I, intro h_nzM, have hA_nont : nontrivial A, apply is_integral_domain.to_nontrivial (integral_domain.to_is_integral_domain A), by_cases h_topM : M = ⊤, { rcases h_topM with rfl, obtain ⟨p_id, h_nzp, h_pp⟩ : ∃ (p : ideal A), p ≠ ⊥ ∧ p.is_prime, { apply ring.not_is_field_iff_exists_prime.mp h_fA }, use [({⟨p_id, h_pp⟩} : multiset (prime_spectrum A)), le_top], rwa [multiset.map_singleton, multiset.singleton_eq_singleton, multiset.prod_singleton, subtype.coe_mk] }, by_cases h_prM : M.is_prime, { use ({⟨M, h_prM⟩} : multiset (prime_spectrum A)), rw [multiset.map_singleton, multiset.singleton_eq_singleton, multiset.prod_singleton, subtype.coe_mk], exact ⟨le_rfl, h_nzM⟩ }, obtain ⟨x, hx, y, hy, h_xy⟩ := (ideal.not_is_prime_iff.mp h_prM).resolve_left h_topM, have lt_add : ∀ z ∉ M, M < M + span A {z}, { intros z hz, refine lt_of_le_of_ne le_sup_left (λ m_eq, hz _), rw m_eq, exact mem_sup_right (mem_span_singleton_self z) }, obtain ⟨Wx, h_Wx_le, h_Wx_ne⟩ := hgt (M + span A {x}) (lt_add _ hx) (ne_bot_of_gt (lt_add _ hx)), obtain ⟨Wy, h_Wy_le, h_Wx_ne⟩ := hgt (M + span A {y}) (lt_add _ hy) (ne_bot_of_gt (lt_add _ hy)), use Wx + Wy, rw [multiset.map_add, multiset.prod_add], refine ⟨le_trans (submodule.mul_le_mul h_Wx_le h_Wy_le) _, mt ideal.mul_eq_bot.mp _⟩, { rw add_mul, apply sup_le (show M * (M + span A {y}) ≤ M, from ideal.mul_le_right), rw mul_add, apply sup_le (show span A {x} * M ≤ M, from ideal.mul_le_left), rwa [span_mul_span, singleton_mul_singleton, span_singleton_le_iff_mem] }, { rintro (hx | hy); contradiction }, end end primes
189157e8cded23ca01ff92f3bdcacdfe6eefec22
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/group_ring_action_auto.lean
d8b52f4eb6ee614c7294e0661f3bef1f59aa67cb
[]
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
5,921
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.group_theory.group_action.group import Mathlib.data.equiv.ring import Mathlib.deprecated.subring import Mathlib.PostPort universes u v l u_1 namespace Mathlib /-! # Group action on rings This file defines the typeclass of monoid acting on semirings `mul_semiring_action M R`, and the corresponding typeclass of invariant subrings. Note that `algebra` does not satisfy the axioms of `mul_semiring_action`. ## Implementation notes There is no separate typeclass for group acting on rings, group acting on fields, etc. They are all grouped under `mul_semiring_action`. ## Tags group action, invariant subring -/ /-- Typeclass for multiplicative actions by monoids on semirings. -/ class mul_semiring_action (M : Type u) [monoid M] (R : Type v) [semiring R] extends distrib_mul_action M R where smul_one : ∀ (g : M), g • 1 = 1 smul_mul : ∀ (g : M) (x y : R), g • (x * y) = g • x * g • y /-- Typeclass for faithful multiplicative actions by monoids on semirings. -/ class faithful_mul_semiring_action (M : Type u) [monoid M] (R : Type v) [semiring R] extends mul_semiring_action M R where eq_of_smul_eq_smul' : ∀ {m₁ m₂ : M}, (∀ (r : R), m₁ • r = m₂ • r) → m₁ = m₂ @[simp] theorem smul_mul' {M : Type u} [monoid M] {R : Type v} [semiring R] [mul_semiring_action M R] (g : M) (x : R) (y : R) : g • (x * y) = g • x * g • y := mul_semiring_action.smul_mul g x y theorem eq_of_smul_eq_smul {M : Type u} [monoid M] (R : Type v) [semiring R] [faithful_mul_semiring_action M R] {m₁ : M} {m₂ : M} : (∀ (r : R), m₁ • r = m₂ • r) → m₁ = m₂ := faithful_mul_semiring_action.eq_of_smul_eq_smul' /-- Each element of the monoid defines a additive monoid homomorphism. -/ def distrib_mul_action.to_add_monoid_hom (M : Type u) [monoid M] (A : Type v) [add_monoid A] [distrib_mul_action M A] (x : M) : A →+ A := add_monoid_hom.mk (has_scalar.smul x) (smul_zero x) (smul_add x) /-- Each element of the group defines an additive monoid isomorphism. -/ def distrib_mul_action.to_add_equiv (G : Type u) [group G] (A : Type v) [add_monoid A] [distrib_mul_action G A] (x : G) : A ≃+ A := add_equiv.mk (add_monoid_hom.to_fun (distrib_mul_action.to_add_monoid_hom G A x)) (equiv.inv_fun (coe_fn (mul_action.to_perm G A) x)) sorry sorry sorry /-- Each element of the group defines an additive monoid homomorphism. -/ def distrib_mul_action.hom_add_monoid_hom (M : Type u) [monoid M] (A : Type v) [add_monoid A] [distrib_mul_action M A] : M →* add_monoid.End A := monoid_hom.mk (distrib_mul_action.to_add_monoid_hom M A) sorry sorry /-- Each element of the monoid defines a semiring homomorphism. -/ def mul_semiring_action.to_semiring_hom (M : Type u) [monoid M] (R : Type v) [semiring R] [mul_semiring_action M R] (x : M) : R →+* R := ring_hom.mk (add_monoid_hom.to_fun (distrib_mul_action.to_add_monoid_hom M R x)) (smul_one x) (smul_mul' x) sorry sorry theorem injective_to_semiring_hom (M : Type u) [monoid M] (R : Type v) [semiring R] [faithful_mul_semiring_action M R] : function.injective (mul_semiring_action.to_semiring_hom M R) := fun (m₁ m₂ : M) (h : mul_semiring_action.to_semiring_hom M R m₁ = mul_semiring_action.to_semiring_hom M R m₂) => eq_of_smul_eq_smul R fun (r : R) => iff.mp ring_hom.ext_iff h r /-- Each element of the group defines a semiring isomorphism. -/ def mul_semiring_action.to_semiring_equiv (G : Type u) [group G] (R : Type v) [semiring R] [mul_semiring_action G R] (x : G) : R ≃+* R := ring_equiv.mk (add_equiv.to_fun (distrib_mul_action.to_add_equiv G R x)) (add_equiv.inv_fun (distrib_mul_action.to_add_equiv G R x)) sorry sorry sorry sorry theorem list.smul_prod (M : Type u) [monoid M] (R : Type v) [semiring R] [mul_semiring_action M R] (g : M) (L : List R) : g • list.prod L = list.prod (list.map (has_scalar.smul g) L) := monoid_hom.map_list_prod (↑(mul_semiring_action.to_semiring_hom M R g)) L theorem multiset.smul_prod (M : Type u) [monoid M] (S : Type v) [comm_semiring S] [mul_semiring_action M S] (g : M) (m : multiset S) : g • multiset.prod m = multiset.prod (multiset.map (has_scalar.smul g) m) := monoid_hom.map_multiset_prod (↑(mul_semiring_action.to_semiring_hom M S g)) m theorem smul_prod (M : Type u) [monoid M] (S : Type v) [comm_semiring S] [mul_semiring_action M S] (g : M) {ι : Type u_1} (f : ι → S) (s : finset ι) : (g • finset.prod s fun (i : ι) => f i) = finset.prod s fun (i : ι) => g • f i := monoid_hom.map_prod (↑(mul_semiring_action.to_semiring_hom M S g)) f s @[simp] theorem smul_inv {M : Type u} [monoid M] (F : Type v) [field F] [mul_semiring_action M F] (x : M) (m : F) : x • (m⁻¹) = (x • m⁻¹) := ring_hom.map_inv (mul_semiring_action.to_semiring_hom M F x) m @[simp] theorem smul_pow {M : Type u} [monoid M] {R : Type v} [semiring R] [mul_semiring_action M R] (x : M) (m : R) (n : ℕ) : x • m ^ n = (x • m) ^ n := nat.rec_on n (smul_one x) fun (n : ℕ) (ih : x • m ^ n = (x • m) ^ n) => Eq.trans (smul_mul' x m (m ^ n)) (congr_arg (Mul.mul (x • m)) ih) /-- A subring invariant under the action. -/ class is_invariant_subring (M : Type u) [monoid M] {R : Type v} [ring R] [mul_semiring_action M R] (S : set R) [is_subring S] where smul_mem : ∀ (m : M) {x : R}, x ∈ S → m • x ∈ S protected instance is_invariant_subring.to_mul_semiring_action (M : Type u) [monoid M] {R : Type v} [ring R] [mul_semiring_action M R] (S : set R) [is_subring S] [is_invariant_subring M S] : mul_semiring_action M ↥S := mul_semiring_action.mk sorry sorry end Mathlib
59dd77255a4b2a5d5acf7699cbb783d06d63daaf
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/group_theory/p_group.lean
0a4c8224a053650809e1362bcee2c9f295f57c03
[ "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
16,376
lean
/- Copyright (c) 2018 . All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Thomas Browning -/ import data.zmod.basic import group_theory.index import group_theory.group_action.conj_act import group_theory.group_action.quotient import group_theory.perm.cycle.type import group_theory.specific_groups.cyclic import tactic.interval_cases /-! # p-groups > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file contains a proof that if `G` is a `p`-group acting on a finite set `α`, then the number of fixed points of the action is congruent mod `p` to the cardinality of `α`. It also contains proofs of some corollaries of this lemma about existence of fixed points. -/ open_locale big_operators open fintype mul_action variables (p : ℕ) (G : Type*) [group G] /-- A p-group is a group in which every element has prime power order -/ def is_p_group : Prop := ∀ g : G, ∃ k : ℕ, g ^ (p ^ k) = 1 variables {p} {G} namespace is_p_group lemma iff_order_of [hp : fact p.prime] : is_p_group p G ↔ ∀ g : G, ∃ k : ℕ, order_of g = p ^ k := forall_congr (λ g, ⟨λ ⟨k, hk⟩, exists_imp_exists (by exact λ j, Exists.snd) ((nat.dvd_prime_pow hp.out).mp (order_of_dvd_of_pow_eq_one hk)), exists_imp_exists (λ k hk, by rw [←hk, pow_order_of_eq_one])⟩) lemma of_card [fintype G] {n : ℕ} (hG : card G = p ^ n) : is_p_group p G := λ g, ⟨n, by rw [←hG, pow_card_eq_one]⟩ lemma of_bot : is_p_group p (⊥ : subgroup G) := of_card (subgroup.card_bot.trans (pow_zero p).symm) lemma iff_card [fact p.prime] [fintype G] : is_p_group p G ↔ ∃ n : ℕ, card G = p ^ n := begin have hG : card G ≠ 0 := card_ne_zero, refine ⟨λ h, _, λ ⟨n, hn⟩, of_card hn⟩, suffices : ∀ q ∈ nat.factors (card G), q = p, { use (card G).factors.length, rw [←list.prod_replicate, ←list.eq_replicate_of_mem this, nat.prod_factors hG] }, intros q hq, obtain ⟨hq1, hq2⟩ := (nat.mem_factors hG).mp hq, haveI : fact q.prime := ⟨hq1⟩, obtain ⟨g, hg⟩ := exists_prime_order_of_dvd_card q hq2, obtain ⟨k, hk⟩ := (iff_order_of.mp h) g, exact (hq1.pow_eq_iff.mp (hg.symm.trans hk).symm).1.symm, end section G_is_p_group variables (hG : is_p_group p G) include hG lemma of_injective {H : Type*} [group H] (ϕ : H →* G) (hϕ : function.injective ϕ) : is_p_group p H := begin simp_rw [is_p_group, ←hϕ.eq_iff, ϕ.map_pow, ϕ.map_one], exact λ h, hG (ϕ h), end lemma to_subgroup (H : subgroup G) : is_p_group p H := hG.of_injective H.subtype subtype.coe_injective lemma of_surjective {H : Type*} [group H] (ϕ : G →* H) (hϕ : function.surjective ϕ) : is_p_group p H := begin refine λ h, exists.elim (hϕ h) (λ g hg, exists_imp_exists (λ k hk, _) (hG g)), rw [←hg, ←ϕ.map_pow, hk, ϕ.map_one], end lemma to_quotient (H : subgroup G) [H.normal] : is_p_group p (G ⧸ H) := hG.of_surjective (quotient_group.mk' H) quotient.surjective_quotient_mk' lemma of_equiv {H : Type*} [group H] (ϕ : G ≃* H) : is_p_group p H := hG.of_surjective ϕ.to_monoid_hom ϕ.surjective lemma order_of_coprime {n : ℕ} (hn : p.coprime n) (g : G) : (order_of g).coprime n := let ⟨k, hk⟩ := hG g in (hn.pow_left k).coprime_dvd_left (order_of_dvd_of_pow_eq_one hk) /-- If `gcd(p,n) = 1`, then the `n`th power map is a bijection. -/ noncomputable def pow_equiv {n : ℕ} (hn : p.coprime n) : G ≃ G := let h : ∀ g : G, (nat.card (subgroup.zpowers g)).coprime n := λ g, order_eq_card_zpowers' g ▸ hG.order_of_coprime hn g in { to_fun := (^ n), inv_fun := λ g, (pow_coprime (h g)).symm ⟨g, subgroup.mem_zpowers g⟩, left_inv := λ g, subtype.ext_iff.1 $ (pow_coprime (h (g ^ n))).left_inv ⟨g, _, subtype.ext_iff.1 $ (pow_coprime (h g)).left_inv ⟨g, subgroup.mem_zpowers g⟩⟩, right_inv := λ g, subtype.ext_iff.1 $ (pow_coprime (h g)).right_inv ⟨g, subgroup.mem_zpowers g⟩ } @[simp] lemma pow_equiv_apply {n : ℕ} (hn : p.coprime n) (g : G) : hG.pow_equiv hn g = g ^ n := rfl @[simp] lemma pow_equiv_symm_apply {n : ℕ} (hn : p.coprime n) (g : G) : (hG.pow_equiv hn).symm g = g ^ (order_of g).gcd_b n := by rw order_eq_card_zpowers'; refl variables [hp : fact p.prime] include hp /-- If `p ∤ n`, then the `n`th power map is a bijection. -/ @[reducible] noncomputable def pow_equiv' {n : ℕ} (hn : ¬ p ∣ n) : G ≃ G := pow_equiv hG (hp.out.coprime_iff_not_dvd.mpr hn) lemma index (H : subgroup G) [H.finite_index] : ∃ n : ℕ, H.index = p ^ n := begin haveI := H.normal_core.fintype_quotient_of_finite_index, obtain ⟨n, hn⟩ := iff_card.mp (hG.to_quotient H.normal_core), obtain ⟨k, hk1, hk2⟩ := (nat.dvd_prime_pow hp.out).mp ((congr_arg _ (H.normal_core.index_eq_card.trans hn)).mp (subgroup.index_dvd_of_le H.normal_core_le)), exact ⟨k, hk2⟩, end lemma card_eq_or_dvd : nat.card G = 1 ∨ p ∣ nat.card G := begin casesI fintype_or_infinite G, { obtain ⟨n, hn⟩ := iff_card.mp hG, rw [nat.card_eq_fintype_card, hn], cases n, { exact or.inl rfl }, { exact or.inr ⟨p ^ n, rfl⟩ } }, { rw nat.card_eq_zero_of_infinite, exact or.inr ⟨0, rfl⟩ }, end lemma nontrivial_iff_card [fintype G] : nontrivial G ↔ ∃ n > 0, card G = p ^ n := ⟨λ hGnt, let ⟨k, hk⟩ := iff_card.1 hG in ⟨k, nat.pos_of_ne_zero $ λ hk0, by rw [hk0, pow_zero] at hk; exactI fintype.one_lt_card.ne' hk, hk⟩, λ ⟨k, hk0, hk⟩, one_lt_card_iff_nontrivial.1 $ hk.symm ▸ one_lt_pow (fact.out p.prime).one_lt (ne_of_gt hk0)⟩ variables {α : Type*} [mul_action G α] lemma card_orbit (a : α) [fintype (orbit G a)] : ∃ n : ℕ, card (orbit G a) = p ^ n := begin let ϕ := orbit_equiv_quotient_stabilizer G a, haveI := fintype.of_equiv (orbit G a) ϕ, haveI := (stabilizer G a).finite_index_of_finite_quotient, rw [card_congr ϕ, ←subgroup.index_eq_card], exact hG.index (stabilizer G a), end variables (α) [fintype α] /-- If `G` is a `p`-group acting on a finite set `α`, then the number of fixed points of the action is congruent mod `p` to the cardinality of `α` -/ lemma card_modeq_card_fixed_points [fintype (fixed_points G α)] : card α ≡ card (fixed_points G α) [MOD p] := begin classical, calc card α = card (Σ y : quotient (orbit_rel G α), {x // quotient.mk' x = y}) : card_congr (equiv.sigma_fiber_equiv (@quotient.mk' _ (orbit_rel G α))).symm ... = ∑ a : quotient (orbit_rel G α), card {x // quotient.mk' x = a} : card_sigma _ ... ≡ ∑ a : fixed_points G α, 1 [MOD p] : _ ... = _ : by simp; refl, rw [←zmod.eq_iff_modeq_nat p, nat.cast_sum, nat.cast_sum], have key : ∀ x, card {y // (quotient.mk' y : quotient (orbit_rel G α)) = quotient.mk' x} = card (orbit G x) := λ x, by simp only [quotient.eq']; congr, refine eq.symm (finset.sum_bij_ne_zero (λ a _ _, quotient.mk' a.1) (λ _ _ _, finset.mem_univ _) (λ a₁ a₂ _ _ _ _ h, subtype.eq ((mem_fixed_points' α).mp a₂.2 a₁.1 (quotient.exact' h))) (λ b, quotient.induction_on' b (λ b _ hb, _)) (λ a ha _, by { rw [key, mem_fixed_points_iff_card_orbit_eq_one.mp a.2] })), obtain ⟨k, hk⟩ := hG.card_orbit b, have : k = 0 := le_zero_iff.1 (nat.le_of_lt_succ (lt_of_not_ge (mt (pow_dvd_pow p) (by rwa [pow_one, ←hk, ←nat.modeq_zero_iff_dvd, ←zmod.eq_iff_modeq_nat, ←key, nat.cast_zero])))), exact ⟨⟨b, mem_fixed_points_iff_card_orbit_eq_one.2 $ by rw [hk, this, pow_zero]⟩, finset.mem_univ _, (ne_of_eq_of_ne nat.cast_one one_ne_zero), rfl⟩, end /-- If a p-group acts on `α` and the cardinality of `α` is not a multiple of `p` then the action has a fixed point. -/ lemma nonempty_fixed_point_of_prime_not_dvd_card (hpα : ¬ p ∣ card α) [finite (fixed_points G α)] : (fixed_points G α).nonempty := @set.nonempty_of_nonempty_subtype _ _ begin casesI nonempty_fintype (fixed_points G α), rw [←card_pos_iff, pos_iff_ne_zero], contrapose! hpα, rw [←nat.modeq_zero_iff_dvd, ←hpα], exact hG.card_modeq_card_fixed_points α, end /-- If a p-group acts on `α` and the cardinality of `α` is a multiple of `p`, and the action has one fixed point, then it has another fixed point. -/ lemma exists_fixed_point_of_prime_dvd_card_of_fixed_point (hpα : p ∣ card α) {a : α} (ha : a ∈ fixed_points G α) : ∃ b, b ∈ fixed_points G α ∧ a ≠ b := begin casesI nonempty_fintype (fixed_points G α), have hpf : p ∣ card (fixed_points G α) := nat.modeq_zero_iff_dvd.mp ((hG.card_modeq_card_fixed_points α).symm.trans hpα.modeq_zero_nat), have hα : 1 < card (fixed_points G α) := (fact.out p.prime).one_lt.trans_le (nat.le_of_dvd (card_pos_iff.2 ⟨⟨a, ha⟩⟩) hpf), exact let ⟨⟨b, hb⟩, hba⟩ := exists_ne_of_one_lt_card hα ⟨a, ha⟩ in ⟨b, hb, λ hab, hba (by simp_rw [hab])⟩ end lemma center_nontrivial [nontrivial G] [finite G] : nontrivial (subgroup.center G) := begin classical, casesI nonempty_fintype G, have := (hG.of_equiv conj_act.to_conj_act).exists_fixed_point_of_prime_dvd_card_of_fixed_point G, rw conj_act.fixed_points_eq_center at this, obtain ⟨g, hg⟩ := this _ (subgroup.center G).one_mem, { exact ⟨⟨1, ⟨g, hg.1⟩, mt subtype.ext_iff.mp hg.2⟩⟩ }, { obtain ⟨n, hn0, hn⟩ := hG.nontrivial_iff_card.mp infer_instance, exact hn.symm ▸ dvd_pow_self _ (ne_of_gt hn0) }, end lemma bot_lt_center [nontrivial G] [finite G] : ⊥ < subgroup.center G := begin haveI := center_nontrivial hG, casesI nonempty_fintype G, classical, exact bot_lt_iff_ne_bot.mpr ((subgroup.center G).one_lt_card_iff_ne_bot.mp fintype.one_lt_card), end end G_is_p_group lemma to_le {H K : subgroup G} (hK : is_p_group p K) (hHK : H ≤ K) : is_p_group p H := hK.of_injective (subgroup.inclusion hHK) (λ a b h, subtype.ext (show _, from subtype.ext_iff.mp h)) lemma to_inf_left {H K : subgroup G} (hH : is_p_group p H) : is_p_group p (H ⊓ K : subgroup G) := hH.to_le inf_le_left lemma to_inf_right {H K : subgroup G} (hK : is_p_group p K) : is_p_group p (H ⊓ K : subgroup G) := hK.to_le inf_le_right lemma map {H : subgroup G} (hH : is_p_group p H) {K : Type*} [group K] (ϕ : G →* K) : is_p_group p (H.map ϕ) := begin rw [←H.subtype_range, monoid_hom.map_range], exact hH.of_surjective (ϕ.restrict H).range_restrict (ϕ.restrict H).range_restrict_surjective, end lemma comap_of_ker_is_p_group {H : subgroup G} (hH : is_p_group p H) {K : Type*} [group K] (ϕ : K →* G) (hϕ : is_p_group p ϕ.ker) : is_p_group p (H.comap ϕ) := begin intro g, obtain ⟨j, hj⟩ := hH ⟨ϕ g.1, g.2⟩, rw [subtype.ext_iff, H.coe_pow, subtype.coe_mk, ←ϕ.map_pow] at hj, obtain ⟨k, hk⟩ := hϕ ⟨g.1 ^ p ^ j, hj⟩, rwa [subtype.ext_iff, ϕ.ker.coe_pow, subtype.coe_mk, ←pow_mul, ←pow_add] at hk, exact ⟨j + k, by rwa [subtype.ext_iff, (H.comap ϕ).coe_pow]⟩, end lemma ker_is_p_group_of_injective {K : Type*} [group K] {ϕ : K →* G} (hϕ : function.injective ϕ) : is_p_group p ϕ.ker := (congr_arg (λ Q : subgroup K, is_p_group p Q) (ϕ.ker_eq_bot_iff.mpr hϕ)).mpr is_p_group.of_bot lemma comap_of_injective {H : subgroup G} (hH : is_p_group p H) {K : Type*} [group K] (ϕ : K →* G) (hϕ : function.injective ϕ) : is_p_group p (H.comap ϕ) := hH.comap_of_ker_is_p_group ϕ (ker_is_p_group_of_injective hϕ) lemma comap_subtype {H : subgroup G} (hH : is_p_group p H) {K : subgroup G} : is_p_group p (H.comap K.subtype) := hH.comap_of_injective K.subtype subtype.coe_injective lemma to_sup_of_normal_right {H K : subgroup G} (hH : is_p_group p H) (hK : is_p_group p K) [K.normal] : is_p_group p (H ⊔ K : subgroup G) := begin rw [←quotient_group.ker_mk K, ←subgroup.comap_map_eq], apply (hH.map (quotient_group.mk' K)).comap_of_ker_is_p_group, rwa quotient_group.ker_mk, end lemma to_sup_of_normal_left {H K : subgroup G} (hH : is_p_group p H) (hK : is_p_group p K) [H.normal] : is_p_group p (H ⊔ K : subgroup G) := (congr_arg (λ H : subgroup G, is_p_group p H) sup_comm).mp (to_sup_of_normal_right hK hH) lemma to_sup_of_normal_right' {H K : subgroup G} (hH : is_p_group p H) (hK : is_p_group p K) (hHK : H ≤ K.normalizer) : is_p_group p (H ⊔ K : subgroup G) := let hHK' := to_sup_of_normal_right (hH.of_equiv (subgroup.subgroup_of_equiv_of_le hHK).symm) (hK.of_equiv (subgroup.subgroup_of_equiv_of_le subgroup.le_normalizer).symm) in ((congr_arg (λ H : subgroup K.normalizer, is_p_group p H) (subgroup.sup_subgroup_of_eq hHK subgroup.le_normalizer)).mp hHK').of_equiv (subgroup.subgroup_of_equiv_of_le (sup_le hHK subgroup.le_normalizer)) lemma to_sup_of_normal_left' {H K : subgroup G} (hH : is_p_group p H) (hK : is_p_group p K) (hHK : K ≤ H.normalizer) : is_p_group p (H ⊔ K : subgroup G) := (congr_arg (λ H : subgroup G, is_p_group p H) sup_comm).mp (to_sup_of_normal_right' hK hH hHK) /-- finite p-groups with different p have coprime orders -/ lemma coprime_card_of_ne {G₂ : Type*} [group G₂] (p₁ p₂ : ℕ) [hp₁ : fact p₁.prime] [hp₂ : fact p₂.prime] (hne : p₁ ≠ p₂) (H₁ : subgroup G) (H₂ : subgroup G₂) [fintype H₁] [fintype H₂] (hH₁ : is_p_group p₁ H₁) (hH₂ : is_p_group p₂ H₂) : nat.coprime (fintype.card H₁) (fintype.card H₂) := begin obtain ⟨n₁, heq₁⟩ := iff_card.mp hH₁, rw heq₁, clear heq₁, obtain ⟨n₂, heq₂⟩ := iff_card.mp hH₂, rw heq₂, clear heq₂, exact nat.coprime_pow_primes _ _ (hp₁.elim) (hp₂.elim) hne, end /-- p-groups with different p are disjoint -/ lemma disjoint_of_ne (p₁ p₂ : ℕ) [hp₁ : fact p₁.prime] [hp₂ : fact p₂.prime] (hne : p₁ ≠ p₂) (H₁ H₂ : subgroup G) (hH₁ : is_p_group p₁ H₁) (hH₂ : is_p_group p₂ H₂) : disjoint H₁ H₂ := begin rw subgroup.disjoint_def, intros x hx₁ hx₂, obtain ⟨n₁, hn₁⟩ := iff_order_of.mp hH₁ ⟨x, hx₁⟩, obtain ⟨n₂, hn₂⟩ := iff_order_of.mp hH₂ ⟨x, hx₂⟩, rw [← order_of_subgroup, subgroup.coe_mk] at hn₁ hn₂, have : p₁ ^ n₁ = p₂ ^ n₂, by rw [← hn₁, ← hn₂], rcases n₁.eq_zero_or_pos with rfl|hn₁, { simpa using hn₁ }, { exact absurd (eq_of_prime_pow_eq hp₁.out.prime hp₂.out.prime hn₁ this) hne } end section p2comm variables [fintype G] [fact p.prime] {n : ℕ} (hGpn : card G = p ^ n) include hGpn open subgroup /-- The cardinality of the `center` of a `p`-group is `p ^ k` where `k` is positive. -/ lemma card_center_eq_prime_pow (hn : 0 < n) [fintype (center G)] : ∃ k > 0, card (center G) = p ^ k := begin have hcG := to_subgroup (of_card hGpn) (center G), rcases iff_card.1 hcG with ⟨k, hk⟩, haveI : nontrivial G := (nontrivial_iff_card $ of_card hGpn).2 ⟨n, hn, hGpn⟩, exact (nontrivial_iff_card hcG).mp (center_nontrivial (of_card hGpn)), end omit hGpn /-- The quotient by the center of a group of cardinality `p ^ 2` is cyclic. -/ lemma cyclic_center_quotient_of_card_eq_prime_sq (hG : card G = p ^ 2) : is_cyclic (G ⧸ (center G)) := begin classical, rcases card_center_eq_prime_pow hG zero_lt_two with ⟨k, hk0, hk⟩, rw [card_eq_card_quotient_mul_card_subgroup (center G), mul_comm, hk] at hG, have hk2 := (nat.pow_dvd_pow_iff_le_right (fact.out p.prime).one_lt).1 ⟨_, hG.symm⟩, interval_cases k, { rw [sq, pow_one, mul_right_inj' (fact.out p.prime).ne_zero] at hG, exact is_cyclic_of_prime_card hG }, { exact @is_cyclic_of_subsingleton _ _ ⟨fintype.card_le_one_iff.1 (mul_right_injective₀ (pow_ne_zero 2 (ne_zero.ne p)) (hG.trans (mul_one (p ^ 2)).symm)).le⟩ }, end /-- A group of order `p ^ 2` is commutative. See also `is_p_group.commutative_of_card_eq_prime_sq` for just the proof that `∀ a b, a * b = b * a` -/ def comm_group_of_card_eq_prime_sq (hG : card G = p ^ 2) : comm_group G := @comm_group_of_cycle_center_quotient _ _ _ _ (cyclic_center_quotient_of_card_eq_prime_sq hG) _ (quotient_group.ker_mk (center G)).le /-- A group of order `p ^ 2` is commutative. See also `is_p_group.comm_group_of_card_eq_prime_sq` for the `comm_group` instance. -/ lemma commutative_of_card_eq_prime_sq (hG : card G = p ^ 2) : ∀ a b : G, a * b = b * a := (comm_group_of_card_eq_prime_sq hG).mul_comm end p2comm end is_p_group
ac178c90de676e14d739b83e1abdd640d1eb2245
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/tactic/dependencies.lean
46850fc385c25af9e301457d578761556e125abe
[ "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
30,420
lean
/- Copyright (c) 2020 Jannis Limperg. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jannis Limperg -/ import tactic.core /-! # Tactics About Dependencies This module provides tactics to compute dependencies and reverse dependencies of hypotheses. An expression `e` depends on a hypothesis `h` if `e` would not be valid if `h` were removed from the context. For example, the expression `e := x > 0` depends on `x`. We say that `x` is a dependency of `e` and that `e` is a reverse dependency of `x`. It is sometimes useful to consider *inclusive* dependency: `e` inclusively depends on `h` iff `e` depends on `h` or `e = h` (so inclusive dependency is the reflexive closure of regular dependency). Note that the standard library does not use quite the same terminology: * `kdependencies`/`kdeps` from the standard library compute reverse dependencies, not dependencies. * `kdepends_on` and functions derived from it ignore local definitions and therefore compute a weaker dependency relation (see next section). ## Local Definitions Determining dependencies of hypotheses is usually straightforward: a hypothesis `r : R` depends on another hypothesis `d : D` if `d` occurs in `R`. The implementation is more involved, however, in the presence of local definitions. Consider this context: ```lean n m : ℕ k : ℕ := m o : ℕ := k h : o > 0 ``` `h` depends on `o`, `k` and `m`, but only the dependency on `o` is syntactically obvious. `kdepends_on` ignores this complication and claims that `h` does not depend on `k` or `m`. We do not follow this example but process local definitions properly. This means that if the context contains a local definition, we need to compute the syntactic dependencies of `h`, then their dependencies, and so on. ## Direct Dependencies If you want to ignore local definitions while computing dependencies, this module also provides tactics to find the *direct* dependencies of a hypothesis. These are the hypotheses that syntactically appear in the hypothesis's type (or value, if the hypothesis is a local definition). -/ open native open expr_set (local_set_to_name_set) open name_set (local_list_to_name_set) namespace tactic /-! ### Direct Dependencies -/ /-! #### Checking whether hypotheses directly depend on each other -/ /-- `type_has_local_in_name_set h ns` returns true iff the type of `h` contains a local constant whose unique name appears in `ns`. -/ meta def type_has_local_in_name_set (h : expr) (ns : name_set) : tactic bool := do h_type ← infer_type h, pure $ h_type.has_local_in ns /-- `type_has_local_in_set h hs` returns true iff the type of `h` contains any of the local constants `hs`. -/ meta def type_has_local_in_set (h : expr) (hs : expr_set) : tactic bool := type_has_local_in_name_set h $ local_set_to_name_set hs /-- `type_has_local_in h hs` returns true iff the type of `h` contains any of the local constants `hs`. -/ meta def type_has_local_in (h : expr) (hs : list expr) : tactic bool := type_has_local_in_name_set h $ local_list_to_name_set hs /-- `local_def_value_has_local_in_name_set h ns` returns true iff `h` is a local definition whose value contains a local constant whose unique name appears in `ns`. -/ meta def local_def_value_has_local_in_name_set (h : expr) (ns : name_set) : tactic bool := do (some h_val) ← try_core $ local_def_value h | pure ff, pure $ h_val.has_local_in ns /-- `local_def_value_has_local_in_set h hs` returns true iff `h` is a local definition whose value contains any of the local constants `hs`. -/ meta def local_def_value_has_local_in_set (h : expr) (hs : expr_set) : tactic bool := local_def_value_has_local_in_name_set h $ local_set_to_name_set hs /-- `local_def_value_has_local_in h hs` returns true iff `h` is a local definition whose value contains any of the local constants `hs`. -/ meta def local_def_value_has_local_in (h : expr) (hs : list expr) : tactic bool := local_def_value_has_local_in_name_set h $ local_list_to_name_set hs /-- `hyp_directly_depends_on_local_name_set h ns` is true iff the hypothesis `h` directly depends on a hypothesis whose unique name appears in `ns`. -/ meta def hyp_directly_depends_on_local_name_set (h : expr) (ns : name_set) : tactic bool := list.mbor [ type_has_local_in_name_set h ns, local_def_value_has_local_in_name_set h ns ] /-- `hyp_directly_depends_on_local_set h hs` is true iff the hypothesis `h` directly depends on any of the hypotheses `hs`. -/ meta def hyp_directly_depends_on_local_set (h : expr) (hs : expr_set) : tactic bool := hyp_directly_depends_on_local_name_set h $ local_set_to_name_set hs /-- `hyp_directly_depends_on_locals h hs` is true iff the hypothesis `h` directly depends on any of the hypotheses `hs`. -/ meta def hyp_directly_depends_on_locals (h : expr) (hs : list expr) : tactic bool := hyp_directly_depends_on_local_name_set h $ local_list_to_name_set hs /-- `hyp_directly_depends_on_local_name_set_inclusive h ns` is true iff the hypothesis `h` directly depends on a hypothesis whose unique name appears in `ns` or `h`'s name appears in `ns`. -/ meta def hyp_directly_depends_on_local_name_set_inclusive (h : expr) (ns : name_set) : tactic bool := list.mbor [ pure $ ns.contains h.local_uniq_name , hyp_directly_depends_on_local_name_set h ns ] /-- `hyp_directly_depends_on_local_set_inclusive h ns` is true iff the hypothesis `h` directly depends on any of the hypotheses `hs` or `h` appears in `hs`. -/ meta def hyp_directly_depends_on_local_set_inclusive (h : expr) (hs : expr_set) : tactic bool := hyp_directly_depends_on_local_name_set_inclusive h $ local_set_to_name_set hs /-- `hyp_directly_depends_on_locals_inclusive h ns` is true iff the hypothesis `h` directly depends on any of the hypotheses `hs` or `h` appears in `hs`. -/ meta def hyp_directly_depends_on_locals_inclusive (h : expr) (hs : list expr) : tactic bool := hyp_directly_depends_on_local_name_set_inclusive h $ local_list_to_name_set hs /-! #### Computing the direct dependencies of a hypothesis -/ /-- `direct_dependency_set_of_hyp h` is the set of hypotheses that the hypothesis `h` directly depends on. These are the hypotheses that appear in `h`'s type or value (if `h` is a local definition). -/ meta def direct_dependency_set_of_hyp (h : expr) : tactic expr_set := do t ← infer_type h, let deps := t.list_local_consts', (some val) ← try_core $ local_def_value h | pure deps, let deps := deps.union val.list_local_consts', pure deps /-- `direct_dependency_name_set_of_hyp h` is the set of unique names of hypotheses that the hypothesis `h` directly depends on. These are the hypotheses that appear in `h`'s type or value (if `h` is a local definition). -/ meta def direct_dependency_name_set_of_hyp (h : expr) : tactic name_set := local_set_to_name_set <$> direct_dependency_set_of_hyp h /-- `direct_dependencies_of_hyp h` is the list of hypotheses that the hypothesis `h` directly depends on. These are the hypotheses that appear in `h`'s type or value (if `h` is a local definition). The dependencies are returned in no particular order. -/ meta def direct_dependencies_of_hyp (h : expr) : tactic (list expr) := rb_set.to_list <$> direct_dependency_set_of_hyp h /-- `direct_dependency_set_of_hyp_inclusive h` is the set of hypotheses that the hypothesis `h` directly depends on, plus `h` itself. -/ meta def direct_dependency_set_of_hyp_inclusive (h : expr) : tactic expr_set := do deps ← direct_dependency_set_of_hyp h, pure $ deps.insert h /-- `direct_dependency_name_set_of_hyp_inclusive h` is the set of unique names of hypotheses that the hypothesis `h` directly depends on, plus `h` itself. -/ meta def direct_dependency_name_set_of_hyp_inclusive (h : expr) : tactic name_set := local_set_to_name_set <$> direct_dependency_set_of_hyp_inclusive h /-- `direct_dependencies_of_hyp_inclusive h` is the list of hypotheses that the hypothesis `h` directly depends on, plus `h` itself. The dependencies are returned in no particular order. -/ meta def direct_dependencies_of_hyp_inclusive (h : expr) : tactic (list expr) := rb_set.to_list <$> direct_dependency_set_of_hyp_inclusive h /-! ### Indirect/Transitive Dependencies -/ /-! #### Checking whether hypotheses depend on each other -/ /-- `hyp_depends_on_local_name_set' cache h ns` is true iff `h` depends on any of the hypotheses whose unique names appear in `ns`. `cache` must be a set of hypotheses known *not* to depend (even indirectly) on any of the `ns`. This is a performance optimisation, so you can give an empty cache. The tactic also returns an expanded cache with hypotheses which the tactic has encountered. You probably want to use `tactic.hyp_depends_on_local_name_set` or `tactic.hyps_depend_on_local_name_set` instead of this tactic. -/ meta def hyp_depends_on_local_name_set' : expr_set → expr → name_set → tactic (bool × expr_set) := λ cache h ns, do ff ← pure $ cache.contains h | pure (ff, cache), direct_deps ← direct_dependency_set_of_hyp h, let has_dep := direct_deps.fold ff (λ d b, b || ns.contains d.local_uniq_name), ff ← pure has_dep | pure (tt, cache), (has_dep, cache) ← direct_deps.mfold (ff, cache) $ λ d ⟨b, cache⟩, if b then pure (tt, cache) else hyp_depends_on_local_name_set' cache d ns, if has_dep then pure (tt, cache) else pure (ff, cache.insert h) /-- `hyp_depends_on_local_name_set h ns` is true iff the hypothesis `h` depends on any of the hypotheses whose unique names appear in `ns`. If you need to check dependencies of multiple hypotheses, use `tactic.hyps_depend_on_local_name_set`. -/ meta def hyp_depends_on_local_name_set (h : expr) (ns : name_set) : tactic bool := do ctx_has_local_def ← context_upto_hyp_has_local_def h, if ctx_has_local_def then prod.fst <$> hyp_depends_on_local_name_set' mk_expr_set h ns else hyp_directly_depends_on_local_name_set h ns /-- `hyp_depends_on_local_set h hs` is true iff the hypothesis `h` depends on any of the hypotheses `hs`. If you need to check dependencies of multiple hypotheses, use `tactic.hyps_depend_on_local_set`. -/ meta def hyp_depends_on_local_set (h : expr) (hs : expr_set) : tactic bool := hyp_depends_on_local_name_set h $ local_set_to_name_set hs /-- `hyp_depends_on_locals h hs` is true iff the hypothesis `h` depends on any of the hypotheses `hs`. If you need to check dependencies of multiple hypotheses, use `tactic.hyps_depend_on_locals`. -/ meta def hyp_depends_on_locals (h : expr) (hs : list expr) : tactic bool := hyp_depends_on_local_name_set h $ local_list_to_name_set hs /-- `hyps_depend_on_local_name_set hs ns` returns, for each `h ∈ hs`, whether `h` depends on a hypothesis whose unique name appears in `ns`. This is the same as (but more efficient than) calling `tactic.hyp_depends_on_local_name_set` for every `h ∈ hs`. -/ meta def hyps_depend_on_local_name_set (hs : list expr) (ns : name_set) : tactic (list bool) := do ctx_has_local ← context_has_local_def, if ctx_has_local then let go : expr → list bool × expr_set → tactic (list bool × expr_set) := λ h ⟨deps, cache⟩, do { (h_dep, cache) ← hyp_depends_on_local_name_set' cache h ns, pure (h_dep :: deps, cache) } in prod.fst <$> hs.mfoldr go ([], mk_expr_map) else hs.mmap $ λ h, hyp_directly_depends_on_local_name_set h ns /-- `hyps_depend_on_local_set hs is` returns, for each `h ∈ hs`, whether `h` depends on any of the hypotheses `is`. This is the same as (but more efficient than) calling `tactic.hyp_depends_on_local_set` for every `h ∈ hs`. -/ meta def hyps_depend_on_local_set (hs : list expr) (is : expr_set) : tactic (list bool) := hyps_depend_on_local_name_set hs $ local_set_to_name_set is /-- `hyps_depend_on_locals hs is` returns, for each `h ∈ hs`, whether `h` depends on any of the hypotheses `is`. This is the same as (but more efficient than) calling `tactic.hyp_depends_on_locals` for every `h ∈ hs`. -/ meta def hyps_depend_on_locals (hs is : list expr) : tactic (list bool) := hyps_depend_on_local_name_set hs $ local_list_to_name_set is /-- `hyp_depends_on_local_name_set_inclusive' cache h ns` is true iff the hypothesis `h` inclusively depends on a hypothesis whose unique name appears in `ns`. `cache` must be a set of hypotheses known *not* to depend (even indirectly) on any of the `ns`. This is a performance optimisation, so you can give an empty cache. The tactic also returns an expanded cache with hypotheses which the tactic has encountered. Note that the cache records exclusive, not inclusive dependencies. You probably want to use `tactic.hyp_depends_on_local_name_set_inclusive` or `tactic.hyps_depend_on_local_name_set_inclusive` instead of this tactic. -/ meta def hyp_depends_on_local_name_set_inclusive' (cache : expr_set) (h : expr) (ns : name_set) : tactic (bool × expr_set) := if ns.contains h.local_uniq_name then pure (tt, cache) else hyp_depends_on_local_name_set' cache h ns /-- `hyp_depends_on_local_name_set_inclusive h ns` is true iff the hypothesis `h` inclusively depends on any of the hypotheses whose unique names appear in `ns`. If you need to check the dependencies of multiple hypotheses, use `tactic.hyps_depend_on_local_name_set_inclusive`. -/ meta def hyp_depends_on_local_name_set_inclusive (h : expr) (ns : name_set) : tactic bool := list.mbor [ pure $ ns.contains h.local_uniq_name, hyp_depends_on_local_name_set h ns ] /-- `hyp_depends_on_local_set_inclusive h hs` is true iff the hypothesis `h` inclusively depends on any of the hypotheses `hs`. If you need to check dependencies of multiple hypotheses, use `tactic.hyps_depend_on_local_set_inclusive`. -/ meta def hyp_depends_on_local_set_inclusive (h : expr) (hs : expr_set) : tactic bool := hyp_depends_on_local_name_set_inclusive h $ local_set_to_name_set hs /-- `hyp_depends_on_locals_inclusive h hs` is true iff the hypothesis `h` inclusively depends on any of the hypotheses `hs`. If you need to check dependencies of multiple hypotheses, use `tactic.hyps_depend_on_locals_inclusive`. -/ meta def hyp_depends_on_locals_inclusive (h : expr) (hs : list expr) : tactic bool := hyp_depends_on_local_name_set_inclusive h $ local_list_to_name_set hs /-- `hyps_depend_on_local_name_set_inclusive hs ns` returns, for each `h ∈ hs`, whether `h` inclusively depends on a hypothesis whose unique name appears in `ns`. This is the same as (but more efficient than) calling `tactic.hyp_depends_on_local_name_set_inclusive` for every `h ∈ hs`. -/ meta def hyps_depend_on_local_name_set_inclusive (hs : list expr) (ns : name_set) : tactic (list bool) := do ctx_has_local ← context_has_local_def, if ctx_has_local then let go : expr → list bool × expr_set → tactic (list bool × expr_set) := λ h ⟨deps, cache⟩, do { (h_dep, cache) ← hyp_depends_on_local_name_set_inclusive' cache h ns, pure (h_dep :: deps, cache) } in prod.fst <$> hs.mfoldr go ([], mk_expr_map) else hs.mmap $ λ h, hyp_directly_depends_on_local_name_set_inclusive h ns /-- `hyps_depend_on_local_set_inclusive hs is` returns, for each `h ∈ hs`, whether `h` depends inclusively on any of the hypotheses `is`. This is the same as (but more efficient than) calling `tactic.hyp_depends_on_local_set_inclusive` for every `h ∈ hs`. -/ meta def hyps_depend_on_local_set_inclusive (hs : list expr) (is : expr_set) : tactic (list bool) := hyps_depend_on_local_name_set_inclusive hs $ local_set_to_name_set is /-- `hyps_depend_on_locals_inclusive hs is` returns, for each `h ∈ hs`, whether `h` depends inclusively on any of the hypotheses `is`. This is the same as (but more efficient than) calling `tactic.hyp_depends_on_locals_inclusive` for every `h ∈ hs`. -/ meta def hyps_depend_on_locals_inclusive (hs is : list expr) : tactic (list bool) := hyps_depend_on_local_name_set_inclusive hs $ local_list_to_name_set is /-! #### Computing the dependencies of a hypothesis -/ /-- `dependency_set_of_hyp' cache h` is the set of dependencies of the hypothesis `h`. `cache` is a map from hypotheses to all their dependencies (including indirect dependencies). This is a performance optimisation, so you can give an empty cache. The tactic also returns an expanded cache with hypotheses which the tactic has encountered. You probably want to use `tactic.dependency_set_of_hyp` or `tactic.dependency_sets_of_hyps` instead of this tactic. -/ meta def dependency_set_of_hyp' : expr_map expr_set → expr → tactic (expr_set × expr_map expr_set) := λ cache h, do match cache.find h with | some deps := pure (deps, cache) | none := do direct_deps ← direct_dependency_set_of_hyp h, (deps, cache) ← direct_deps.mfold (direct_deps, cache) $ λ h' ⟨deps, cache⟩, do { (deps', cache) ← dependency_set_of_hyp' cache h', pure (deps.union deps', cache) }, pure (deps, cache.insert h deps) end /-- `dependency_set_of_hyp h` is the set of dependencies of the hypothesis `h`. If you need the dependencies of multiple hypotheses, use `tactic.dependency_sets_of_hyps`. -/ meta def dependency_set_of_hyp (h : expr) : tactic expr_set := do ctx_has_local ← context_upto_hyp_has_local_def h, if ctx_has_local then prod.fst <$> dependency_set_of_hyp' mk_expr_map h else direct_dependency_set_of_hyp h /-- `dependency_name_set_of_hyp h` is the set of unique names of the dependencies of the hypothesis `h`. If you need the dependencies of multiple hypotheses, use `tactic.dependency_name_sets_of_hyps`. -/ meta def dependency_name_set_of_hyp (h : expr) : tactic name_set := local_set_to_name_set <$> dependency_set_of_hyp h /-- `dependencies_of_hyp h` is the list of dependencies of the hypothesis `h`. The dependencies are returned in no particular order. If you need the dependencies of multiple hypotheses, use `tactic.dependencies_of_hyps`. -/ meta def dependencies_of_hyp (h : expr) : tactic (list expr) := rb_set.to_list <$> dependency_set_of_hyp h /-- `dependency_sets_of_hyps hs` returns, for each `h ∈ hs`, the set of dependencies of `h`. This is the same as (but more performant than) using `tactic.dependency_set_of_hyp` on every `h ∈ hs`. -/ meta def dependency_sets_of_hyps (hs : list expr) : tactic (list expr_set) := do ctx_has_def ← context_has_local_def, if ctx_has_def then let go : expr → list expr_set × expr_map expr_set → tactic (list expr_set × expr_map expr_set) := do λ h ⟨deps, cache⟩, do { (h_deps, cache) ← dependency_set_of_hyp' cache h, pure (h_deps :: deps, cache) } in prod.fst <$> hs.mfoldr go ([], mk_expr_map) else hs.mmap direct_dependency_set_of_hyp /-- `dependency_name_sets_of_hyps hs` returns, for each `h ∈ hs`, the set of unique names of the dependencies of `h`. This is the same as (but more performant than) using `tactic.dependency_name_set_of_hyp` on every `h ∈ hs`. -/ meta def dependency_name_sets_of_hyps (hs : list expr) : tactic (list name_set) := list.map local_set_to_name_set <$> dependency_sets_of_hyps hs /-- `dependencies_of_hyps hs` returns, for each `h ∈ hs`, the dependencies of `h`. The dependencies appear in no particular order in the returned lists. This is the same as (but more performant than) using `tactic.dependencies_of_hyp` on every `h ∈ hs`. -/ meta def dependencies_of_hyps (hs : list expr) : tactic (list (list expr)) := list.map rb_set.to_list <$> dependency_sets_of_hyps hs /-- `dependency_set_of_hyp_inclusive' cache h` is the set of dependencies of the hypothesis `h`, plus `h` itself. `cache` is a map from hypotheses to all their dependencies (including indirect dependencies). This is a performance optimisation, so you can give an empty cache. The tactic also returns an expanded cache with hypotheses which the tactic has encountered. Note that the cache records exclusive, not inclusive dependencies. You probably want to use `tactic.dependency_set_of_hyp_inclusive` or `tactic.dependency_sets_of_hyps_inclusive` instead of this tactic. -/ meta def dependency_set_of_hyp_inclusive' (cache : expr_map expr_set) (h : expr) : tactic (expr_set × expr_map expr_set) := do (deps, cache) ← dependency_set_of_hyp' cache h, pure (deps.insert h, cache) /-- `dependency_set_of_hyp_inclusive h` is the set of dependencies of the hypothesis `h`, plus `h` itself. If you need the dependencies of multiple hypotheses, use `tactic.dependency_sets_of_hyps_inclusive`. -/ meta def dependency_set_of_hyp_inclusive (h : expr) : tactic expr_set := do deps ← dependency_set_of_hyp h, pure $ deps.insert h /-- `dependency_name_set_of_hyp_inclusive h` is the set of unique names of the dependencies of the hypothesis `h`, plus the unique name of `h` itself. If you need the dependencies of multiple hypotheses, use `tactic.dependency_name_sets_of_hyps_inclusive`. -/ meta def dependency_name_set_of_hyp_inclusive (h : expr) : tactic name_set := local_set_to_name_set <$> dependency_set_of_hyp_inclusive h /-- `dependencies_of_hyp_inclusive h` is the list of dependencies of the hypothesis `h`, plus `h` itself. The dependencies are returned in no particular order. If you need the dependencies of multiple hypotheses, use `tactic.dependencies_of_hyps_inclusive`. -/ meta def dependencies_of_hyp_inclusive (h : expr) : tactic (list expr) := rb_set.to_list <$> dependency_set_of_hyp_inclusive h /-- `dependency_sets_of_hyps_inclusive hs` returns, for each `h ∈ hs`, the dependencies of `h`, plus `h` itself. This is the same as (but more performant than) using `tactic.dependency_set_of_hyp_inclusive` on every `h ∈ hs`. -/ meta def dependency_sets_of_hyps_inclusive (hs : list expr) : tactic (list expr_set) := do ctx_has_def ← context_has_local_def, if ctx_has_def then let go : expr → list expr_set × expr_map expr_set → tactic (list expr_set × expr_map expr_set) := λ h ⟨deps, cache⟩, do { (h_deps, cache) ← dependency_set_of_hyp_inclusive' cache h, pure (h_deps :: deps, cache) } in prod.fst <$> hs.mfoldr go ([], mk_expr_map) else hs.mmap direct_dependency_set_of_hyp_inclusive /-- `dependency_name_sets_of_hyps_inclusive hs` returns, for each `h ∈ hs`, the unique names of the dependencies of `h`, plus the unique name of `h` itself. This is the same as (but more performant than) using `tactic.dependency_name_set_of_hyp_inclusive` on every `h ∈ hs`. -/ meta def dependency_name_sets_of_hyps_inclusive (hs : list expr) : tactic (list name_set) := list.map local_set_to_name_set <$> dependency_sets_of_hyps_inclusive hs /-- `dependencies_of_hyps_inclusive hs` returns, for each `h ∈ hs`, the dependencies of `h`, plus `h` itself. The dependencies appear in no particular order in the returned lists. This is the same as (but more performant than) using `tactic.dependencies_of_hyp_inclusive` on every `h ∈ hs`. -/ meta def dependencies_of_hyps_inclusive (hs : list expr) : tactic (list (list expr)) := list.map rb_set.to_list <$> dependency_sets_of_hyps_inclusive hs /-! #### Computing the reverse dependencies of a hypothesis -/ private meta def reverse_dependencies_of_hyp_name_set_aux (hs : name_set) : list expr → list expr → name_set → tactic (list expr) | [] revdeps _ := pure revdeps.reverse | (H :: Hs) revdeps ns := do let H_uname := H.local_uniq_name, H_is_revdep ← list.mband [ pure $ ¬ hs.contains H_uname, hyp_directly_depends_on_local_name_set H ns ], if H_is_revdep then reverse_dependencies_of_hyp_name_set_aux Hs (H :: revdeps) (ns.insert H_uname) else reverse_dependencies_of_hyp_name_set_aux Hs revdeps ns /-- `reverse_dependencies_of_hyp_name_set hs` is the list of reverse dependencies of the hypotheses whose unique names appear in `hs`, excluding the `hs` themselves. The reverse dependencies are returned in the order in which they appear in the context. -/ meta def reverse_dependencies_of_hyp_name_set (hs : name_set) : tactic (list expr) := do ctx ← local_context, let ctx := ctx.after (λ h, hs.contains h.local_uniq_name), reverse_dependencies_of_hyp_name_set_aux hs ctx [] hs /-- `reverse_dependencies_of_hyp_set hs` is the list of reverse dependencies of the hypotheses `hs`, excluding the `hs` themselves. The reverse dependencies are returned in the order in which they appear in the context. -/ meta def reverse_dependencies_of_hyp_set (hs : expr_set) : tactic (list expr) := reverse_dependencies_of_hyp_name_set $ local_set_to_name_set hs /-- `reverse_dependencies_of_hyps hs` is the list of reverse dependencies of the hypotheses `hs`, excluding the `hs` themselves. The reverse dependencies are returned in the order in which they appear in the context. -/ meta def reverse_dependencies_of_hyps (hs : list expr) : tactic (list expr) := reverse_dependencies_of_hyp_name_set $ local_list_to_name_set hs private meta def reverse_dependencies_of_hyp_name_set_inclusive_aux : list expr → list expr → name_set → tactic (list expr) | [] revdeps _ := pure revdeps.reverse | (H :: Hs) revdeps ns := do let H_uname := H.local_uniq_name, H_is_revdep ← list.mbor [ pure $ ns.contains H.local_uniq_name, hyp_directly_depends_on_local_name_set H ns ], if H_is_revdep then reverse_dependencies_of_hyp_name_set_inclusive_aux Hs (H :: revdeps) (ns.insert H_uname) else reverse_dependencies_of_hyp_name_set_inclusive_aux Hs revdeps ns /-- `reverse_dependencies_of_hyp_name_set_inclusive hs` is the list of reverse dependencies of the hypotheses whose unique names appear in `hs`, including the `hs` themselves. The reverse dependencies are returned in the order in which they appear in the context. -/ meta def reverse_dependencies_of_hyp_name_set_inclusive (hs : name_set) : tactic (list expr) := do ctx ← local_context, let ctx := ctx.drop_while (λ h, ¬ hs.contains h.local_uniq_name), reverse_dependencies_of_hyp_name_set_inclusive_aux ctx [] hs /-- `reverse_dependencies_of_hyp_set_inclusive hs` is the list of reverse dependencies of the hypotheses `hs`, including the `hs` themselves. The inclusive reverse dependencies are returned in the order in which they appear in the context. -/ meta def reverse_dependencies_of_hyp_set_inclusive (hs : expr_set) : tactic (list expr) := reverse_dependencies_of_hyp_name_set_inclusive $ local_set_to_name_set hs /-- `reverse_dependencies_of_hyps_inclusive hs` is the list of reverse dependencies of the hypotheses `hs`, including the `hs` themselves. The reverse dependencies are returned in the order in which they appear in the context. -/ meta def reverse_dependencies_of_hyps_inclusive (hs : list expr) : tactic (list expr) := reverse_dependencies_of_hyp_name_set_inclusive $ local_list_to_name_set hs /-! ### Reverting a hypothesis and its reverse dependencies -/ /-- `revert_name_set hs` reverts the hypotheses whose unique names appear in `hs`, as well as any hypotheses that depend on them. Returns the number of reverted hypotheses and a list containing these hypotheses. The reverted hypotheses are returned in the order in which they used to appear in the context and are guaranteed to store the correct type (see `tactic.update_type`). -/ meta def revert_name_set (hs : name_set) : tactic (ℕ × list expr) := do to_revert ← reverse_dependencies_of_hyp_name_set_inclusive hs, to_revert_with_types ← to_revert.mmap update_type, num_reverted ← revert_lst to_revert, pure (num_reverted, to_revert_with_types) /-- `revert_set hs` reverts the hypotheses `hs`, as well as any hypotheses that depend on them. Returns the number of reverted hypotheses and a list containing these hypotheses. The reverted hypotheses are returned in the order in which they used to appear in the context and are guaranteed to store the correct type (see `tactic.update_type`). -/ meta def revert_set (hs : expr_set) : tactic (ℕ × list expr) := revert_name_set $ local_set_to_name_set hs /-- `revert_lst' hs` reverts the hypotheses `hs`, as well as any hypotheses that depend on them. Returns the number of reverted hypotheses and a list containing these hypotheses. The reverted hypotheses are returned in the order in which they used to appear in the context and are guaranteed to store the correct type (see `tactic.update_type`). This is a more informative version of `tactic.revert_lst`. -/ meta def revert_lst' (hs : list expr) : tactic (ℕ × list expr) := revert_name_set $ local_list_to_name_set hs /-- `revert_reverse_dependencies_of_hyp h` reverts all the hypotheses that depend on the hypothesis `h`, including the local definitions that have `h` in their value. This fixes a bug in `tactic.revert_kdependencies` that does not revert local definitions for which `h` only appears in the value. Returns the number of reverted hypotheses. -/ /- We cannot implement it as `revert e >> intro1` because that would change the local constant in the context. -/ meta def revert_reverse_dependencies_of_hyp (h : expr) : tactic ℕ := reverse_dependencies_of_hyp_name_set (mk_name_set.insert h.local_uniq_name) >>= revert_lst /-- `revert_reverse_dependencies_of_hyp_name_set hs` reverts all the hypotheses that depend on a hypothesis whose unique name appears in `hs`. The `hs` themselves are not reverted, unless they depend on each other. Returns the number of reverted hypotheses. -/ meta def revert_reverse_dependencies_of_hyp_name_set (hs : name_set) : tactic ℕ := reverse_dependencies_of_hyp_name_set hs >>= revert_lst /-- `revert_reverse_dependencies_of_hyp_set hs` reverts all the hypotheses that depend on a hypothesis in `hs`. The `hs` themselves are not reverted, unless they depend on each other. Returns the number of reverted hypotheses. -/ meta def revert_reverse_dependencies_of_hyp_set (hs : expr_set) : tactic ℕ := reverse_dependencies_of_hyp_set hs >>= revert_lst /-- `revert_reverse_dependencies_of_hyp hs` reverts all the hypotheses that depend on a hypothesis in `hs`. The `hs` themselves are not reverted, unless they depend on each other. Returns the number of reverted hypotheses. -/ meta def revert_reverse_dependencies_of_hyps (hs : list expr) : tactic ℕ := reverse_dependencies_of_hyps hs >>= revert_lst end tactic
1c0393d5086c430fb660f60b6ec1a93f4380bce7
ef6b7797dbbd7b1dfff69894d190a965b101c5ff
/src/hilbert_props.lean
aa6f172a0734842e65a9c4e04dad7acc248be71b
[]
no_license
utensil-star/leanteach2020
43d57f1b23eded178e2049a0957b7ec38fd4e1a7
93326a5e5b0efeba30d9dc9ee85d52b1029cb24d
refs/heads/master
1,666,413,811,198
1,592,598,394,000
1,592,598,394,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,259
lean
import tactic import .hilbert noncomputable theory open_locale classical local infix ` ≃ `:55 := C -- \ equiv == equivalence/congruence local infix `⬝`:56 := Segment.mk -- \ cdot == center-dot ------------------------------- -- |#Instructions For Hilbert# | ------------------------------- -- Alex: I copied the instructions from the propositions.lean document -- and deleted the ones that didn't pertain to the Hilbert group /- 0. Read these instructions carefully. 1. I have tried my best to translate statements of the propositions into Lean. 2. In place of proofs, I have placed sorry's. 3. Do NOT add your proofs to this file. Create a new file called euclid_props.lean (and hilbert_props.lean) on CoCalc. Copy the statements there and add your proofs to it. 4. You might have to make minor changes to the statement to make it compatible with your syntax. Don't make too many changes though. 5. If you do make a change to the statement, then don't forget to add a note in your hilbert_props.lean file. 6. I am also mentioning missing definitions in this file. You need to define these in your hilbert.lean / euclid.lean source file so that the propositions given here make sense. 7. If you spot some obvious mistakes in the statement of the propositions given below then let me know. You can also ask me for clarifications. 8. This is still an incomplete list and I will keep adding more propositions in this file. -- VK -/ -- If two distinct lines intersect, then they do so in exactly one point. lemma single_intersection (l₁ l₂ : Line) : l₁ ≠ l₂ → intersect_line l₁ l₂ → ∃! x : Point, lies_on_line x l₁ ∧ lies_on_line x l₂ := begin intros h₁ h₂, rw intersect_line at h₂, choose x h₂ using h₂, use x, tidy, symmetry, by_contradiction, have line_exists := line_exists x y a_2, tidy, have h₃ : l₁ = ⟨x, y, a_2⟩, { apply line_unique, assumption, assumption}, have h₄ : l₂ = ⟨x, y, a_2⟩, { apply line_unique, assumption, assumption}, cc, end -- Through any point there exists at least two lines. lemma two_lines (p : Point) : ∃ l₁ l₂ : Line, l₁ ≠ l₂ ∧ lies_on_line p l₁ ∧ lies_on_line p l₂ := begin choose a b c h using no_line_on_three_points, by_cases ha : p ≠ a, by_cases hb : p ≠ b, by_cases hc : p ≠ c, set la : Line := ⟨p, a, ha⟩, set lb : Line := ⟨p, b, hb⟩, set lc : Line := ⟨p, c, hc⟩, by_cases hab : la ≠ lb, use la, use lb, have le := line_exists p a ha, split, assumption, split, exact le.1, have le := line_exists p b hb, exact le.1, simp at hab, by_cases hbc : lb ≠ lc, repeat {sorry}, end -- # Euclid's Proposition 1 --------------------------- -- To construct an equilateral triangle on a given -- finite straight line. theorem prop1 (s : Segment) : ∃ t : Triangle, t.p₁ = s.p₁ ∧ t.p₂ = s.p₂ ∧ equilateral t := begin let a : Point := s.p₁, let b : Point := s.p₂, -- let c : Point := s.p₁ ⬝ c ≃ s.p₂ ⬝ c, -- , sorry, end -- # Euclid's Proposition 2 --------------------------- -- To place a straight line equal to a given straight -- line with one end at a given point. theorem prop2 (s : Segment) (h : s.p₁ ≠ s.p₂): ∃ s' : Segment, s ≃ s' ∧ s'.p₁ = s.p₁ := begin sorry, --let l : Line := line_of_points s.p₁ s.p₂ h, --let y : Line := lies_on_line s.p₁ y, --fapply segment_copy' s.p₁ s.p₂ l s.p₁ y, end -- Proposition 3. To cut off from the greater of two given unequal -- straight lines a straight line equal to the less. -- Assume s₂ < s₁ --theorem prop3 (s₁ s₂ : Segment) (h : s₁.p1 ≠ s₁.p2): -- ∃ x : Point, lies_on_segment x s₁ h ∧ s₁.p1⬝x ≃ s₂ := sorry -- Proposition 4. If two triangles have two sides equal to two sides -- respectively, and have the angles contained by the equal straight -- lines equal, then they also have the base equal to the base, the -- triangle equals the triangle, and the remaining angles equal the -- remaining angles respectively, namely those opposite the equal -- sides. --theorem prop4 (t₁ t₂ : Triangle) : -- t₁.a⬝t₁.b ≃ t₂.a⬝t₂.b -- → t₁.a⬝t₁.c ≃ t₂.a⬝t₂.c -- → (Angle.mk t₁.a {Ray . base:=t₁.a, extension:=t₁.b} {Ray . base:=t₁.a, extension:=t₁.b} rfl rfl) ≃ Angle.mk t₁.a {Ray . base:=t₁.a, extension:=t₁.b} {Ray . base:=t₁.a, extension:=t₁.b} rfl rfl -- → congruent_triangles t₁ t₂ -- := sorry -- Proposition 5. In isosceles triangles the angles at the base equal -- one another, and, if the equal straight lines are produced further, -- then the angles under the base equal one another. theorem prop5_part1 (abc : Triangle) : let sides := sides_of_triangle abc in let angles := angles_of_triangle abc in sides.nth 0 ≃ sides.nth 1 -- a⬝b ≃ b⬝c → angles.nth 0 ≃ angles.nth 2 := begin set a := abc.p₁, set b := abc.p₂, set c := abc.p₃, intros sides angles h, have x : b⬝a ≃ a⬝b, { apply segment_swap}, have ba_bc : b⬝a ≃ b⬝c, { apply C_segment_trans, apply C_segment_symm, exact x, exact h}, have bc_ba : b⬝c ≃ b⬝a, { apply C_segment_symm, exact ba_bc}, have abc_cba : (⟨a, b, c⟩ : Angle) ≃ ⟨c, b, a⟩, by symmetry, have cong_tri := congruent_triangle_SAS b a c b c a ba_bc bc_ba abc_cba, have angles_cong := angles_of_congruent_triangle ⟨b, a, c⟩ ⟨b, c, a⟩ cong_tri, exact angles_cong.2.1, end -- Proposition 6. -- If in a triangle two angles equal one another, then the sides opposite the equal angles also equal one another. -- TODO: Maybe this should be a Theorem? -- Corresponding angles in congruent triangles must be congruent -- May be needed -- ∧ t₁.α₁ ≃ t₂.α₁ -- ∧ t₁.α₂ ≃ t₂.α₂ -- ∧ t₁.α₃ ≃ t₂.α₃ -- # Proposition 6 ------------------ -- If in a triangle two angles equal one another, then the sides -- opposite the equal angles also equal one another. --https://artofproblemsolving.com/wiki/index.php/Base_Angle_Theorem theorem prop_6 (abc : Triangle): let sides := (sides_of_triangle abc) in let angles := (angles_of_triangle abc) in angles.nth 0 ≃ angles.nth 2 → sides.nth 0 ≃ sides.nth 1 := -- bac ≃ bca → ab ≃ bc begin set a := abc.p₁, set b := abc.p₂, set c := abc.p₃, intros sides angles h, -- BAC === BCA or ACB -- sides: ba = ac -- angle: by_contradiction, -- assume ¬ (ab ≃ bc) sorry, end #exit -- Proposition 7. -- -- Given two straight lines constructed from the ends of a straight line and meeting in a point, there cannot be constructed from the ends of the same straight line, and on the same side of it, two other straight lines meeting in another point and equal to the former two respectively, namely each equal to that from the same end. -- Proposition 8. -- If two triangles have the two sides equal to two sides respectively, and also have the base equal to the base, then they also have the angles equal which are contained by the equal straight lines. -- Proposition 9. -- To bisect a given rectilinear angle. theorem prop_9 (a : Angle): ∃ (p : Point), Angle.mk a.ext₁ a.base p ≃ Angle.mk p a.base a.ext₂ -- Proposition 10. -- To bisect a given finite straight line. theorem prop_10 (s : Segment) : ∃ (p : Point), B s.p₁ p s.p₂ ∧ p₁⬝p ≃ p⬝p₂ -- Proposition 11. -- To draw a straight line at right angles to a given straight line from a given point on it. -- Proposition 12. -- To draw a straight line perpendicular to a given infinite straight line from a given point not on it. -- Proposition 13. -- If a straight line stands on a straight line, then it makes either two right angles or angles whose sum equals two right angles. -- Proposition 14. -- If with any straight line, and at a point on it, two straight lines not lying on the same side make the sum of the adjacent angles equal to two right angles, then the two straight lines are in a straight line with one another. -- Proposition 15. -- If two straight lines cut one another, then they make the vertical angles equal to one another. -- Corollary. If two straight lines cut one another, then they will make the angles at the point of section equal to four right angles. -- /- Proposition 16. In any triangle, if one of the sides is produced, then the exterior angle is greater than either of the interior and opposite angles. Proposition 17. In any triangle the sum of any two angles is less than two right angles. Proposition 18. In any triangle the angle opposite the greater side is greater. Proposition 19. In any triangle the side opposite the greater angle is greater. Proposition 20. In any triangle the sum of any two sides is greater than the remaining one. Proposition 21. If from the ends of one of the sides of a triangle two straight lines are constructed meeting within the triangle, then the sum of the straight lines so constructed is less than the sum of the remaining two sides of the triangle, but the constructed straight lines contain a greater angle than the angle contained by the remaining two sides. Proposition 22. To construct a triangle out of three straight lines which equal three given straight lines: thus it is necessary that the sum of any two of the straight lines should be greater than the remaining one. Proposition 23. To construct a rectilinear angle equal to a given rectilinear angle on a given straight line and at a point on it. Proposition 24. If two triangles have two sides equal to two sides respectively, but have one of the angles contained by the equal straight lines greater than the other, then they also have the base greater than the base. Proposition 25. If two triangles have two sides equal to two sides respectively, but have the base greater than the base, then they also have the one of the angles contained by the equal straight lines greater than the other. Proposition 26. If two triangles have two angles equal to two angles respectively, and one side equal to one side, namely, either the side adjoining the equal angles, or that opposite one of the equal angles, then the remaining sides equal the remaining sides and the remaining angle equals the remaining angle. -/ theorem prop26_part1 (t₁ t₂ : Triangle): t₁.α₁ ≃ t₂.α₁ → t₁.α₂ ≃ t₂.α₂ → t₁.s₁₂ ≃ t₂.s₁₂ → congruent t₁ t₂ := begin let G : Point := sorry end /- Proposition 27. If a straight line falling on two straight lines makes the alternate angles equal to one another, then the straight lines are parallel to one another. Proposition 28. If a straight line falling on two straight lines makes the exterior angle equal to the interior and opposite angle on the same side, or the sum of the interior angles on the same side equal to two right angles, then the straight lines are parallel to one another. Proposition 29. A straight line falling on parallel straight lines makes the alternate angles equal to one another, the exterior angle equal to the interior and opposite angle, and the sum of the interior angles on the same side equal to two right angles. Proposition 30. Straight lines parallel to the same straight line are also parallel to one another. -/ theorem prop30 (l₁ l₂ l₃ : Line): parallel_lines l₁ l₂ → parallel_lines l₁ l₃ → parallel_lines l₂ l₃ /-Proposition 31. To draw a straight line through a given point parallel to a given straight line. -/ theorem prop31 (l : Line) (p: Point) (h: ¬lies_on_line p l): ∃ (l' : Line), lies_on_line p l' ∧ parallel_lines l l' := begin /-split, split, let l' := Line, use l', choose l' using parallel_postulate,-/ sorry, end /-Proposition 32. In any triangle, if one of the sides is produced, then the exterior angle equals the sum of the two interior and opposite angles, and the sum of the three interior angles of the triangle equals two right angles. Proposition 33. Straight lines which join the ends of equal and parallel straight lines in the same directions are themselves equal and parallel. Proposition 34. In parallelogrammic areas the opposite sides and angles equal one another, and the diameter bisects the areas. Proposition 35. Parallelograms which are on the same base and in the same parallels equal one another. Proposition 36. Parallelograms which are on equal bases and in the same parallels equal one another. Proposition 37. Triangles which are on the same base and in the same parallels equal one another. Proposition 38. Triangles which are on equal bases and in the same parallels equal one another. Proposition 39. Equal triangles which are on the same base and on the same side are also in the same parallels. Proposition 40. Equal triangles which are on equal bases and on the same side are also in the same parallels. Proposition 41. If a parallelogram has the same base with a triangle and is in the same parallels, then the parallelogram is double the triangle. Proposition 42. To construct a parallelogram equal to a given triangle in a given rectilinear angle. Proposition 43. In any parallelogram the complements of the parallelograms about the diameter equal one another. Proposition 44. To a given straight line in a given rectilinear angle, to apply a parallelogram equal to a given triangle. Proposition 45. To construct a parallelogram equal to a given rectilinear figure in a given rectilinear angle. Proposition 46. To describe a square on a given straight line. Proposition 47. In right-angled triangles the square on the side opposite the right angle equals the sum of the squares on the sides containing the right angle. Proposition 48. If in a triangle the square on one of the sides equals the sum of the squares on the remaining two sides of the triangle, then the angle contained by the remaining two sides of the triangle is right. -/
8208050ff16bb4639345e7251b0894361fad6a0f
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/probability/process/stopping.lean
cec8a181ef003823eac59b8e4dc13ad367c335e1
[ "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
54,329
lean
/- Copyright (c) 2021 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying, Rémy Degenne -/ import probability.process.adapted /-! # Stopping times, stopped processes and stopped values > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Definition and properties of stopping times. ## Main definitions * `measure_theory.is_stopping_time`: a stopping time with respect to some filtration `f` is a function `τ` such that for all `i`, the preimage of `{j | j ≤ i}` along `τ` is `f i`-measurable * `measure_theory.is_stopping_time.measurable_space`: the σ-algebra associated with a stopping time ## Main results * `prog_measurable.stopped_process`: the stopped process of a progressively measurable process is progressively measurable. * `mem_ℒp_stopped_process`: if a process belongs to `ℒp` at every time in `ℕ`, then its stopped process belongs to `ℒp` as well. ## Tags stopping time, stochastic process -/ open filter order topological_space open_locale classical measure_theory nnreal ennreal topology big_operators namespace measure_theory variables {Ω β ι : Type*} {m : measurable_space Ω} /-! ### Stopping times -/ /-- A stopping time with respect to some filtration `f` is a function `τ` such that for all `i`, the preimage of `{j | j ≤ i}` along `τ` is measurable with respect to `f i`. Intuitively, the stopping time `τ` describes some stopping rule such that at time `i`, we may determine it with the information we have at time `i`. -/ def is_stopping_time [preorder ι] (f : filtration ι m) (τ : Ω → ι) := ∀ i : ι, measurable_set[f i] $ {ω | τ ω ≤ i} lemma is_stopping_time_const [preorder ι] (f : filtration ι m) (i : ι) : is_stopping_time f (λ ω, i) := λ j, by simp only [measurable_set.const] section measurable_set section preorder variables [preorder ι] {f : filtration ι m} {τ : Ω → ι} protected lemma is_stopping_time.measurable_set_le (hτ : is_stopping_time f τ) (i : ι) : measurable_set[f i] {ω | τ ω ≤ i} := hτ i lemma is_stopping_time.measurable_set_lt_of_pred [pred_order ι] (hτ : is_stopping_time f τ) (i : ι) : measurable_set[f i] {ω | τ ω < i} := begin by_cases hi_min : is_min i, { suffices : {ω : Ω | τ ω < i} = ∅, by { rw this, exact @measurable_set.empty _ (f i), }, ext1 ω, simp only [set.mem_set_of_eq, set.mem_empty_iff_false, iff_false], rw is_min_iff_forall_not_lt at hi_min, exact hi_min (τ ω), }, have : {ω : Ω | τ ω < i} = τ ⁻¹' (set.Iio i) := rfl, rw [this, ←Iic_pred_of_not_is_min hi_min], exact f.mono (pred_le i) _ (hτ.measurable_set_le $ pred i), end end preorder section countable_stopping_time namespace is_stopping_time variables [partial_order ι] {τ : Ω → ι} {f : filtration ι m} protected lemma measurable_set_eq_of_countable_range (hτ : is_stopping_time f τ) (h_countable : (set.range τ).countable) (i : ι) : measurable_set[f i] {ω | τ ω = i} := begin have : {ω | τ ω = i} = {ω | τ ω ≤ i} \ (⋃ (j ∈ set.range τ) (hj : j < i), {ω | τ ω ≤ j}), { ext1 a, simp only [set.mem_set_of_eq, set.mem_range, set.Union_exists, set.Union_Union_eq', set.mem_diff, set.mem_Union, exists_prop, not_exists, not_and, not_le], split; intro h, { simp only [h, lt_iff_le_not_le, le_refl, and_imp, imp_self, implies_true_iff, and_self], }, { have h_lt_or_eq : τ a < i ∨ τ a = i := lt_or_eq_of_le h.1, rcases h_lt_or_eq with h_lt | rfl, { exfalso, exact h.2 a h_lt (le_refl (τ a)), }, { refl, }, }, }, rw this, refine (hτ.measurable_set_le i).diff _, refine measurable_set.bUnion h_countable (λ j hj, _), by_cases hji : j < i, { simp only [hji, set.Union_true], exact f.mono hji.le _ (hτ.measurable_set_le j), }, { simp only [hji, set.Union_false], exact @measurable_set.empty _ (f i), }, end protected lemma measurable_set_eq_of_countable [countable ι] (hτ : is_stopping_time f τ) (i : ι) : measurable_set[f i] {ω | τ ω = i} := hτ.measurable_set_eq_of_countable_range (set.to_countable _) i protected lemma measurable_set_lt_of_countable_range (hτ : is_stopping_time f τ) (h_countable : (set.range τ).countable) (i : ι) : measurable_set[f i] {ω | τ ω < i} := begin have : {ω | τ ω < i} = {ω | τ ω ≤ i} \ {ω | τ ω = i}, { ext1 ω, simp [lt_iff_le_and_ne], }, rw this, exact (hτ.measurable_set_le i).diff (hτ.measurable_set_eq_of_countable_range h_countable i), end protected lemma measurable_set_lt_of_countable [countable ι] (hτ : is_stopping_time f τ) (i : ι) : measurable_set[f i] {ω | τ ω < i} := hτ.measurable_set_lt_of_countable_range (set.to_countable _) i protected lemma measurable_set_ge_of_countable_range {ι} [linear_order ι] {τ : Ω → ι} {f : filtration ι m} (hτ : is_stopping_time f τ) (h_countable : (set.range τ).countable) (i : ι) : measurable_set[f i] {ω | i ≤ τ ω} := begin have : {ω | i ≤ τ ω} = {ω | τ ω < i}ᶜ, { ext1 ω, simp only [set.mem_set_of_eq, set.mem_compl_iff, not_lt], }, rw this, exact (hτ.measurable_set_lt_of_countable_range h_countable i).compl, end protected lemma measurable_set_ge_of_countable {ι} [linear_order ι] {τ : Ω → ι} {f : filtration ι m} [countable ι] (hτ : is_stopping_time f τ) (i : ι) : measurable_set[f i] {ω | i ≤ τ ω} := hτ.measurable_set_ge_of_countable_range (set.to_countable _) i end is_stopping_time end countable_stopping_time section linear_order variables [linear_order ι] {f : filtration ι m} {τ : Ω → ι} lemma is_stopping_time.measurable_set_gt (hτ : is_stopping_time f τ) (i : ι) : measurable_set[f i] {ω | i < τ ω} := begin have : {ω | i < τ ω} = {ω | τ ω ≤ i}ᶜ, { ext1 ω, simp only [set.mem_set_of_eq, set.mem_compl_iff, not_le], }, rw this, exact (hτ.measurable_set_le i).compl, end section topological_space variables [topological_space ι] [order_topology ι] [first_countable_topology ι] /-- Auxiliary lemma for `is_stopping_time.measurable_set_lt`. -/ lemma is_stopping_time.measurable_set_lt_of_is_lub (hτ : is_stopping_time f τ) (i : ι) (h_lub : is_lub (set.Iio i) i) : measurable_set[f i] {ω | τ ω < i} := begin by_cases hi_min : is_min i, { suffices : {ω | τ ω < i} = ∅, by { rw this, exact @measurable_set.empty _ (f i), }, ext1 ω, simp only [set.mem_set_of_eq, set.mem_empty_iff_false, iff_false], exact is_min_iff_forall_not_lt.mp hi_min (τ ω), }, obtain ⟨seq, -, -, h_tendsto, h_bound⟩ : ∃ seq : ℕ → ι, monotone seq ∧ (∀ j, seq j ≤ i) ∧ tendsto seq at_top (𝓝 i) ∧ (∀ j, seq j < i), from h_lub.exists_seq_monotone_tendsto (not_is_min_iff.mp hi_min), have h_Ioi_eq_Union : set.Iio i = ⋃ j, {k | k ≤ seq j}, { ext1 k, simp only [set.mem_Iio, set.mem_Union, set.mem_set_of_eq], refine ⟨λ hk_lt_i, _, λ h_exists_k_le_seq, _⟩, { rw tendsto_at_top' at h_tendsto, have h_nhds : set.Ici k ∈ 𝓝 i, from mem_nhds_iff.mpr ⟨set.Ioi k, set.Ioi_subset_Ici le_rfl, is_open_Ioi, hk_lt_i⟩, obtain ⟨a, ha⟩ : ∃ (a : ℕ), ∀ (b : ℕ), b ≥ a → k ≤ seq b := h_tendsto (set.Ici k) h_nhds, exact ⟨a, ha a le_rfl⟩, }, { obtain ⟨j, hk_seq_j⟩ := h_exists_k_le_seq, exact hk_seq_j.trans_lt (h_bound j), }, }, have h_lt_eq_preimage : {ω | τ ω < i} = τ ⁻¹' (set.Iio i), { ext1 ω, simp only [set.mem_set_of_eq, set.mem_preimage, set.mem_Iio], }, rw [h_lt_eq_preimage, h_Ioi_eq_Union], simp only [set.preimage_Union, set.preimage_set_of_eq], exact measurable_set.Union (λ n, f.mono (h_bound n).le _ (hτ.measurable_set_le (seq n))), end lemma is_stopping_time.measurable_set_lt (hτ : is_stopping_time f τ) (i : ι) : measurable_set[f i] {ω | τ ω < i} := begin obtain ⟨i', hi'_lub⟩ : ∃ i', is_lub (set.Iio i) i', from exists_lub_Iio i, cases lub_Iio_eq_self_or_Iio_eq_Iic i hi'_lub with hi'_eq_i h_Iio_eq_Iic, { rw ← hi'_eq_i at hi'_lub ⊢, exact hτ.measurable_set_lt_of_is_lub i' hi'_lub, }, { have h_lt_eq_preimage : {ω : Ω | τ ω < i} = τ ⁻¹' (set.Iio i) := rfl, rw [h_lt_eq_preimage, h_Iio_eq_Iic], exact f.mono (lub_Iio_le i hi'_lub) _ (hτ.measurable_set_le i'), }, end lemma is_stopping_time.measurable_set_ge (hτ : is_stopping_time f τ) (i : ι) : measurable_set[f i] {ω | i ≤ τ ω} := begin have : {ω | i ≤ τ ω} = {ω | τ ω < i}ᶜ, { ext1 ω, simp only [set.mem_set_of_eq, set.mem_compl_iff, not_lt], }, rw this, exact (hτ.measurable_set_lt i).compl, end lemma is_stopping_time.measurable_set_eq (hτ : is_stopping_time f τ) (i : ι) : measurable_set[f i] {ω | τ ω = i} := begin have : {ω | τ ω = i} = {ω | τ ω ≤ i} ∩ {ω | τ ω ≥ i}, { ext1 ω, simp only [set.mem_set_of_eq, ge_iff_le, set.mem_inter_iff, le_antisymm_iff], }, rw this, exact (hτ.measurable_set_le i).inter (hτ.measurable_set_ge i), end lemma is_stopping_time.measurable_set_eq_le (hτ : is_stopping_time f τ) {i j : ι} (hle : i ≤ j) : measurable_set[f j] {ω | τ ω = i} := f.mono hle _ $ hτ.measurable_set_eq i lemma is_stopping_time.measurable_set_lt_le (hτ : is_stopping_time f τ) {i j : ι} (hle : i ≤ j) : measurable_set[f j] {ω | τ ω < i} := f.mono hle _ $ hτ.measurable_set_lt i end topological_space end linear_order section countable lemma is_stopping_time_of_measurable_set_eq [preorder ι] [countable ι] {f : filtration ι m} {τ : Ω → ι} (hτ : ∀ i, measurable_set[f i] {ω | τ ω = i}) : is_stopping_time f τ := begin intro i, rw show {ω | τ ω ≤ i} = ⋃ k ≤ i, {ω | τ ω = k}, by { ext, simp }, refine measurable_set.bUnion (set.to_countable _) (λ k hk, _), exact f.mono hk _ (hτ k), end end countable end measurable_set namespace is_stopping_time protected lemma max [linear_order ι] {f : filtration ι m} {τ π : Ω → ι} (hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) : is_stopping_time f (λ ω, max (τ ω) (π ω)) := begin intro i, simp_rw [max_le_iff, set.set_of_and], exact (hτ i).inter (hπ i), end protected lemma max_const [linear_order ι] {f : filtration ι m} {τ : Ω → ι} (hτ : is_stopping_time f τ) (i : ι) : is_stopping_time f (λ ω, max (τ ω) i) := hτ.max (is_stopping_time_const f i) protected lemma min [linear_order ι] {f : filtration ι m} {τ π : Ω → ι} (hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) : is_stopping_time f (λ ω, min (τ ω) (π ω)) := begin intro i, simp_rw [min_le_iff, set.set_of_or], exact (hτ i).union (hπ i), end protected lemma min_const [linear_order ι] {f : filtration ι m} {τ : Ω → ι} (hτ : is_stopping_time f τ) (i : ι) : is_stopping_time f (λ ω, min (τ ω) i) := hτ.min (is_stopping_time_const f i) lemma add_const [add_group ι] [preorder ι] [covariant_class ι ι (function.swap (+)) (≤)] [covariant_class ι ι (+) (≤)] {f : filtration ι m} {τ : Ω → ι} (hτ : is_stopping_time f τ) {i : ι} (hi : 0 ≤ i) : is_stopping_time f (λ ω, τ ω + i) := begin intro j, simp_rw [← le_sub_iff_add_le], exact f.mono (sub_le_self j hi) _ (hτ (j - i)), end lemma add_const_nat {f : filtration ℕ m} {τ : Ω → ℕ} (hτ : is_stopping_time f τ) {i : ℕ} : is_stopping_time f (λ ω, τ ω + i) := begin refine is_stopping_time_of_measurable_set_eq (λ j, _), by_cases hij : i ≤ j, { simp_rw [eq_comm, ← nat.sub_eq_iff_eq_add hij, eq_comm], exact f.mono (j.sub_le i) _ (hτ.measurable_set_eq (j - i)) }, { rw not_le at hij, convert measurable_set.empty, ext ω, simp only [set.mem_empty_iff_false, iff_false], rintro (hx : τ ω + i = j), linarith }, end -- generalize to certain countable type? lemma add {f : filtration ℕ m} {τ π : Ω → ℕ} (hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) : is_stopping_time f (τ + π) := begin intro i, rw (_ : {ω | (τ + π) ω ≤ i} = ⋃ k ≤ i, {ω | π ω = k} ∩ {ω | τ ω + k ≤ i}), { exact measurable_set.Union (λ k, measurable_set.Union (λ hk, (hπ.measurable_set_eq_le hk).inter (hτ.add_const_nat i))) }, ext ω, simp only [pi.add_apply, set.mem_set_of_eq, set.mem_Union, set.mem_inter_iff, exists_prop], refine ⟨λ h, ⟨π ω, by linarith, rfl, h⟩, _⟩, rintro ⟨j, hj, rfl, h⟩, assumption end section preorder variables [preorder ι] {f : filtration ι m} {τ π : Ω → ι} /-- The associated σ-algebra with a stopping time. -/ protected def measurable_space (hτ : is_stopping_time f τ) : measurable_space Ω := { measurable_set' := λ s, ∀ i : ι, measurable_set[f i] (s ∩ {ω | τ ω ≤ i}), measurable_set_empty := λ i, (set.empty_inter {ω | τ ω ≤ i}).symm ▸ @measurable_set.empty _ (f i), measurable_set_compl := λ s hs i, begin rw (_ : sᶜ ∩ {ω | τ ω ≤ i} = (sᶜ ∪ {ω | τ ω ≤ i}ᶜ) ∩ {ω | τ ω ≤ i}), { refine measurable_set.inter _ _, { rw ← set.compl_inter, exact (hs i).compl }, { exact hτ i} }, { rw set.union_inter_distrib_right, simp only [set.compl_inter_self, set.union_empty] } end, measurable_set_Union := λ s hs i, begin rw forall_swap at hs, rw set.Union_inter, exact measurable_set.Union (hs i), end } protected lemma measurable_set (hτ : is_stopping_time f τ) (s : set Ω) : measurable_set[hτ.measurable_space] s ↔ ∀ i : ι, measurable_set[f i] (s ∩ {ω | τ ω ≤ i}) := iff.rfl lemma measurable_space_mono (hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) (hle : τ ≤ π) : hτ.measurable_space ≤ hπ.measurable_space := begin intros s hs i, rw (_ : s ∩ {ω | π ω ≤ i} = s ∩ {ω | τ ω ≤ i} ∩ {ω | π ω ≤ i}), { exact (hs i).inter (hπ i) }, { ext, simp only [set.mem_inter_iff, iff_self_and, and.congr_left_iff, set.mem_set_of_eq], intros hle' _, exact le_trans (hle _) hle' }, end lemma measurable_space_le_of_countable [countable ι] (hτ : is_stopping_time f τ) : hτ.measurable_space ≤ m := begin intros s hs, change ∀ i, measurable_set[f i] (s ∩ {ω | τ ω ≤ i}) at hs, rw (_ : s = ⋃ i, s ∩ {ω | τ ω ≤ i}), { exact measurable_set.Union (λ i, f.le i _ (hs i)) }, { ext ω, split; rw set.mem_Union, { exact λ hx, ⟨τ ω, hx, le_rfl⟩ }, { rintro ⟨_, hx, _⟩, exact hx } } end lemma measurable_space_le' [is_countably_generated (at_top : filter ι)] [(at_top : filter ι).ne_bot] (hτ : is_stopping_time f τ) : hτ.measurable_space ≤ m := begin intros s hs, change ∀ i, measurable_set[f i] (s ∩ {ω | τ ω ≤ i}) at hs, obtain ⟨seq : ℕ → ι, h_seq_tendsto⟩ := at_top.exists_seq_tendsto, rw (_ : s = ⋃ n, s ∩ {ω | τ ω ≤ seq n}), { exact measurable_set.Union (λ i, f.le (seq i) _ (hs (seq i))), }, { ext ω, split; rw set.mem_Union, { intros hx, suffices : ∃ i, τ ω ≤ seq i, from ⟨this.some, hx, this.some_spec⟩, rw tendsto_at_top at h_seq_tendsto, exact (h_seq_tendsto (τ ω)).exists, }, { rintro ⟨_, hx, _⟩, exact hx }, }, all_goals { apply_instance, }, end lemma measurable_space_le {ι} [semilattice_sup ι] {f : filtration ι m} {τ : Ω → ι} [is_countably_generated (at_top : filter ι)] (hτ : is_stopping_time f τ) : hτ.measurable_space ≤ m := begin casesI is_empty_or_nonempty ι, { haveI : is_empty Ω := ⟨λ ω, is_empty.false (τ ω)⟩, intros s hsτ, suffices hs : s = ∅, by { rw hs, exact measurable_set.empty, }, haveI : unique (set Ω) := set.unique_empty, rw [unique.eq_default s, unique.eq_default ∅], }, exact measurable_space_le' hτ, end example {f : filtration ℕ m} {τ : Ω → ℕ} (hτ : is_stopping_time f τ) : hτ.measurable_space ≤ m := hτ.measurable_space_le example {f : filtration ℝ m} {τ : Ω → ℝ} (hτ : is_stopping_time f τ) : hτ.measurable_space ≤ m := hτ.measurable_space_le @[simp] lemma measurable_space_const (f : filtration ι m) (i : ι) : (is_stopping_time_const f i).measurable_space = f i := begin ext1 s, change measurable_set[(is_stopping_time_const f i).measurable_space] s ↔ measurable_set[f i] s, rw is_stopping_time.measurable_set, split; intro h, { specialize h i, simpa only [le_refl, set.set_of_true, set.inter_univ] using h, }, { intro j, by_cases hij : i ≤ j, { simp only [hij, set.set_of_true, set.inter_univ], exact f.mono hij _ h, }, { simp only [hij, set.set_of_false, set.inter_empty, measurable_set.empty], }, }, end lemma measurable_set_inter_eq_iff (hτ : is_stopping_time f τ) (s : set Ω) (i : ι) : measurable_set[hτ.measurable_space] (s ∩ {ω | τ ω = i}) ↔ measurable_set[f i] (s ∩ {ω | τ ω = i}) := begin have : ∀ j, ({ω : Ω | τ ω = i} ∩ {ω : Ω | τ ω ≤ j}) = {ω : Ω | τ ω = i} ∩ {ω | i ≤ j}, { intro j, ext1 ω, simp only [set.mem_inter_iff, set.mem_set_of_eq, and.congr_right_iff], intro hxi, rw hxi, }, split; intro h, { specialize h i, simpa only [set.inter_assoc, this, le_refl, set.set_of_true, set.inter_univ] using h, }, { intro j, rw [set.inter_assoc, this], by_cases hij : i ≤ j, { simp only [hij, set.set_of_true, set.inter_univ], exact f.mono hij _ h, }, { simp [hij], }, }, end lemma measurable_space_le_of_le_const (hτ : is_stopping_time f τ) {i : ι} (hτ_le : ∀ ω, τ ω ≤ i) : hτ.measurable_space ≤ f i := (measurable_space_mono hτ _ hτ_le).trans (measurable_space_const _ _).le lemma measurable_space_le_of_le (hτ : is_stopping_time f τ) {n : ι} (hτ_le : ∀ ω, τ ω ≤ n) : hτ.measurable_space ≤ m := (hτ.measurable_space_le_of_le_const hτ_le).trans (f.le n) lemma le_measurable_space_of_const_le (hτ : is_stopping_time f τ) {i : ι} (hτ_le : ∀ ω, i ≤ τ ω) : f i ≤ hτ.measurable_space := (measurable_space_const _ _).symm.le.trans (measurable_space_mono _ hτ hτ_le) end preorder instance sigma_finite_stopping_time {ι} [semilattice_sup ι] [order_bot ι] [(filter.at_top : filter ι).is_countably_generated] {μ : measure Ω} {f : filtration ι m} {τ : Ω → ι} [sigma_finite_filtration μ f] (hτ : is_stopping_time f τ) : sigma_finite (μ.trim hτ.measurable_space_le) := begin refine sigma_finite_trim_mono hτ.measurable_space_le _, { exact f ⊥, }, { exact hτ.le_measurable_space_of_const_le (λ _, bot_le), }, { apply_instance, }, end instance sigma_finite_stopping_time_of_le {ι} [semilattice_sup ι] [order_bot ι] {μ : measure Ω} {f : filtration ι m} {τ : Ω → ι} [sigma_finite_filtration μ f] (hτ : is_stopping_time f τ) {n : ι} (hτ_le : ∀ ω, τ ω ≤ n) : sigma_finite (μ.trim (hτ.measurable_space_le_of_le hτ_le)) := begin refine sigma_finite_trim_mono (hτ.measurable_space_le_of_le hτ_le) _, { exact f ⊥, }, { exact hτ.le_measurable_space_of_const_le (λ _, bot_le), }, { apply_instance, }, end section linear_order variables [linear_order ι] {f : filtration ι m} {τ π : Ω → ι} protected lemma measurable_set_le' (hτ : is_stopping_time f τ) (i : ι) : measurable_set[hτ.measurable_space] {ω | τ ω ≤ i} := begin intro j, have : {ω : Ω | τ ω ≤ i} ∩ {ω : Ω | τ ω ≤ j} = {ω : Ω | τ ω ≤ min i j}, { ext1 ω, simp only [set.mem_inter_iff, set.mem_set_of_eq, le_min_iff], }, rw this, exact f.mono (min_le_right i j) _ (hτ _), end protected lemma measurable_set_gt' (hτ : is_stopping_time f τ) (i : ι) : measurable_set[hτ.measurable_space] {ω | i < τ ω} := begin have : {ω : Ω | i < τ ω} = {ω : Ω | τ ω ≤ i}ᶜ, by { ext1 ω, simp, }, rw this, exact (hτ.measurable_set_le' i).compl, end protected lemma measurable_set_eq' [topological_space ι] [order_topology ι] [first_countable_topology ι] (hτ : is_stopping_time f τ) (i : ι) : measurable_set[hτ.measurable_space] {ω | τ ω = i} := begin rw [← set.univ_inter {ω | τ ω = i}, measurable_set_inter_eq_iff, set.univ_inter], exact hτ.measurable_set_eq i, end protected lemma measurable_set_ge' [topological_space ι] [order_topology ι] [first_countable_topology ι] (hτ : is_stopping_time f τ) (i : ι) : measurable_set[hτ.measurable_space] {ω | i ≤ τ ω} := begin have : {ω | i ≤ τ ω} = {ω | τ ω = i} ∪ {ω | i < τ ω}, { ext1 ω, simp only [le_iff_lt_or_eq, set.mem_set_of_eq, set.mem_union], rw [@eq_comm _ i, or_comm], }, rw this, exact (hτ.measurable_set_eq' i).union (hτ.measurable_set_gt' i), end protected lemma measurable_set_lt' [topological_space ι] [order_topology ι] [first_countable_topology ι] (hτ : is_stopping_time f τ) (i : ι) : measurable_set[hτ.measurable_space] {ω | τ ω < i} := begin have : {ω | τ ω < i} = {ω | τ ω ≤ i} \ {ω | τ ω = i}, { ext1 ω, simp only [lt_iff_le_and_ne, set.mem_set_of_eq, set.mem_diff], }, rw this, exact (hτ.measurable_set_le' i).diff (hτ.measurable_set_eq' i), end section countable protected lemma measurable_set_eq_of_countable_range' (hτ : is_stopping_time f τ) (h_countable : (set.range τ).countable) (i : ι) : measurable_set[hτ.measurable_space] {ω | τ ω = i} := begin rw [← set.univ_inter {ω | τ ω = i}, measurable_set_inter_eq_iff, set.univ_inter], exact hτ.measurable_set_eq_of_countable_range h_countable i, end protected lemma measurable_set_eq_of_countable' [countable ι] (hτ : is_stopping_time f τ) (i : ι) : measurable_set[hτ.measurable_space] {ω | τ ω = i} := hτ.measurable_set_eq_of_countable_range' (set.to_countable _) i protected lemma measurable_set_ge_of_countable_range' (hτ : is_stopping_time f τ) (h_countable : (set.range τ).countable) (i : ι) : measurable_set[hτ.measurable_space] {ω | i ≤ τ ω} := begin have : {ω | i ≤ τ ω} = {ω | τ ω = i} ∪ {ω | i < τ ω}, { ext1 ω, simp only [le_iff_lt_or_eq, set.mem_set_of_eq, set.mem_union], rw [@eq_comm _ i, or_comm], }, rw this, exact (hτ.measurable_set_eq_of_countable_range' h_countable i).union (hτ.measurable_set_gt' i), end protected lemma measurable_set_ge_of_countable' [countable ι] (hτ : is_stopping_time f τ) (i : ι) : measurable_set[hτ.measurable_space] {ω | i ≤ τ ω} := hτ.measurable_set_ge_of_countable_range' (set.to_countable _) i protected lemma measurable_set_lt_of_countable_range' (hτ : is_stopping_time f τ) (h_countable : (set.range τ).countable) (i : ι) : measurable_set[hτ.measurable_space] {ω | τ ω < i} := begin have : {ω | τ ω < i} = {ω | τ ω ≤ i} \ {ω | τ ω = i}, { ext1 ω, simp only [lt_iff_le_and_ne, set.mem_set_of_eq, set.mem_diff], }, rw this, exact (hτ.measurable_set_le' i).diff (hτ.measurable_set_eq_of_countable_range' h_countable i), end protected lemma measurable_set_lt_of_countable' [countable ι] (hτ : is_stopping_time f τ) (i : ι) : measurable_set[hτ.measurable_space] {ω | τ ω < i} := hτ.measurable_set_lt_of_countable_range' (set.to_countable _) i protected lemma measurable_space_le_of_countable_range (hτ : is_stopping_time f τ) (h_countable : (set.range τ).countable) : hτ.measurable_space ≤ m := begin intros s hs, change ∀ i, measurable_set[f i] (s ∩ {ω | τ ω ≤ i}) at hs, rw (_ : s = ⋃ (i ∈ set.range τ), s ∩ {ω | τ ω ≤ i}), { exact measurable_set.bUnion h_countable (λ i _, f.le i _ (hs i)), }, { ext ω, split; rw set.mem_Union, { exact λ hx, ⟨τ ω, by simpa using hx⟩,}, { rintro ⟨i, hx⟩, simp only [set.mem_range, set.Union_exists, set.mem_Union, set.mem_inter_iff, set.mem_set_of_eq, exists_prop, exists_and_distrib_right] at hx, exact hx.1.2, } } end end countable protected lemma measurable [topological_space ι] [measurable_space ι] [borel_space ι] [order_topology ι] [second_countable_topology ι] (hτ : is_stopping_time f τ) : measurable[hτ.measurable_space] τ := @measurable_of_Iic ι Ω _ _ _ hτ.measurable_space _ _ _ _ (λ i, hτ.measurable_set_le' i) protected lemma measurable_of_le [topological_space ι] [measurable_space ι] [borel_space ι] [order_topology ι] [second_countable_topology ι] (hτ : is_stopping_time f τ) {i : ι} (hτ_le : ∀ ω, τ ω ≤ i) : measurable[f i] τ := hτ.measurable.mono (measurable_space_le_of_le_const _ hτ_le) le_rfl lemma measurable_space_min (hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) : (hτ.min hπ).measurable_space = hτ.measurable_space ⊓ hπ.measurable_space := begin refine le_antisymm _ _, { exact le_inf (measurable_space_mono _ hτ (λ _, min_le_left _ _)) (measurable_space_mono _ hπ (λ _, min_le_right _ _)), }, { intro s, change measurable_set[hτ.measurable_space] s ∧ measurable_set[hπ.measurable_space] s → measurable_set[(hτ.min hπ).measurable_space] s, simp_rw is_stopping_time.measurable_set, have : ∀ i, {ω | min (τ ω) (π ω) ≤ i} = {ω | τ ω ≤ i} ∪ {ω | π ω ≤ i}, { intro i, ext1 ω, simp, }, simp_rw [this, set.inter_union_distrib_left], exact λ h i, (h.left i).union (h.right i), }, end lemma measurable_set_min_iff (hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) (s : set Ω) : measurable_set[(hτ.min hπ).measurable_space] s ↔ measurable_set[hτ.measurable_space] s ∧ measurable_set[hπ.measurable_space] s := by { rw measurable_space_min, refl, } lemma measurable_space_min_const (hτ : is_stopping_time f τ) {i : ι} : (hτ.min_const i).measurable_space = hτ.measurable_space ⊓ f i := by rw [hτ.measurable_space_min (is_stopping_time_const _ i), measurable_space_const] lemma measurable_set_min_const_iff (hτ : is_stopping_time f τ) (s : set Ω) {i : ι} : measurable_set[(hτ.min_const i).measurable_space] s ↔ measurable_set[hτ.measurable_space] s ∧ measurable_set[f i] s := by rw [measurable_space_min_const, measurable_space.measurable_set_inf] lemma measurable_set_inter_le [topological_space ι] [second_countable_topology ι] [order_topology ι] [measurable_space ι] [borel_space ι] (hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) (s : set Ω) (hs : measurable_set[hτ.measurable_space] s) : measurable_set[(hτ.min hπ).measurable_space] (s ∩ {ω | τ ω ≤ π ω}) := begin simp_rw is_stopping_time.measurable_set at ⊢ hs, intro i, have : (s ∩ {ω | τ ω ≤ π ω} ∩ {ω | min (τ ω) (π ω) ≤ i}) = (s ∩ {ω | τ ω ≤ i}) ∩ {ω | min (τ ω) (π ω) ≤ i} ∩ {ω | min (τ ω) i ≤ min (min (τ ω) (π ω)) i}, { ext1 ω, simp only [min_le_iff, set.mem_inter_iff, set.mem_set_of_eq, le_min_iff, le_refl, true_and, and_true, true_or, or_true], by_cases hτi : τ ω ≤ i, { simp only [hτi, true_or, and_true, and.congr_right_iff], intro hx, split; intro h, { exact or.inl h, }, { cases h, { exact h, }, { exact hτi.trans h, }, }, }, simp only [hτi, false_or, and_false, false_and, iff_false, not_and, not_le, and_imp], refine λ hx hτ_le_π, lt_of_lt_of_le _ hτ_le_π, rw ← not_le, exact hτi, }, rw this, refine ((hs i).inter ((hτ.min hπ) i)).inter _, apply measurable_set_le, { exact (hτ.min_const i).measurable_of_le (λ _, min_le_right _ _), }, { exact ((hτ.min hπ).min_const i).measurable_of_le (λ _, min_le_right _ _), }, end lemma measurable_set_inter_le_iff [topological_space ι] [second_countable_topology ι] [order_topology ι] [measurable_space ι] [borel_space ι] (hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) (s : set Ω) : measurable_set[hτ.measurable_space] (s ∩ {ω | τ ω ≤ π ω}) ↔ measurable_set[(hτ.min hπ).measurable_space] (s ∩ {ω | τ ω ≤ π ω}) := begin split; intro h, { have : s ∩ {ω | τ ω ≤ π ω} = s ∩ {ω | τ ω ≤ π ω} ∩ {ω | τ ω ≤ π ω}, by rw [set.inter_assoc, set.inter_self], rw this, exact measurable_set_inter_le _ _ _ h, }, { rw measurable_set_min_iff at h, exact h.1, }, end lemma measurable_set_inter_le_const_iff (hτ : is_stopping_time f τ) (s : set Ω) (i : ι) : measurable_set[hτ.measurable_space] (s ∩ {ω | τ ω ≤ i}) ↔ measurable_set[(hτ.min_const i).measurable_space] (s ∩ {ω | τ ω ≤ i}) := begin rw [is_stopping_time.measurable_set_min_iff hτ (is_stopping_time_const _ i), is_stopping_time.measurable_space_const, is_stopping_time.measurable_set], refine ⟨λ h, ⟨h, _⟩, λ h j, h.1 j⟩, specialize h i, rwa [set.inter_assoc, set.inter_self] at h, end lemma measurable_set_le_stopping_time [topological_space ι] [second_countable_topology ι] [order_topology ι] [measurable_space ι] [borel_space ι] (hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) : measurable_set[hτ.measurable_space] {ω | τ ω ≤ π ω} := begin rw hτ.measurable_set, intro j, have : {ω | τ ω ≤ π ω} ∩ {ω | τ ω ≤ j} = {ω | min (τ ω) j ≤ min (π ω) j} ∩ {ω | τ ω ≤ j}, { ext1 ω, simp only [set.mem_inter_iff, set.mem_set_of_eq, min_le_iff, le_min_iff, le_refl, and_true, and.congr_left_iff], intro h, simp only [h, or_self, and_true], by_cases hj : j ≤ π ω, { simp only [hj, h.trans hj, or_self], }, { simp only [hj, or_false], }, }, rw this, refine measurable_set.inter _ (hτ.measurable_set_le j), apply measurable_set_le, { exact (hτ.min_const j).measurable_of_le (λ _, min_le_right _ _), }, { exact (hπ.min_const j).measurable_of_le (λ _, min_le_right _ _), }, end lemma measurable_set_stopping_time_le [topological_space ι] [second_countable_topology ι] [order_topology ι] [measurable_space ι] [borel_space ι] (hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) : measurable_set[hπ.measurable_space] {ω | τ ω ≤ π ω} := begin suffices : measurable_set[(hτ.min hπ).measurable_space] {ω : Ω | τ ω ≤ π ω}, by { rw measurable_set_min_iff hτ hπ at this, exact this.2, }, rw [← set.univ_inter {ω : Ω | τ ω ≤ π ω}, ← hτ.measurable_set_inter_le_iff hπ, set.univ_inter], exact measurable_set_le_stopping_time hτ hπ, end lemma measurable_set_eq_stopping_time [add_group ι] [topological_space ι] [measurable_space ι] [borel_space ι] [order_topology ι] [measurable_singleton_class ι] [second_countable_topology ι] [has_measurable_sub₂ ι] (hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) : measurable_set[hτ.measurable_space] {ω | τ ω = π ω} := begin rw hτ.measurable_set, intro j, have : {ω | τ ω = π ω} ∩ {ω | τ ω ≤ j} = {ω | min (τ ω) j = min (π ω) j} ∩ {ω | τ ω ≤ j} ∩ {ω | π ω ≤ j}, { ext1 ω, simp only [set.mem_inter_iff, set.mem_set_of_eq], refine ⟨λ h, ⟨⟨_, h.2⟩, _⟩, λ h, ⟨_, h.1.2⟩⟩, { rw h.1, }, { rw ← h.1, exact h.2, }, { cases h with h' hσ_le, cases h' with h_eq hτ_le, rwa [min_eq_left hτ_le, min_eq_left hσ_le] at h_eq, }, }, rw this, refine measurable_set.inter (measurable_set.inter _ (hτ.measurable_set_le j)) (hπ.measurable_set_le j), apply measurable_set_eq_fun, { exact (hτ.min_const j).measurable_of_le (λ _, min_le_right _ _), }, { exact (hπ.min_const j).measurable_of_le (λ _, min_le_right _ _), }, end lemma measurable_set_eq_stopping_time_of_countable [countable ι] [topological_space ι] [measurable_space ι] [borel_space ι] [order_topology ι] [measurable_singleton_class ι] [second_countable_topology ι] (hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) : measurable_set[hτ.measurable_space] {ω | τ ω = π ω} := begin rw hτ.measurable_set, intro j, have : {ω | τ ω = π ω} ∩ {ω | τ ω ≤ j} = {ω | min (τ ω) j = min (π ω) j} ∩ {ω | τ ω ≤ j} ∩ {ω | π ω ≤ j}, { ext1 ω, simp only [set.mem_inter_iff, set.mem_set_of_eq], refine ⟨λ h, ⟨⟨_, h.2⟩, _⟩, λ h, ⟨_, h.1.2⟩⟩, { rw h.1, }, { rw ← h.1, exact h.2, }, { cases h with h' hπ_le, cases h' with h_eq hτ_le, rwa [min_eq_left hτ_le, min_eq_left hπ_le] at h_eq, }, }, rw this, refine measurable_set.inter (measurable_set.inter _ (hτ.measurable_set_le j)) (hπ.measurable_set_le j), apply measurable_set_eq_fun_of_countable, { exact (hτ.min_const j).measurable_of_le (λ _, min_le_right _ _), }, { exact (hπ.min_const j).measurable_of_le (λ _, min_le_right _ _), }, end end linear_order end is_stopping_time section linear_order /-! ## Stopped value and stopped process -/ /-- Given a map `u : ι → Ω → E`, its stopped value with respect to the stopping time `τ` is the map `x ↦ u (τ ω) ω`. -/ def stopped_value (u : ι → Ω → β) (τ : Ω → ι) : Ω → β := λ ω, u (τ ω) ω lemma stopped_value_const (u : ι → Ω → β) (i : ι) : stopped_value u (λ ω, i) = u i := rfl variable [linear_order ι] /-- Given a map `u : ι → Ω → E`, the stopped process with respect to `τ` is `u i ω` if `i ≤ τ ω`, and `u (τ ω) ω` otherwise. Intuitively, the stopped process stops evolving once the stopping time has occured. -/ def stopped_process (u : ι → Ω → β) (τ : Ω → ι) : ι → Ω → β := λ i ω, u (min i (τ ω)) ω lemma stopped_process_eq_stopped_value {u : ι → Ω → β} {τ : Ω → ι} : stopped_process u τ = λ i, stopped_value u (λ ω, min i (τ ω)) := rfl lemma stopped_value_stopped_process {u : ι → Ω → β} {τ σ : Ω → ι} : stopped_value (stopped_process u τ) σ = stopped_value u (λ ω, min (σ ω) (τ ω)) := rfl lemma stopped_process_eq_of_le {u : ι → Ω → β} {τ : Ω → ι} {i : ι} {ω : Ω} (h : i ≤ τ ω) : stopped_process u τ i ω = u i ω := by simp [stopped_process, min_eq_left h] lemma stopped_process_eq_of_ge {u : ι → Ω → β} {τ : Ω → ι} {i : ι} {ω : Ω} (h : τ ω ≤ i) : stopped_process u τ i ω = u (τ ω) ω := by simp [stopped_process, min_eq_right h] section prog_measurable variables [measurable_space ι] [topological_space ι] [order_topology ι] [second_countable_topology ι] [borel_space ι] [topological_space β] {u : ι → Ω → β} {τ : Ω → ι} {f : filtration ι m} lemma prog_measurable_min_stopping_time [metrizable_space ι] (hτ : is_stopping_time f τ) : prog_measurable f (λ i ω, min i (τ ω)) := begin intro i, let m_prod : measurable_space (set.Iic i × Ω) := measurable_space.prod _ (f i), let m_set : ∀ t : set (set.Iic i × Ω), measurable_space t := λ _, @subtype.measurable_space (set.Iic i × Ω) _ m_prod, let s := {p : set.Iic i × Ω | τ p.2 ≤ i}, have hs : measurable_set[m_prod] s, from @measurable_snd (set.Iic i) Ω _ (f i) _ (hτ i), have h_meas_fst : ∀ t : set (set.Iic i × Ω), measurable[m_set t] (λ x : t, ((x : set.Iic i × Ω).fst : ι)), from λ t, (@measurable_subtype_coe (set.Iic i × Ω) m_prod _).fst.subtype_coe, apply measurable.strongly_measurable, refine measurable_of_restrict_of_restrict_compl hs _ _, { refine @measurable.min _ _ _ _ _ (m_set s) _ _ _ _ _ (h_meas_fst s) _, refine @measurable_of_Iic ι s _ _ _ (m_set s) _ _ _ _ (λ j, _), have h_set_eq : (λ x : s, τ (x : set.Iic i × Ω).snd) ⁻¹' set.Iic j = (λ x : s, (x : set.Iic i × Ω).snd) ⁻¹' {ω | τ ω ≤ min i j}, { ext1 ω, simp only [set.mem_preimage, set.mem_Iic, iff_and_self, le_min_iff, set.mem_set_of_eq], exact λ _, ω.prop, }, rw h_set_eq, suffices h_meas : @measurable _ _ (m_set s) (f i) (λ x : s, (x : set.Iic i × Ω).snd), from h_meas (f.mono (min_le_left _ _) _ (hτ.measurable_set_le (min i j))), exact measurable_snd.comp (@measurable_subtype_coe _ m_prod _), }, { suffices h_min_eq_left : (λ x : sᶜ, min ↑((x : set.Iic i × Ω).fst) (τ (x : set.Iic i × Ω).snd)) = λ x : sᶜ, ↑((x : set.Iic i × Ω).fst), { rw [set.restrict, h_min_eq_left], exact h_meas_fst _, }, ext1 ω, rw min_eq_left, have hx_fst_le : ↑(ω : set.Iic i × Ω).fst ≤ i, from (ω : set.Iic i × Ω).fst.prop, refine hx_fst_le.trans (le_of_lt _), convert ω.prop, simp only [not_le, set.mem_compl_iff, set.mem_set_of_eq], }, end lemma prog_measurable.stopped_process [metrizable_space ι] (h : prog_measurable f u) (hτ : is_stopping_time f τ) : prog_measurable f (stopped_process u τ) := h.comp (prog_measurable_min_stopping_time hτ) (λ i x, min_le_left _ _) lemma prog_measurable.adapted_stopped_process [metrizable_space ι] (h : prog_measurable f u) (hτ : is_stopping_time f τ) : adapted f (stopped_process u τ) := (h.stopped_process hτ).adapted lemma prog_measurable.strongly_measurable_stopped_process [metrizable_space ι] (hu : prog_measurable f u) (hτ : is_stopping_time f τ) (i : ι) : strongly_measurable (stopped_process u τ i) := (hu.adapted_stopped_process hτ i).mono (f.le _) lemma strongly_measurable_stopped_value_of_le (h : prog_measurable f u) (hτ : is_stopping_time f τ) {n : ι} (hτ_le : ∀ ω, τ ω ≤ n) : strongly_measurable[f n] (stopped_value u τ) := begin have : stopped_value u τ = (λ (p : set.Iic n × Ω), u ↑(p.fst) p.snd) ∘ (λ ω, (⟨τ ω, hτ_le ω⟩, ω)), { ext1 ω, simp only [stopped_value, function.comp_app, subtype.coe_mk], }, rw this, refine strongly_measurable.comp_measurable (h n) _, exact (hτ.measurable_of_le hτ_le).subtype_mk.prod_mk measurable_id, end lemma measurable_stopped_value [metrizable_space β] [measurable_space β] [borel_space β] (hf_prog : prog_measurable f u) (hτ : is_stopping_time f τ) : measurable[hτ.measurable_space] (stopped_value u τ) := begin have h_str_meas : ∀ i, strongly_measurable[f i] (stopped_value u (λ ω, min (τ ω) i)), from λ i, strongly_measurable_stopped_value_of_le hf_prog (hτ.min_const i) (λ _, min_le_right _ _), intros t ht i, suffices : stopped_value u τ ⁻¹' t ∩ {ω : Ω | τ ω ≤ i} = stopped_value u (λ ω, min (τ ω) i) ⁻¹' t ∩ {ω : Ω | τ ω ≤ i}, by { rw this, exact ((h_str_meas i).measurable ht).inter (hτ.measurable_set_le i), }, ext1 ω, simp only [stopped_value, set.mem_inter_iff, set.mem_preimage, set.mem_set_of_eq, and.congr_left_iff], intro h, rw min_eq_left h, end end prog_measurable end linear_order section stopped_value_of_mem_finset variables {μ : measure Ω} {τ σ : Ω → ι} {E : Type*} {p : ℝ≥0∞} {u : ι → Ω → E} lemma stopped_value_eq_of_mem_finset [add_comm_monoid E] {s : finset ι} (hbdd : ∀ ω, τ ω ∈ s) : stopped_value u τ = ∑ i in s, set.indicator {ω | τ ω = i} (u i) := begin ext y, rw [stopped_value, finset.sum_apply, finset.sum_indicator_eq_sum_filter], suffices : finset.filter (λ i, y ∈ {ω : Ω | τ ω = i}) s = ({τ y} : finset ι), by rw [this, finset.sum_singleton], ext1 ω, simp only [set.mem_set_of_eq, finset.mem_filter, finset.mem_singleton], split; intro h, { exact h.2.symm, }, { refine ⟨_, h.symm⟩, rw h, exact hbdd y, }, end lemma stopped_value_eq' [preorder ι] [locally_finite_order_bot ι] [add_comm_monoid E] {N : ι} (hbdd : ∀ ω, τ ω ≤ N) : stopped_value u τ = ∑ i in finset.Iic N, set.indicator {ω | τ ω = i} (u i) := stopped_value_eq_of_mem_finset (λ ω, finset.mem_Iic.mpr (hbdd ω)) lemma stopped_process_eq_of_mem_finset [linear_order ι] [add_comm_monoid E] {s : finset ι} (n : ι) (hbdd : ∀ ω, τ ω < n → τ ω ∈ s) : stopped_process u τ n = set.indicator {a | n ≤ τ a} (u n) + ∑ i in s.filter (< n), set.indicator {ω | τ ω = i} (u i) := begin ext ω, rw [pi.add_apply, finset.sum_apply], cases le_or_lt n (τ ω), { rw [stopped_process_eq_of_le h, set.indicator_of_mem, finset.sum_eq_zero, add_zero], { intros m hm, refine set.indicator_of_not_mem _ _, rw [finset.mem_filter] at hm, exact (hm.2.trans_le h).ne', }, { exact h, } }, { rw [stopped_process_eq_of_ge (le_of_lt h), finset.sum_eq_single_of_mem (τ ω)], { rw [set.indicator_of_not_mem, zero_add, set.indicator_of_mem], { exact rfl }, -- refl does not work { exact not_le.2 h } }, { rw [finset.mem_filter], exact ⟨hbdd ω h, h⟩, }, { intros b hb hneq, rw set.indicator_of_not_mem, exact hneq.symm } }, end lemma stopped_process_eq'' [linear_order ι] [locally_finite_order_bot ι] [add_comm_monoid E] (n : ι) : stopped_process u τ n = set.indicator {a | n ≤ τ a} (u n) + ∑ i in finset.Iio n, set.indicator {ω | τ ω = i} (u i) := begin have h_mem : ∀ ω, τ ω < n → τ ω ∈ finset.Iio n := λ ω h, finset.mem_Iio.mpr h, rw stopped_process_eq_of_mem_finset n h_mem, swap, { apply_instance, }, congr' with i, simp only [finset.Iio_filter_lt, min_eq_right], end section stopped_value variables [partial_order ι] {ℱ : filtration ι m} [normed_add_comm_group E] lemma mem_ℒp_stopped_value_of_mem_finset (hτ : is_stopping_time ℱ τ) (hu : ∀ n, mem_ℒp (u n) p μ) {s : finset ι} (hbdd : ∀ ω, τ ω ∈ s) : mem_ℒp (stopped_value u τ) p μ := begin rw stopped_value_eq_of_mem_finset hbdd, swap, apply_instance, refine mem_ℒp_finset_sum' _ (λ i hi, mem_ℒp.indicator _ (hu i)), refine ℱ.le i {a : Ω | τ a = i} (hτ.measurable_set_eq_of_countable_range _ i), refine ((finset.finite_to_set s).subset (λ ω hω, _)).countable, obtain ⟨y, rfl⟩ := hω, exact hbdd y, end lemma mem_ℒp_stopped_value [locally_finite_order_bot ι] (hτ : is_stopping_time ℱ τ) (hu : ∀ n, mem_ℒp (u n) p μ) {N : ι} (hbdd : ∀ ω, τ ω ≤ N) : mem_ℒp (stopped_value u τ) p μ := mem_ℒp_stopped_value_of_mem_finset hτ hu (λ ω, finset.mem_Iic.mpr (hbdd ω)) lemma integrable_stopped_value_of_mem_finset (hτ : is_stopping_time ℱ τ) (hu : ∀ n, integrable (u n) μ) {s : finset ι} (hbdd : ∀ ω, τ ω ∈ s) : integrable (stopped_value u τ) μ := begin simp_rw ← mem_ℒp_one_iff_integrable at hu ⊢, exact mem_ℒp_stopped_value_of_mem_finset hτ hu hbdd, end variables (ι) lemma integrable_stopped_value [locally_finite_order_bot ι] (hτ : is_stopping_time ℱ τ) (hu : ∀ n, integrable (u n) μ) {N : ι} (hbdd : ∀ ω, τ ω ≤ N) : integrable (stopped_value u τ) μ := integrable_stopped_value_of_mem_finset hτ hu (λ ω, finset.mem_Iic.mpr (hbdd ω)) end stopped_value section stopped_process variables [linear_order ι] [topological_space ι] [order_topology ι] [first_countable_topology ι] {ℱ : filtration ι m} [normed_add_comm_group E] lemma mem_ℒp_stopped_process_of_mem_finset (hτ : is_stopping_time ℱ τ) (hu : ∀ n, mem_ℒp (u n) p μ) (n : ι) {s : finset ι} (hbdd : ∀ ω, τ ω < n → τ ω ∈ s) : mem_ℒp (stopped_process u τ n) p μ := begin rw stopped_process_eq_of_mem_finset n hbdd, swap, { apply_instance, }, refine mem_ℒp.add _ _, { exact mem_ℒp.indicator (ℱ.le n {a : Ω | n ≤ τ a} (hτ.measurable_set_ge n)) (hu n) }, { suffices : mem_ℒp (λ ω, ∑ i in s.filter (< n), {a : Ω | τ a = i}.indicator (u i) ω) p μ, { convert this, ext1 ω, simp only [finset.sum_apply] }, refine mem_ℒp_finset_sum _ (λ i hi, mem_ℒp.indicator _ (hu i)), exact ℱ.le i {a : Ω | τ a = i} (hτ.measurable_set_eq i) }, end lemma mem_ℒp_stopped_process [locally_finite_order_bot ι] (hτ : is_stopping_time ℱ τ) (hu : ∀ n, mem_ℒp (u n) p μ) (n : ι) : mem_ℒp (stopped_process u τ n) p μ := mem_ℒp_stopped_process_of_mem_finset hτ hu n (λ ω h, finset.mem_Iio.mpr h) lemma integrable_stopped_process_of_mem_finset (hτ : is_stopping_time ℱ τ) (hu : ∀ n, integrable (u n) μ) (n : ι) {s : finset ι} (hbdd : ∀ ω, τ ω < n → τ ω ∈ s) : integrable (stopped_process u τ n) μ := begin simp_rw ← mem_ℒp_one_iff_integrable at hu ⊢, exact mem_ℒp_stopped_process_of_mem_finset hτ hu n hbdd, end lemma integrable_stopped_process [locally_finite_order_bot ι] (hτ : is_stopping_time ℱ τ) (hu : ∀ n, integrable (u n) μ) (n : ι) : integrable (stopped_process u τ n) μ := integrable_stopped_process_of_mem_finset hτ hu n (λ ω h, finset.mem_Iio.mpr h) end stopped_process end stopped_value_of_mem_finset section adapted_stopped_process variables [topological_space β] [pseudo_metrizable_space β] [linear_order ι] [topological_space ι] [second_countable_topology ι] [order_topology ι] [measurable_space ι] [borel_space ι] {f : filtration ι m} {u : ι → Ω → β} {τ : Ω → ι} /-- The stopped process of an adapted process with continuous paths is adapted. -/ lemma adapted.stopped_process [metrizable_space ι] (hu : adapted f u) (hu_cont : ∀ ω, continuous (λ i, u i ω)) (hτ : is_stopping_time f τ) : adapted f (stopped_process u τ) := ((hu.prog_measurable_of_continuous hu_cont).stopped_process hτ).adapted /-- If the indexing order has the discrete topology, then the stopped process of an adapted process is adapted. -/ lemma adapted.stopped_process_of_discrete [discrete_topology ι] (hu : adapted f u) (hτ : is_stopping_time f τ) : adapted f (stopped_process u τ) := (hu.prog_measurable_of_discrete.stopped_process hτ).adapted lemma adapted.strongly_measurable_stopped_process [metrizable_space ι] (hu : adapted f u) (hu_cont : ∀ ω, continuous (λ i, u i ω)) (hτ : is_stopping_time f τ) (n : ι) : strongly_measurable (stopped_process u τ n) := (hu.prog_measurable_of_continuous hu_cont).strongly_measurable_stopped_process hτ n lemma adapted.strongly_measurable_stopped_process_of_discrete [discrete_topology ι] (hu : adapted f u) (hτ : is_stopping_time f τ) (n : ι) : strongly_measurable (stopped_process u τ n) := hu.prog_measurable_of_discrete.strongly_measurable_stopped_process hτ n end adapted_stopped_process section nat /-! ### Filtrations indexed by `ℕ` -/ open filtration variables {f : filtration ℕ m} {u : ℕ → Ω → β} {τ π : Ω → ℕ} lemma stopped_value_sub_eq_sum [add_comm_group β] (hle : τ ≤ π) : stopped_value u π - stopped_value u τ = λ ω, (∑ i in finset.Ico (τ ω) (π ω), (u (i + 1) - u i)) ω := begin ext ω, rw [finset.sum_Ico_eq_sub _ (hle ω), finset.sum_range_sub, finset.sum_range_sub], simp [stopped_value], end lemma stopped_value_sub_eq_sum' [add_comm_group β] (hle : τ ≤ π) {N : ℕ} (hbdd : ∀ ω, π ω ≤ N) : stopped_value u π - stopped_value u τ = λ ω, (∑ i in finset.range (N + 1), set.indicator {ω | τ ω ≤ i ∧ i < π ω} (u (i + 1) - u i)) ω := begin rw stopped_value_sub_eq_sum hle, ext ω, simp only [finset.sum_apply, finset.sum_indicator_eq_sum_filter], refine finset.sum_congr _ (λ _ _, rfl), ext i, simp only [finset.mem_filter, set.mem_set_of_eq, finset.mem_range, finset.mem_Ico], exact ⟨λ h, ⟨lt_trans h.2 (nat.lt_succ_iff.2 $ hbdd _), h⟩, λ h, h.2⟩ end section add_comm_monoid variables [add_comm_monoid β] lemma stopped_value_eq {N : ℕ} (hbdd : ∀ ω, τ ω ≤ N) : stopped_value u τ = λ x, (∑ i in finset.range (N + 1), set.indicator {ω | τ ω = i} (u i)) x := stopped_value_eq_of_mem_finset (λ ω, finset.mem_range_succ_iff.mpr (hbdd ω)) lemma stopped_process_eq (n : ℕ) : stopped_process u τ n = set.indicator {a | n ≤ τ a} (u n) + ∑ i in finset.range n, set.indicator {ω | τ ω = i} (u i) := begin rw stopped_process_eq'' n, swap, { apply_instance, }, congr' with i, rw [finset.mem_Iio, finset.mem_range], end lemma stopped_process_eq' (n : ℕ) : stopped_process u τ n = set.indicator {a | n + 1 ≤ τ a} (u n) + ∑ i in finset.range (n + 1), set.indicator {a | τ a = i} (u i) := begin have : {a | n ≤ τ a}.indicator (u n) = {a | n + 1 ≤ τ a}.indicator (u n) + {a | τ a = n}.indicator (u n), { ext x, rw [add_comm, pi.add_apply, ← set.indicator_union_of_not_mem_inter], { simp_rw [@eq_comm _ _ n, @le_iff_eq_or_lt _ _ n, nat.succ_le_iff], refl }, { rintro ⟨h₁, h₂⟩, exact (nat.succ_le_iff.1 h₂).ne h₁.symm } }, rw [stopped_process_eq, this, finset.sum_range_succ_comm, ← add_assoc], end end add_comm_monoid end nat section piecewise_const variables [preorder ι] {𝒢 : filtration ι m} {τ η : Ω → ι} {i j : ι} {s : set Ω} [decidable_pred (∈ s)] /-- Given stopping times `τ` and `η` which are bounded below, `set.piecewise s τ η` is also a stopping time with respect to the same filtration. -/ lemma is_stopping_time.piecewise_of_le (hτ_st : is_stopping_time 𝒢 τ) (hη_st : is_stopping_time 𝒢 η) (hτ : ∀ ω, i ≤ τ ω) (hη : ∀ ω, i ≤ η ω) (hs : measurable_set[𝒢 i] s) : is_stopping_time 𝒢 (s.piecewise τ η) := begin intro n, have : {ω | s.piecewise τ η ω ≤ n} = (s ∩ {ω | τ ω ≤ n}) ∪ (sᶜ ∩ {ω | η ω ≤ n}), { ext1 ω, simp only [set.piecewise, set.mem_inter_iff, set.mem_set_of_eq, and.congr_right_iff], by_cases hx : ω ∈ s; simp [hx], }, rw this, by_cases hin : i ≤ n, { have hs_n : measurable_set[𝒢 n] s, from 𝒢.mono hin _ hs, exact (hs_n.inter (hτ_st n)).union (hs_n.compl.inter (hη_st n)), }, { have hτn : ∀ ω, ¬ τ ω ≤ n := λ ω hτn, hin ((hτ ω).trans hτn), have hηn : ∀ ω, ¬ η ω ≤ n := λ ω hηn, hin ((hη ω).trans hηn), simp [hτn, hηn], }, end lemma is_stopping_time_piecewise_const (hij : i ≤ j) (hs : measurable_set[𝒢 i] s) : is_stopping_time 𝒢 (s.piecewise (λ _, i) (λ _, j)) := (is_stopping_time_const 𝒢 i).piecewise_of_le (is_stopping_time_const 𝒢 j) (λ x, le_rfl) (λ _, hij) hs lemma stopped_value_piecewise_const {ι' : Type*} {i j : ι'} {f : ι' → Ω → ℝ} : stopped_value f (s.piecewise (λ _, i) (λ _, j)) = s.piecewise (f i) (f j) := by { ext ω, rw stopped_value, by_cases hx : ω ∈ s; simp [hx] } lemma stopped_value_piecewise_const' {ι' : Type*} {i j : ι'} {f : ι' → Ω → ℝ} : stopped_value f (s.piecewise (λ _, i) (λ _, j)) = s.indicator (f i) + sᶜ.indicator (f j) := by { ext ω, rw stopped_value, by_cases hx : ω ∈ s; simp [hx] } end piecewise_const section condexp /-! ### Conditional expectation with respect to the σ-algebra generated by a stopping time -/ variables [linear_order ι] {μ : measure Ω} {ℱ : filtration ι m} {τ σ : Ω → ι} {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [complete_space E] {f : Ω → E} lemma condexp_stopping_time_ae_eq_restrict_eq_of_countable_range [sigma_finite_filtration μ ℱ] (hτ : is_stopping_time ℱ τ) (h_countable : (set.range τ).countable) [sigma_finite (μ.trim (hτ.measurable_space_le_of_countable_range h_countable))] (i : ι) : μ[f | hτ.measurable_space] =ᵐ[μ.restrict {x | τ x = i}] μ[f | ℱ i] := begin refine condexp_ae_eq_restrict_of_measurable_space_eq_on (hτ.measurable_space_le_of_countable_range h_countable) (ℱ.le i) (hτ.measurable_set_eq_of_countable_range' h_countable i) (λ t, _), rw [set.inter_comm _ t, is_stopping_time.measurable_set_inter_eq_iff], end lemma condexp_stopping_time_ae_eq_restrict_eq_of_countable [countable ι] [sigma_finite_filtration μ ℱ] (hτ : is_stopping_time ℱ τ) [sigma_finite (μ.trim hτ.measurable_space_le_of_countable)] (i : ι) : μ[f | hτ.measurable_space] =ᵐ[μ.restrict {x | τ x = i}] μ[f | ℱ i] := condexp_stopping_time_ae_eq_restrict_eq_of_countable_range hτ (set.to_countable _) i variables [(filter.at_top : filter ι).is_countably_generated] lemma condexp_min_stopping_time_ae_eq_restrict_le_const (hτ : is_stopping_time ℱ τ) (i : ι) [sigma_finite (μ.trim (hτ.min_const i).measurable_space_le)] : μ[f | (hτ.min_const i).measurable_space] =ᵐ[μ.restrict {x | τ x ≤ i}] μ[f | hτ.measurable_space] := begin haveI : sigma_finite (μ.trim hτ.measurable_space_le), { have h_le : (hτ.min_const i).measurable_space ≤ hτ.measurable_space, { rw is_stopping_time.measurable_space_min_const, exact inf_le_left, }, exact sigma_finite_trim_mono _ h_le, }, refine (condexp_ae_eq_restrict_of_measurable_space_eq_on hτ.measurable_space_le (hτ.min_const i).measurable_space_le (hτ.measurable_set_le' i) (λ t, _)).symm, rw [set.inter_comm _ t, hτ.measurable_set_inter_le_const_iff], end variables [topological_space ι] [order_topology ι] lemma condexp_stopping_time_ae_eq_restrict_eq [first_countable_topology ι] [sigma_finite_filtration μ ℱ] (hτ : is_stopping_time ℱ τ) [sigma_finite (μ.trim hτ.measurable_space_le)] (i : ι) : μ[f | hτ.measurable_space] =ᵐ[μ.restrict {x | τ x = i}] μ[f | ℱ i] := begin refine condexp_ae_eq_restrict_of_measurable_space_eq_on hτ.measurable_space_le (ℱ.le i) (hτ.measurable_set_eq' i) (λ t, _), rw [set.inter_comm _ t, is_stopping_time.measurable_set_inter_eq_iff], end lemma condexp_min_stopping_time_ae_eq_restrict_le [measurable_space ι] [second_countable_topology ι] [borel_space ι] (hτ : is_stopping_time ℱ τ) (hσ : is_stopping_time ℱ σ) [sigma_finite (μ.trim (hτ.min hσ).measurable_space_le)] : μ[f | (hτ.min hσ).measurable_space] =ᵐ[μ.restrict {x | τ x ≤ σ x}] μ[f | hτ.measurable_space] := begin haveI : sigma_finite (μ.trim hτ.measurable_space_le), { have h_le : (hτ.min hσ).measurable_space ≤ hτ.measurable_space, { rw is_stopping_time.measurable_space_min, exact inf_le_left, }, exact sigma_finite_trim_mono _ h_le, }, refine (condexp_ae_eq_restrict_of_measurable_space_eq_on hτ.measurable_space_le (hτ.min hσ).measurable_space_le (hτ.measurable_set_le_stopping_time hσ) (λ t, _)).symm, rw [set.inter_comm _ t, is_stopping_time.measurable_set_inter_le_iff], end end condexp end measure_theory
ef1f8b5fa3eaf5efb6c6998fa12c1761bf6d42c0
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/ring_theory/coprime/ideal.lean
aa22abce01acaf552cb678c2e4ccdf5b0ec19024
[ "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
4,205
lean
/- Copyright (c) 2022 Pierre-Alexandre Bazin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Pierre-Alexandre Bazin -/ import linear_algebra.dfinsupp import ring_theory.ideal.operations /-! # An additional lemma about coprime ideals This lemma generalises `exists_sum_eq_one_iff_pairwise_coprime` to the case of non-principal ideals. It is on a separate file due to import requirements. -/ namespace ideal variables {ι R : Type*} [comm_semiring R] /--A finite family of ideals is pairwise coprime (that is, any two of them generate the whole ring) iff when taking all the possible intersections of all but one of these ideals, the resulting family of ideals still generate the whole ring. For example with three ideals : `I ⊔ J = I ⊔ K = J ⊔ K = ⊤ ↔ (I ⊓ J) ⊔ (I ⊓ K) ⊔ (J ⊓ K) = ⊤`. When ideals are all of the form `I i = R ∙ s i`, this is equivalent to the `exists_sum_eq_one_iff_pairwise_coprime` lemma.-/ lemma supr_infi_eq_top_iff_pairwise {t : finset ι} (h : t.nonempty) (I : ι → ideal R) : (⨆ i ∈ t, ⨅ j (hj : j ∈ t) (ij : j ≠ i), I j) = ⊤ ↔ (t : set ι).pairwise (λ i j, I i ⊔ I j = ⊤) := begin haveI : decidable_eq ι := classical.dec_eq ι, rw [eq_top_iff_one, submodule.mem_supr_finset_iff_exists_sum], refine h.cons_induction _ _; clear' t h, { simp only [finset.sum_singleton, finset.coe_singleton, set.pairwise_singleton, iff_true], refine λ a, ⟨λ i, if h : i = a then ⟨1, _⟩ else 0, _⟩, { rw h, simp only [finset.mem_singleton, ne.def, infi_infi_eq_left, eq_self_iff_true, not_true, infi_false]}, { simp only [dif_pos, dif_ctx_congr, submodule.coe_mk, eq_self_iff_true] } }, intros a t hat h ih, rw [finset.coe_cons, set.pairwise_insert_of_symmetric (λ i j (h : I i ⊔ I j = ⊤), sup_comm.trans h)], split, { rintro ⟨μ, hμ⟩, rw finset.sum_cons at hμ, refine ⟨ih.mp ⟨pi.single h.some ⟨μ a, _⟩ + λ i, ⟨μ i, _⟩, _⟩, λ b hb ab, _⟩, { have := submodule.coe_mem (μ a), rw mem_infi at this ⊢, --for some reason `simp only [mem_infi]` times out intro i, specialize this i, rw [mem_infi, mem_infi] at this ⊢, intros hi _, apply this (finset.subset_cons _ hi), rintro rfl, exact hat hi }, { have := submodule.coe_mem (μ i), simp only [mem_infi] at this ⊢, intros j hj ij, exact this _ (finset.subset_cons _ hj) ij }, { rw [← @if_pos _ _ h.some_spec R (μ a) 0, ← finset.sum_pi_single', ← finset.sum_add_distrib] at hμ, convert hμ, ext i, rw [pi.add_apply, submodule.coe_add, submodule.coe_mk], by_cases hi : i = h.some, { rw [hi, pi.single_eq_same, pi.single_eq_same, submodule.coe_mk] }, { rw [pi.single_eq_of_ne hi, pi.single_eq_of_ne hi, submodule.coe_zero] } }, { rw [eq_top_iff_one, submodule.mem_sup], rw add_comm at hμ, refine ⟨_, _, _, _, hμ⟩, { refine sum_mem _ (λ x hx, _), have := submodule.coe_mem (μ x), simp only [mem_infi] at this, apply this _ (finset.mem_cons_self _ _), rintro rfl, exact hat hx }, { have := submodule.coe_mem (μ a), simp only [mem_infi] at this, exact this _ (finset.subset_cons _ hb) ab.symm } } }, { rintro ⟨hs, Hb⟩, obtain ⟨μ, hμ⟩ := ih.mpr hs, obtain ⟨u, hu, v, hv, huv⟩ := submodule.mem_sup.mp ((eq_top_iff_one _).mp $ sup_infi_eq_top $ λ b hb, Hb b hb $ by { rintro rfl, exact hat hb }), refine ⟨λ i, if hi : i = a then ⟨v, _⟩ else ⟨u * μ i, _⟩, _⟩, { simp only [mem_infi] at hv ⊢, intros j hj ij, rw [finset.mem_cons, ← hi] at hj, exact hv _ (hj.resolve_left ij) }, { have := submodule.coe_mem (μ i), simp only [mem_infi] at this ⊢, intros j hj ij, rcases finset.mem_cons.mp hj with rfl | hj, { exact mul_mem_right _ _ hu }, { exact mul_mem_left _ _ (this _ hj ij) } }, { rw [finset.sum_cons, dif_pos rfl, add_comm], rw ← mul_one u at huv, rw [← huv, ← hμ, finset.mul_sum], congr' 1, apply finset.sum_congr rfl, intros j hj, rw dif_neg, refl, rintro rfl, exact hat hj } } end end ideal
97d9db08b9ae0e3720ce2527de6ce53f07b517c3
07c6143268cfb72beccd1cc35735d424ebcb187b
/src/category_theory/limits/shapes/biproducts.lean
16b92ac7c995cf32d43f85fe88b922914d22f3a8
[ "Apache-2.0" ]
permissive
khoek/mathlib
bc49a842910af13a3c372748310e86467d1dc766
aa55f8b50354b3e11ba64792dcb06cccb2d8ee28
refs/heads/master
1,588,232,063,837
1,587,304,803,000
1,587,304,803,000
176,688,517
0
0
Apache-2.0
1,553,070,585,000
1,553,070,585,000
null
UTF-8
Lean
false
false
11,785
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.epi_mono import category_theory.limits.shapes.products import category_theory.limits.shapes.binary_products /-! # Biproducts and binary biproducts We introduce the notion of biproducts and binary biproducts. These are slightly unusual relative to the other shapes in the library, as they are simultaneously limits and colimits. (Zero objects are similar; they are "biterminal".) We model these here using a `bicone`, with a cone point `X`, and natural transformations `π` from the constant functor with value `X` to `F` and `ι` in the other direction. We implement `has_bilimit` as a `bicone`, equipped with the evidence `is_limit bicone.to_cone` and `is_colimit bicone.to_cocone`. In practice, of course, we are only interested in the special case of bilimits over `discrete J` for `[fintype J] [decidable_eq J]`, which corresponds to finite biproducts. TODO: We should provide a constructor that takes `has_limit F`, `has_colimit F`, and and iso `limit F ≅ colimit F`, and produces `has_bilimit F`. TODO: perhaps it makes sense to unify the treatment of zero objects with this a bit. TODO: later, in pre-additive categories, we should give the equational characterisation of biproducts. ## Notation As `⊕` is already taken for the sum of types, we introduce the notation `X ⊞ Y` for a binary biproduct. We introduce `⨁ f` for the indexed biproduct. -/ universes v u open category_theory open category_theory.functor namespace category_theory.limits variables {J : Type v} [small_category J] variables {C : Type u} [𝒞 : category.{v} C] include 𝒞 /-- A `c : bicone F` is: * an object `c.X` and * a natural transformation `c.π : c.X ⟶ F` from the constant `c.X` functor to `F`. * a natural transformation `c.ι : F ⟶ c.X` from `F` to the constant `c.X` functor. -/ @[nolint has_inhabited_instance] structure bicone {J : Type v} [small_category J] (F : J ⥤ C) := (X : C) (π : (const J).obj X ⟶ F) (ι : F ⟶ (const J).obj X) variables {F : J ⥤ C} namespace bicone /-- Extract the cone from a bicone. -/ @[simps] def to_cone (B : bicone F) : cone F := { .. B } /-- Extract the cocone from a bicone. -/ @[simps] def to_cocone (B : bicone F) : cocone F := { .. B } end bicone /-- `has_bilimit F` represents a particular chosen bicone which is simultaneously a limit and a colimit of the diagram `F`. (This is only interesting when the source category is discrete.) -/ class has_bilimit (F : J ⥤ C) := (bicone : bicone F) (is_limit : is_limit bicone.to_cone) (is_colimit : is_colimit bicone.to_cocone) @[priority 100] instance has_limit_of_has_bilimit [has_bilimit F] : has_limit F := { cone := has_bilimit.bicone.to_cone, is_limit := has_bilimit.is_limit, } @[priority 100] instance has_colimit_of_has_bilimit [has_bilimit F] : has_colimit F := { cocone := has_bilimit.bicone.to_cocone, is_colimit := has_bilimit.is_colimit, } variables (J C) /-- `C` has bilimits of shape `J` if we have chosen a particular limit and a particular colimit, with the same cone points, of every functor `F : J ⥤ C`. (This is only interesting if `J` is discrete.) -/ class has_bilimits_of_shape := (has_bilimit : Π F : J ⥤ C, has_bilimit F) attribute [instance, priority 100] has_bilimits_of_shape.has_bilimit @[priority 100] instance [has_bilimits_of_shape J C] : has_limits_of_shape J C := { has_limit := λ F, by apply_instance } @[priority 100] instance [has_bilimits_of_shape J C] : has_colimits_of_shape J C := { has_colimit := λ F, by apply_instance } /-- `has_finite_biproducts C` represents a choice of biproduct for every family of objects in `C` indexed by a finite type with decidable equality. -/ class has_finite_biproducts := (has_bilimits_of_shape : Π (J : Type v) [fintype J] [decidable_eq J], has_bilimits_of_shape.{v} (discrete J) C) attribute [instance] has_finite_biproducts.has_bilimits_of_shape /-- The isomorphism between the specified limit and the specified colimit for a functor with a bilimit. -/ def biproduct_iso {J : Type v} (F : J → C) [has_bilimit (functor.of_function F)] : limits.pi_obj F ≅ limits.sigma_obj F := eq_to_iso rfl end category_theory.limits namespace category_theory.limits variables {J : Type v} variables {C : Type u} [𝒞 : category.{v} C] include 𝒞 /-- `biproduct f` computes the biproduct of a family of elements `f`. (It is defined as an abbreviation for `limit (functor.of_function f)`, so for most facts about `biproduct f`, you will just use general facts about limits and colimits.) -/ abbreviation biproduct (f : J → C) [has_bilimit (functor.of_function f)] := limit (functor.of_function f) notation `⨁ ` f:20 := biproduct f /-- The projection onto a summand of a biproduct. -/ abbreviation biproduct.π (f : J → C) [has_bilimit (functor.of_function f)] (b : J) : ⨁ f ⟶ f b := limit.π (functor.of_function f) b /-- The inclusion into a summand of a biproduct. -/ abbreviation biproduct.ι (f : J → C) [has_bilimit (functor.of_function f)] (b : J) : f b ⟶ ⨁ f := colimit.ι (functor.of_function f) b /-- Given a collection of maps into the summands, we obtain a map into the biproduct. -/ abbreviation biproduct.lift {f : J → C} [has_bilimit (functor.of_function f)] {P : C} (p : Π b, P ⟶ f b) : P ⟶ ⨁ f := limit.lift _ (fan.mk p) /-- Given a collection of maps out of the summands, we obtain a map out of the biproduct. -/ abbreviation biproduct.desc {f : J → C} [has_bilimit (functor.of_function f)] {P : C} (p : Π b, f b ⟶ P) : ⨁ f ⟶ P := colimit.desc _ (cofan.mk p) /-- Given a collection of maps between corresponding summands of a pair of biproducts indexed by the same type, we obtain a map betweeen the biproducts. -/ abbreviation biproduct.map [fintype J] [decidable_eq J] {f g : J → C} [has_finite_biproducts.{v} C] (p : Π b, f b ⟶ g b) : ⨁ f ⟶ ⨁ g := (@lim (discrete J) _ C _ _).map (nat_trans.of_function p) instance biproduct.ι_mono [decidable_eq J] (f : J → C) [has_bilimit (functor.of_function f)] (b : J) : split_mono (biproduct.ι f b) := { retraction := biproduct.desc $ λ b', if h : b' = b then eq_to_hom (congr_arg f h) else biproduct.ι f b' ≫ biproduct.π f b } instance biproduct.π_epi [decidable_eq J] (f : J → C) [has_bilimit (functor.of_function f)] (b : J) : split_epi (biproduct.π f b) := { section_ := biproduct.lift $ λ b', if h : b = b' then eq_to_hom (congr_arg f h) else biproduct.ι f b ≫ biproduct.π f b' } variables {C} /-- A binary bicone for a pair of objects `P Q : C` consists of the cone point `X`, maps from `X` to both `P` and `Q`, and maps from both `P` and `Q` to `X`. -/ @[nolint has_inhabited_instance] structure binary_bicone (P Q : C) := (X : C) (π₁ : X ⟶ P) (π₂ : X ⟶ Q) (ι₁ : P ⟶ X) (ι₂ : Q ⟶ X) namespace binary_bicone variables {P Q : C} /-- Extract the cone from a binary bicone. -/ @[simp] def to_cone (c : binary_bicone.{v} P Q) : cone (pair P Q) := binary_fan.mk c.π₁ c.π₂ /-- Extract the cocone from a binary bicone. -/ @[simp] def to_cocone (c : binary_bicone.{v} P Q) : cocone (pair P Q) := binary_cofan.mk c.ι₁ c.ι₂ end binary_bicone /-- `has_binary_biproduct P Q` represents a particular chosen bicone which is simultaneously a limit and a colimit of the diagram `pair P Q`. -/ class has_binary_biproduct (P Q : C) := (bicone : binary_bicone.{v} P Q) (is_limit : is_limit bicone.to_cone) (is_colimit : is_colimit bicone.to_cocone) section variable (C) /-- `has_binary_biproducts C` represents a particular chosen bicone which is simultaneously a limit and a colimit of the diagram `pair P Q`, for every `P Q : C`. -/ class has_binary_biproducts := (has_binary_biproduct : Π (P Q : C), has_binary_biproduct.{v} P Q) attribute [instance, priority 100] has_binary_biproducts.has_binary_biproduct end variables {P Q : C} instance has_binary_biproduct.has_limit_pair [has_binary_biproduct.{v} P Q] : has_limit (pair P Q) := { cone := has_binary_biproduct.bicone.to_cone, is_limit := has_binary_biproduct.is_limit.{v}, } instance has_binary_biproduct.has_colimit_pair [has_binary_biproduct.{v} P Q] : has_colimit (pair P Q) := { cocone := has_binary_biproduct.bicone.to_cocone, is_colimit := has_binary_biproduct.is_colimit.{v}, } @[priority 100] instance has_limits_of_shape_walking_pair [has_binary_biproducts.{v} C] : has_limits_of_shape.{v} (discrete walking_pair) C := { has_limit := λ F, has_limit_of_iso (diagram_iso_pair F).symm } @[priority 100] instance has_colimits_of_shape_walking_pair [has_binary_biproducts.{v} C] : has_colimits_of_shape.{v} (discrete walking_pair) C := { has_colimit := λ F, has_colimit_of_iso (diagram_iso_pair F) } /-- The isomorphism between the specified binary product and the specified binary coproduct for a pair for a binary biproduct. -/ def biprod_iso (X Y : C) [has_binary_biproduct.{v} X Y] : limits.prod X Y ≅ limits.coprod X Y := eq_to_iso rfl /-- The chosen biproduct of a pair of objects. -/ abbreviation biprod (X Y : C) [has_binary_biproduct.{v} X Y] := limit (pair X Y) notation X ` ⊞ `:20 Y:20 := biprod X Y /-- The projection onto the first summand of a binary biproduct. -/ abbreviation biprod.fst {X Y : C} [has_binary_biproduct.{v} X Y] : X ⊞ Y ⟶ X := limit.π (pair X Y) walking_pair.left /-- The projection onto the second summand of a binary biproduct. -/ abbreviation biprod.snd {X Y : C} [has_binary_biproduct.{v} X Y] : X ⊞ Y ⟶ Y := limit.π (pair X Y) walking_pair.right /-- The inclusion into the first summand of a binary biproduct. -/ abbreviation biprod.inl {X Y : C} [has_binary_biproduct.{v} X Y] : X ⟶ X ⊞ Y := colimit.ι (pair X Y) walking_pair.left /-- The inclusion into the second summand of a binary biproduct. -/ abbreviation biprod.inr {X Y : C} [has_binary_biproduct.{v} X Y] : Y ⟶ X ⊞ Y := colimit.ι (pair X Y) walking_pair.right /-- Given a pair of maps into the summands of a binary biproduct, we obtain a map into the binary biproduct. -/ abbreviation biprod.lift {W X Y : C} [has_binary_biproduct.{v} X Y] (f : W ⟶ X) (g : W ⟶ Y) : W ⟶ X ⊞ Y := limit.lift _ (binary_fan.mk f g) /-- Given a pair of maps out of the summands of a binary biproduct, we obtain a map out of the binary biproduct. -/ abbreviation biprod.desc {W X Y : C} [has_binary_biproduct.{v} X Y] (f : X ⟶ W) (g : Y ⟶ W) : X ⊞ Y ⟶ W := colimit.desc _ (binary_cofan.mk f g) /-- Given a pair of maps between the summands of a pair of binary biproducts, we obtain a map between the binary biproducts. -/ abbreviation biprod.map {W X Y Z : C} [has_binary_biproducts.{v} C] (f : W ⟶ Y) (g : X ⟶ Z) : W ⊞ X ⟶ Y ⊞ Z := (@lim (discrete walking_pair) _ C _ _).map (@map_pair _ _ (pair W X) (pair Y Z) f g) instance biprod.inl_mono {X Y : C} [has_binary_biproduct.{v} X Y] : split_mono (biprod.inl : X ⟶ X ⊞ Y) := { retraction := biprod.desc (𝟙 X) (biprod.inr ≫ biprod.fst) } instance biprod.inr_mono {X Y : C} [has_binary_biproduct.{v} X Y] : split_mono (biprod.inr : Y ⟶ X ⊞ Y) := { retraction := biprod.desc (biprod.inl ≫ biprod.snd) (𝟙 Y)} instance biprod.fst_epi {X Y : C} [has_binary_biproduct.{v} X Y] : split_epi (biprod.fst : X ⊞ Y ⟶ X) := { section_ := biprod.lift (𝟙 X) (biprod.inl ≫ biprod.snd) } instance biprod.snd_epi {X Y : C} [has_binary_biproduct.{v} X Y] : split_epi (biprod.snd : X ⊞ Y ⟶ Y) := { section_ := biprod.lift (biprod.inr ≫ biprod.fst) (𝟙 Y) } -- TODO: -- If someone is interested, they could provide the constructions: -- has_binary_biproducts ↔ has_finite_biproducts end category_theory.limits
afc767fdbaa1a3ebd479e3c4f049bb2406a38365
8a8d9c511db749b9c0205ee48d6df1e2c6dd1e6f
/library/algebra/ordered_ring.lean
db711c5ea54510617ec8ee6b1a1ee15e86965217
[ "Apache-2.0" ]
permissive
rpglover64/lean
4d92db4b316b543b8a49797e2109532ed5eb88bb
cbac8d13006782c71a2281c3dd76854ccf8623a7
refs/heads/master
1,582,731,391,459
1,427,585,012,000
1,427,585,012,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
20,927
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: algebra.ordered_ring Authors: Jeremy Avigad Here an "ordered_ring" is partially ordered ring, which is ordered with respect to both a weak order and an associated strict order. Our numeric structures (int, rat, and real) will be instances of "linear_ordered_comm_ring". This development is modeled after Isabelle's library. -/ import algebra.ordered_group algebra.ring open eq eq.ops namespace algebra variable {A : Type} definition absurd_a_lt_a {B : Type} {a : A} [s : strict_order A] (H : a < a) : B := absurd H (lt.irrefl a) structure ordered_semiring [class] (A : Type) extends has_mul A, has_zero A, has_lt A, -- TODO: remove hack for improving performance semiring A, ordered_cancel_comm_monoid A, zero_ne_one_class A := (mul_le_mul_of_nonneg_left: ∀a b c, le a b → le zero c → le (mul c a) (mul c b)) (mul_le_mul_of_nonneg_right: ∀a b c, le a b → le zero c → le (mul a c) (mul b c)) (mul_lt_mul_of_pos_left: ∀a b c, lt a b → lt zero c → lt (mul c a) (mul c b)) (mul_lt_mul_of_pos_right: ∀a b c, lt a b → lt zero c → lt (mul a c) (mul b c)) section variable [s : ordered_semiring A] variables (a b c d e : A) include s theorem mul_le_mul_of_nonneg_left {a b c : A} (Hab : a ≤ b) (Hc : 0 ≤ c) : c * a ≤ c * b := !ordered_semiring.mul_le_mul_of_nonneg_left Hab Hc theorem mul_le_mul_of_nonneg_right {a b c : A} (Hab : a ≤ b) (Hc : 0 ≤ c) : a * c ≤ b * c := !ordered_semiring.mul_le_mul_of_nonneg_right Hab Hc -- TODO: there are four variations, depending on which variables we assume to be nonneg theorem mul_le_mul {a b c d : A} (Hac : a ≤ c) (Hbd : b ≤ d) (nn_b : 0 ≤ b) (nn_c : 0 ≤ c) : a * b ≤ c * d := calc a * b ≤ c * b : mul_le_mul_of_nonneg_right Hac nn_b ... ≤ c * d : mul_le_mul_of_nonneg_left Hbd nn_c theorem mul_nonneg {a b : A} (Ha : a ≥ 0) (Hb : b ≥ 0) : a * b ≥ 0 := begin have H : 0 * b ≤ a * b, from mul_le_mul_of_nonneg_right Ha Hb, rewrite zero_mul at H, exact H end theorem mul_nonpos_of_nonneg_of_nonpos {a b : A} (Ha : a ≥ 0) (Hb : b ≤ 0) : a * b ≤ 0 := begin have H : a * b ≤ a * 0, from mul_le_mul_of_nonneg_left Hb Ha, rewrite mul_zero at H, exact H end theorem mul_nonpos_of_nonpos_of_nonneg {a b : A} (Ha : a ≤ 0) (Hb : b ≥ 0) : a * b ≤ 0 := begin have H : a * b ≤ 0 * b, from mul_le_mul_of_nonneg_right Ha Hb, rewrite zero_mul at H, exact H end theorem mul_lt_mul_of_pos_left {a b c : A} (Hab : a < b) (Hc : 0 < c) : c * a < c * b := !ordered_semiring.mul_lt_mul_of_pos_left Hab Hc theorem mul_lt_mul_of_pos_right {a b c : A} (Hab : a < b) (Hc : 0 < c) : a * c < b * c := !ordered_semiring.mul_lt_mul_of_pos_right Hab Hc -- TODO: once again, there are variations theorem mul_lt_mul {a b c d : A} (Hac : a < c) (Hbd : b ≤ d) (pos_b : 0 < b) (nn_c : 0 ≤ c) : a * b < c * d := calc a * b < c * b : mul_lt_mul_of_pos_right Hac pos_b ... ≤ c * d : mul_le_mul_of_nonneg_left Hbd nn_c theorem mul_pos {a b : A} (Ha : a > 0) (Hb : b > 0) : a * b > 0 := begin have H : 0 * b < a * b, from mul_lt_mul_of_pos_right Ha Hb, rewrite zero_mul at H, exact H end theorem mul_neg_of_pos_of_neg {a b : A} (Ha : a > 0) (Hb : b < 0) : a * b < 0 := begin have H : a * b < a * 0, from mul_lt_mul_of_pos_left Hb Ha, rewrite mul_zero at H, exact H end theorem mul_neg_of_neg_of_pos {a b : A} (Ha : a < 0) (Hb : b > 0) : a * b < 0 := begin have H : a * b < 0 * b, from mul_lt_mul_of_pos_right Ha Hb, rewrite zero_mul at H, exact H end end structure linear_ordered_semiring [class] (A : Type) extends ordered_semiring A, linear_strong_order_pair A section variable [s : linear_ordered_semiring A] variables {a b c : A} include s theorem lt_of_mul_lt_mul_left (H : c * a < c * b) (Hc : c ≥ 0) : a < b := lt_of_not_le (assume H1 : b ≤ a, have H2 : c * b ≤ c * a, from mul_le_mul_of_nonneg_left H1 Hc, not_lt_of_le H2 H) theorem lt_of_mul_lt_mul_right (H : a * c < b * c) (Hc : c ≥ 0) : a < b := lt_of_not_le (assume H1 : b ≤ a, have H2 : b * c ≤ a * c, from mul_le_mul_of_nonneg_right H1 Hc, not_lt_of_le H2 H) theorem le_of_mul_le_mul_left (H : c * a ≤ c * b) (Hc : c > 0) : a ≤ b := le_of_not_lt (assume H1 : b < a, have H2 : c * b < c * a, from mul_lt_mul_of_pos_left H1 Hc, not_le_of_lt H2 H) theorem le_of_mul_le_mul_right (H : a * c ≤ b * c) (Hc : c > 0) : a ≤ b := le_of_not_lt (assume H1 : b < a, have H2 : b * c < a * c, from mul_lt_mul_of_pos_right H1 Hc, not_le_of_lt H2 H) theorem pos_of_mul_pos_left (H : 0 < a * b) (H1 : 0 ≤ a) : 0 < b := lt_of_not_le (assume H2 : b ≤ 0, have H3 : a * b ≤ 0, from mul_nonpos_of_nonneg_of_nonpos H1 H2, not_lt_of_le H3 H) theorem pos_of_mul_pos_right (H : 0 < a * b) (H1 : 0 ≤ b) : 0 < a := lt_of_not_le (assume H2 : a ≤ 0, have H3 : a * b ≤ 0, from mul_nonpos_of_nonpos_of_nonneg H2 H1, not_lt_of_le H3 H) end structure ordered_ring [class] (A : Type) extends ring A, ordered_comm_group A, zero_ne_one_class A := (mul_nonneg : ∀a b, le zero a → le zero b → le zero (mul a b)) (mul_pos : ∀a b, lt zero a → lt zero b → lt zero (mul a b)) theorem ordered_ring.mul_le_mul_of_nonneg_left [s : ordered_ring A] {a b c : A} (Hab : a ≤ b) (Hc : 0 ≤ c) : c * a ≤ c * b := have H1 : 0 ≤ b - a, from iff.elim_right !sub_nonneg_iff_le Hab, assert H2 : 0 ≤ c * (b - a), from ordered_ring.mul_nonneg _ _ Hc H1, begin rewrite mul_sub_left_distrib at H2, exact (iff.mp !sub_nonneg_iff_le H2) end theorem ordered_ring.mul_le_mul_of_nonneg_right [s : ordered_ring A] {a b c : A} (Hab : a ≤ b) (Hc : 0 ≤ c) : a * c ≤ b * c := have H1 : 0 ≤ b - a, from iff.elim_right !sub_nonneg_iff_le Hab, assert H2 : 0 ≤ (b - a) * c, from ordered_ring.mul_nonneg _ _ H1 Hc, begin rewrite mul_sub_right_distrib at H2, exact (iff.mp !sub_nonneg_iff_le H2) end theorem ordered_ring.mul_lt_mul_of_pos_left [s : ordered_ring A] {a b c : A} (Hab : a < b) (Hc : 0 < c) : c * a < c * b := have H1 : 0 < b - a, from iff.elim_right !sub_pos_iff_lt Hab, assert H2 : 0 < c * (b - a), from ordered_ring.mul_pos _ _ Hc H1, begin rewrite mul_sub_left_distrib at H2, exact (iff.mp !sub_pos_iff_lt H2) end theorem ordered_ring.mul_lt_mul_of_pos_right [s : ordered_ring A] {a b c : A} (Hab : a < b) (Hc : 0 < c) : a * c < b * c := have H1 : 0 < b - a, from iff.elim_right !sub_pos_iff_lt Hab, assert H2 : 0 < (b - a) * c, from ordered_ring.mul_pos _ _ H1 Hc, begin rewrite mul_sub_right_distrib at H2, exact (iff.mp !sub_pos_iff_lt H2) end definition ordered_ring.to_ordered_semiring [instance] [coercion] [reducible] [s : ordered_ring A] : ordered_semiring A := ⦃ ordered_semiring, s, mul_zero := mul_zero, zero_mul := zero_mul, add_left_cancel := @add.left_cancel A s, add_right_cancel := @add.right_cancel A s, le_of_add_le_add_left := @le_of_add_le_add_left A s, mul_le_mul_of_nonneg_left := @ordered_ring.mul_le_mul_of_nonneg_left A s, mul_le_mul_of_nonneg_right := @ordered_ring.mul_le_mul_of_nonneg_right A s, mul_lt_mul_of_pos_left := @ordered_ring.mul_lt_mul_of_pos_left A s, mul_lt_mul_of_pos_right := @ordered_ring.mul_lt_mul_of_pos_right A s ⦄ section variable [s : ordered_ring A] variables {a b c : A} include s theorem mul_le_mul_of_nonpos_left (H : b ≤ a) (Hc : c ≤ 0) : c * a ≤ c * b := have Hc' : -c ≥ 0, from iff.mp' !neg_nonneg_iff_nonpos Hc, assert H1 : -c * b ≤ -c * a, from mul_le_mul_of_nonneg_left H Hc', have H2 : -(c * b) ≤ -(c * a), begin rewrite [-*neg_mul_eq_neg_mul at H1], exact H1 end, iff.mp !neg_le_neg_iff_le H2 theorem mul_le_mul_of_nonpos_right (H : b ≤ a) (Hc : c ≤ 0) : a * c ≤ b * c := have Hc' : -c ≥ 0, from iff.mp' !neg_nonneg_iff_nonpos Hc, assert H1 : b * -c ≤ a * -c, from mul_le_mul_of_nonneg_right H Hc', have H2 : -(b * c) ≤ -(a * c), begin rewrite [-*neg_mul_eq_mul_neg at H1], exact H1 end, iff.mp !neg_le_neg_iff_le H2 theorem mul_nonneg_of_nonpos_of_nonpos (Ha : a ≤ 0) (Hb : b ≤ 0) : 0 ≤ a * b := begin have H : 0 * b ≤ a * b, from mul_le_mul_of_nonpos_right Ha Hb, rewrite zero_mul at H, exact H end theorem mul_lt_mul_of_neg_left (H : b < a) (Hc : c < 0) : c * a < c * b := have Hc' : -c > 0, from iff.mp' !neg_pos_iff_neg Hc, assert H1 : -c * b < -c * a, from mul_lt_mul_of_pos_left H Hc', have H2 : -(c * b) < -(c * a), begin rewrite [-*neg_mul_eq_neg_mul at H1], exact H1 end, iff.mp !neg_lt_neg_iff_lt H2 theorem mul_lt_mul_of_neg_right (H : b < a) (Hc : c < 0) : a * c < b * c := have Hc' : -c > 0, from iff.mp' !neg_pos_iff_neg Hc, assert H1 : b * -c < a * -c, from mul_lt_mul_of_pos_right H Hc', have H2 : -(b * c) < -(a * c), begin rewrite [-*neg_mul_eq_mul_neg at H1], exact H1 end, iff.mp !neg_lt_neg_iff_lt H2 theorem mul_pos_of_neg_of_neg (Ha : a < 0) (Hb : b < 0) : 0 < a * b := begin have H : 0 * b < a * b, from mul_lt_mul_of_neg_right Ha Hb, rewrite zero_mul at H, exact H end end -- TODO: we can eliminate mul_pos_of_pos, but now it is not worth the effort to redeclare the -- class instance structure linear_ordered_ring [class] (A : Type) extends ordered_ring A, linear_strong_order_pair A -- print fields linear_ordered_semiring definition linear_ordered_ring.to_linear_ordered_semiring [instance] [coercion] [reducible] [s : linear_ordered_ring A] : linear_ordered_semiring A := ⦃ linear_ordered_semiring, s, mul_zero := mul_zero, zero_mul := zero_mul, add_left_cancel := @add.left_cancel A s, add_right_cancel := @add.right_cancel A s, le_of_add_le_add_left := @le_of_add_le_add_left A s, mul_le_mul_of_nonneg_left := @mul_le_mul_of_nonneg_left A s, mul_le_mul_of_nonneg_right := @mul_le_mul_of_nonneg_right A s, mul_lt_mul_of_pos_left := @mul_lt_mul_of_pos_left A s, mul_lt_mul_of_pos_right := @mul_lt_mul_of_pos_right A s, le_total := linear_ordered_ring.le_total ⦄ structure linear_ordered_comm_ring [class] (A : Type) extends linear_ordered_ring A, comm_monoid A theorem linear_ordered_comm_ring.eq_zero_or_eq_zero_of_mul_eq_zero [s : linear_ordered_comm_ring A] {a b : A} (H : a * b = 0) : a = 0 ∨ b = 0 := lt.by_cases (assume Ha : 0 < a, lt.by_cases (assume Hb : 0 < b, begin have H1 : 0 < a * b, from mul_pos Ha Hb, rewrite H at H1, apply (absurd_a_lt_a H1) end) (assume Hb : 0 = b, or.inr (Hb⁻¹)) (assume Hb : 0 > b, begin have H1 : 0 > a * b, from mul_neg_of_pos_of_neg Ha Hb, rewrite H at H1, apply (absurd_a_lt_a H1) end)) (assume Ha : 0 = a, or.inl (Ha⁻¹)) (assume Ha : 0 > a, lt.by_cases (assume Hb : 0 < b, begin have H1 : 0 > a * b, from mul_neg_of_neg_of_pos Ha Hb, rewrite H at H1, apply (absurd_a_lt_a H1) end) (assume Hb : 0 = b, or.inr (Hb⁻¹)) (assume Hb : 0 > b, begin have H1 : 0 < a * b, from mul_pos_of_neg_of_neg Ha Hb, rewrite H at H1, apply (absurd_a_lt_a H1) end)) -- Linearity implies no zero divisors. Doesn't need commutativity. definition linear_ordered_comm_ring.to_integral_domain [instance] [coercion] [reducible] [s: linear_ordered_comm_ring A] : integral_domain A := ⦃ integral_domain, s, eq_zero_or_eq_zero_of_mul_eq_zero := @linear_ordered_comm_ring.eq_zero_or_eq_zero_of_mul_eq_zero A s ⦄ section variable [s : linear_ordered_ring A] variables (a b c : A) include s theorem mul_self_nonneg : a * a ≥ 0 := or.elim (le.total 0 a) (assume H : a ≥ 0, mul_nonneg H H) (assume H : a ≤ 0, mul_nonneg_of_nonpos_of_nonpos H H) theorem zero_le_one : 0 ≤ 1 := one_mul 1 ▸ mul_self_nonneg 1 theorem zero_lt_one : 0 < 1 := lt_of_le_of_ne zero_le_one zero_ne_one theorem pos_and_pos_or_neg_and_neg_of_mul_pos {a b : A} (Hab : a * b > 0) : (a > 0 ∧ b > 0) ∨ (a < 0 ∧ b < 0) := lt.by_cases (assume Ha : 0 < a, lt.by_cases (assume Hb : 0 < b, or.inl (and.intro Ha Hb)) (assume Hb : 0 = b, begin rewrite [-Hb at Hab, mul_zero at Hab], apply (absurd_a_lt_a Hab) end) (assume Hb : b < 0, absurd Hab (lt.asymm (mul_neg_of_pos_of_neg Ha Hb)))) (assume Ha : 0 = a, begin rewrite [-Ha at Hab, zero_mul at Hab], apply (absurd_a_lt_a Hab) end) (assume Ha : a < 0, lt.by_cases (assume Hb : 0 < b, absurd Hab (lt.asymm (mul_neg_of_neg_of_pos Ha Hb))) (assume Hb : 0 = b, begin rewrite [-Hb at Hab, mul_zero at Hab], apply (absurd_a_lt_a Hab) end) (assume Hb : b < 0, or.inr (and.intro Ha Hb))) theorem gt_of_mul_lt_mul_neg_left {a b c} (H : c * a < c * b) (Hc : c ≤ 0) : a > b := have nhc : -c ≥ 0, from neg_nonneg_of_nonpos Hc, have H2 : -(c * b) < -(c * a), from iff.mp' (neg_lt_neg_iff_lt _ _) H, have H3 : (-c) * b < (-c) * a, from calc (-c) * b = - (c * b) : neg_mul_eq_neg_mul ... < -(c * a) : H2 ... = (-c) * a : neg_mul_eq_neg_mul, lt_of_mul_lt_mul_left H3 nhc theorem zero_gt_neg_one : -1 < 0 := neg_zero ▸ (neg_lt_neg zero_lt_one) end /- TODO: Isabelle's library has all kinds of cancelation rules for the simplifier. Search on mult_le_cancel_right1 in Rings.thy. -/ structure decidable_linear_ordered_comm_ring [class] (A : Type) extends linear_ordered_comm_ring A, decidable_linear_ordered_comm_group A section variable [s : decidable_linear_ordered_comm_ring A] variables {a b c : A} include s definition sign (a : A) : A := lt.cases a 0 (-1) 0 1 theorem sign_of_neg (H : a < 0) : sign a = -1 := lt.cases_of_lt H theorem sign_zero : sign 0 = 0 := lt.cases_of_eq rfl theorem sign_of_pos (H : a > 0) : sign a = 1 := lt.cases_of_gt H theorem sign_one : sign 1 = 1 := sign_of_pos zero_lt_one theorem sign_neg_one : sign (-1) = -1 := sign_of_neg (neg_neg_of_pos zero_lt_one) theorem sign_sign (a : A) : sign (sign a) = sign a := lt.by_cases (assume H : a > 0, calc sign (sign a) = sign 1 : by rewrite (sign_of_pos H) ... = 1 : by rewrite sign_one ... = sign a : by rewrite (sign_of_pos H)) (assume H : 0 = a, calc sign (sign a) = sign (sign 0) : by rewrite H ... = sign 0 : by rewrite sign_zero at {1} ... = sign a : by rewrite -H) (assume H : a < 0, calc sign (sign a) = sign (-1) : by rewrite (sign_of_neg H) ... = -1 : by rewrite sign_neg_one ... = sign a : by rewrite (sign_of_neg H)) theorem pos_of_sign_eq_one (H : sign a = 1) : a > 0 := lt.by_cases (assume H1 : 0 < a, H1) (assume H1 : 0 = a, begin rewrite [-H1 at H, sign_zero at H], apply (absurd H zero_ne_one) end) (assume H1 : 0 > a, have H2 : -1 = 1, from (sign_of_neg H1)⁻¹ ⬝ H, absurd ((eq_zero_of_neg_eq H2)⁻¹) zero_ne_one) theorem eq_zero_of_sign_eq_zero (H : sign a = 0) : a = 0 := lt.by_cases (assume H1 : 0 < a, absurd (H⁻¹ ⬝ sign_of_pos H1) zero_ne_one) (assume H1 : 0 = a, H1⁻¹) (assume H1 : 0 > a, have H2 : 0 = -1, from H⁻¹ ⬝ sign_of_neg H1, have H3 : 1 = 0, from eq_neg_of_eq_neg H2 ⬝ neg_zero, absurd (H3⁻¹) zero_ne_one) theorem neg_of_sign_eq_neg_one (H : sign a = -1) : a < 0 := lt.by_cases (assume H1 : 0 < a, have H2 : -1 = 1, from H⁻¹ ⬝ (sign_of_pos H1), absurd ((eq_zero_of_neg_eq H2)⁻¹) zero_ne_one) (assume H1 : 0 = a, have H2 : 0 = -1, begin rewrite [-H1 at H, sign_zero at H], exact H end, have H3 : 1 = 0, from eq_neg_of_eq_neg H2 ⬝ neg_zero, absurd (H3⁻¹) zero_ne_one) (assume H1 : 0 > a, H1) theorem sign_neg (a : A) : sign (-a) = -(sign a) := lt.by_cases (assume H1 : 0 < a, calc sign (-a) = -1 : sign_of_neg (neg_neg_of_pos H1) ... = -(sign a) : by rewrite (sign_of_pos H1)) (assume H1 : 0 = a, calc sign (-a) = sign (-0) : by rewrite H1 ... = sign 0 : by rewrite neg_zero ... = 0 : by rewrite sign_zero ... = -0 : by rewrite neg_zero ... = -(sign 0) : by rewrite sign_zero ... = -(sign a) : by rewrite -H1) (assume H1 : 0 > a, calc sign (-a) = 1 : sign_of_pos (neg_pos_of_neg H1) ... = -(-1) : by rewrite neg_neg ... = -(sign a) : sign_of_neg H1) -- hopefully, will be quick with the simplifier theorem sign_mul (a b : A) : sign (a * b) = sign a * sign b := sorry theorem abs_eq_sign_mul (a : A) : abs a = sign a * a := lt.by_cases (assume H1 : 0 < a, calc abs a = a : abs_of_pos H1 ... = 1 * a : by rewrite one_mul ... = sign a * a : by rewrite (sign_of_pos H1)) (assume H1 : 0 = a, calc abs a = abs 0 : by rewrite H1 ... = 0 : by rewrite abs_zero ... = 0 * a : by rewrite zero_mul ... = sign 0 * a : by rewrite sign_zero ... = sign a * a : by rewrite H1) (assume H1 : a < 0, calc abs a = -a : abs_of_neg H1 ... = -1 * a : by rewrite neg_eq_neg_one_mul ... = sign a * a : by rewrite (sign_of_neg H1)) theorem eq_sign_mul_abs (a : A) : a = sign a * abs a := lt.by_cases (assume H1 : 0 < a, calc a = abs a : abs_of_pos H1 ... = 1 * abs a : by rewrite one_mul ... = sign a * abs a : by rewrite (sign_of_pos H1)) (assume H1 : 0 = a, calc a = 0 : H1⁻¹ ... = 0 * abs a : by rewrite zero_mul ... = sign 0 * abs a : by rewrite sign_zero ... = sign a * abs a : by rewrite H1) (assume H1 : a < 0, calc a = -(-a) : by rewrite neg_neg ... = -abs a : by rewrite (abs_of_neg H1) ... = -1 * abs a : by rewrite neg_eq_neg_one_mul ... = sign a * abs a : by rewrite (sign_of_neg H1)) theorem abs_dvd_iff_dvd (a b : A) : (abs a | b) ↔ (a | b) := abs.by_cases !iff.refl !neg_dvd_iff_dvd theorem dvd_abs_iff (a b : A) : (a | abs b) ↔ (a | b) := abs.by_cases !iff.refl !dvd_neg_iff_dvd theorem abs_mul (a b : A) : abs (a * b) = abs a * abs b := or.elim (le.total 0 a) (assume H1 : 0 ≤ a, or.elim (le.total 0 b) (assume H2 : 0 ≤ b, calc abs (a * b) = a * b : abs_of_nonneg (mul_nonneg H1 H2) ... = abs a * b : by rewrite (abs_of_nonneg H1) ... = abs a * abs b : by rewrite (abs_of_nonneg H2)) (assume H2 : b ≤ 0, calc abs (a * b) = -(a * b) : abs_of_nonpos (mul_nonpos_of_nonneg_of_nonpos H1 H2) ... = a * -b : by rewrite neg_mul_eq_mul_neg ... = abs a * -b : by rewrite (abs_of_nonneg H1) ... = abs a * abs b : by rewrite (abs_of_nonpos H2))) (assume H1 : a ≤ 0, or.elim (le.total 0 b) (assume H2 : 0 ≤ b, calc abs (a * b) = -(a * b) : abs_of_nonpos (mul_nonpos_of_nonpos_of_nonneg H1 H2) ... = -a * b : by rewrite neg_mul_eq_neg_mul ... = abs a * b : by rewrite (abs_of_nonpos H1) ... = abs a * abs b : by rewrite (abs_of_nonneg H2)) (assume H2 : b ≤ 0, calc abs (a * b) = a * b : abs_of_nonneg (mul_nonneg_of_nonpos_of_nonpos H1 H2) ... = -a * -b : by rewrite neg_mul_neg ... = abs a * -b : by rewrite (abs_of_nonpos H1) ... = abs a * abs b : by rewrite (abs_of_nonpos H2))) theorem abs_mul_self (a : A) : abs a * abs a = a * a := abs.by_cases rfl !neg_mul_neg end /- TODO: Multiplication and one, starting with mult_right_le_one_le. -/ end algebra
80fb7c0157ca57c835f59560eef61a2d6cf532fc
e39f04f6ff425fe3b3f5e26a8998b817d1dba80f
/category_theory/natural_isomorphism.lean
e1ba6d3768f08f370e496c951a49af9fd962e610
[ "Apache-2.0" ]
permissive
kristychoi/mathlib
c504b5e8f84e272ea1d8966693c42de7523bf0ec
257fd84fe98927ff4a5ffe044f68c4e9d235cc75
refs/heads/master
1,586,520,722,896
1,544,030,145,000
1,544,031,933,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,385
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Tim Baumann, Stephen Morgan, Scott Morrison import category_theory.isomorphism import category_theory.functor_category open category_theory namespace category_theory.nat_iso universes u₁ u₂ v₁ v₂ variables {C : Type u₁} [𝒞 : category.{u₁ v₁} C] {D : Type u₂} [𝒟 : category.{u₂ v₂} D] include 𝒞 𝒟 def app {F G : C ⥤ D} (α : F ≅ G) (X : C) : F.obj X ≅ G.obj X := { hom := α.hom.app X, inv := α.inv.app X, hom_inv_id' := begin rw [← functor.category.comp_app, iso.hom_inv_id], refl, end, inv_hom_id' := begin rw [← functor.category.comp_app, iso.inv_hom_id], refl, end } @[simp] lemma comp_app {F G H : C ⥤ D} (α : F ≅ G) (β : G ≅ H) (X : C) : app (α ≪≫ β) X = app α X ≪≫ app β X := rfl @[simp] lemma app_hom {F G : C ⥤ D} (α : F ≅ G) (X : C) : (app α X).hom = α.hom.app X := rfl @[simp] lemma app_inv {F G : C ⥤ D} (α : F ≅ G) (X : C) : (app α X).inv = α.inv.app X := rfl variables {F G : C ⥤ D} instance hom_app_is_iso (α : F ≅ G) (X : C) : is_iso (α.hom.app X) := { inv := α.inv.app X, hom_inv_id' := begin rw [←functor.category.comp_app, iso.hom_inv_id, ←functor.category.id_app] end, inv_hom_id' := begin rw [←functor.category.comp_app, iso.inv_hom_id, ←functor.category.id_app] end } instance inv_app_is_iso (α : F ≅ G) (X : C) : is_iso (α.inv.app X) := { inv := α.hom.app X, hom_inv_id' := begin rw [←functor.category.comp_app, iso.inv_hom_id, ←functor.category.id_app] end, inv_hom_id' := begin rw [←functor.category.comp_app, iso.hom_inv_id, ←functor.category.id_app] end } @[simp] lemma hom_vcomp_inv (α : F ≅ G) : (α.hom ⊟ α.inv) = nat_trans.id _ := begin have h : (α.hom ⊟ α.inv) = α.hom ≫ α.inv := rfl, rw h, rw iso.hom_inv_id, refl end @[simp] lemma inv_vcomp_hom (α : F ≅ G) : (α.inv ⊟ α.hom) = nat_trans.id _ := begin have h : (α.inv ⊟ α.hom) = α.inv ≫ α.hom := rfl, rw h, rw iso.inv_hom_id, refl end @[simp] lemma hom_app_inv_app_id (α : F ≅ G) (X : C) : α.hom.app X ≫ α.inv.app X = 𝟙 _ := begin rw ←nat_trans.vcomp_app, simp, end @[simp] lemma inv_app_hom_app_id (α : F ≅ G) (X : C) : α.inv.app X ≫ α.hom.app X = 𝟙 _ := begin rw ←nat_trans.vcomp_app, simp, end variables {X Y : C} @[simp] lemma naturality_1 (α : F ≅ G) (f : X ⟶ Y) : (α.inv.app X) ≫ (F.map f) ≫ (α.hom.app Y) = G.map f := begin erw [nat_trans.naturality, ←category.assoc, is_iso.hom_inv_id, category.id_comp] end @[simp] lemma naturality_2 (α : F ≅ G) (f : X ⟶ Y) : (α.hom.app X) ≫ (G.map f) ≫ (α.inv.app Y) = F.map f := begin erw [nat_trans.naturality, ←category.assoc, is_iso.hom_inv_id, category.id_comp] end def of_components (app : ∀ X : C, (F.obj X) ≅ (G.obj X)) (naturality : ∀ {X Y : C} (f : X ⟶ Y), (F.map f) ≫ ((app Y).hom) = ((app X).hom) ≫ (G.map f)) : F ≅ G := { hom := { app := λ X, ((app X).hom), }, inv := { app := λ X, ((app X).inv), naturality' := λ X Y f, by simpa using congr_arg (λ f, (app X).inv ≫ (f ≫ (app Y).inv)) (naturality f).symm } } @[simp] def of_components.app (app' : ∀ X : C, (F.obj X) ≅ (G.obj X)) (naturality) (X) : app (of_components app' naturality) X = app' X := by tidy @[simp] def of_components.hom_app (app : ∀ X : C, (F.obj X) ≅ (G.obj X)) (naturality) (X) : (of_components app naturality).hom.app X = (app X).hom := rfl @[simp] def of_components.inv_app (app : ∀ X : C, (F.obj X) ≅ (G.obj X)) (naturality) (X) : (of_components app naturality).inv.app X = (app X).inv := rfl end category_theory.nat_iso namespace category_theory.functor universes u₁ u₂ v₁ v₂ section variables {C : Type u₁} [𝒞 : category.{u₁ v₁} C] {D : Type u₂} [𝒟 : category.{u₂ v₂} D] include 𝒞 𝒟 @[simp] protected def id_comp (F : C ⥤ D) : functor.id C ⋙ F ≅ F := { hom := { app := λ X, 𝟙 (F.obj X) }, inv := { app := λ X, 𝟙 (F.obj X) } } @[simp] protected def comp_id (F : C ⥤ D) : F ⋙ functor.id D ≅ F := { hom := { app := λ X, 𝟙 (F.obj X) }, inv := { app := λ X, 𝟙 (F.obj X) } } universes u₃ v₃ u₄ v₄ variables {A : Type u₃} [𝒜 : category.{u₃ v₃} A] {B : Type u₄} [ℬ : category.{u₄ v₄} B] include 𝒜 ℬ variables (F : A ⥤ B) (G : B ⥤ C) (H : C ⥤ D) @[simp] protected def assoc : (F ⋙ G) ⋙ H ≅ F ⋙ (G ⋙ H ):= { hom := { app := λ X, 𝟙 (H.obj (G.obj (F.obj X))) }, inv := { app := λ X, 𝟙 (H.obj (G.obj (F.obj X))) } } -- When it's time to define monoidal categories and 2-categories, -- we'll need to add lemmas relating these natural isomorphisms, -- in particular the pentagon for the associator. end section variables {C : Type u₁} [𝒞 : category.{u₁ v₁} C] include 𝒞 def ulift_down_up : ulift_down.{u₁ v₁ u₂} C ⋙ ulift_up C ≅ functor.id (ulift.{u₂} C) := { hom := { app := λ X, @category.id (ulift.{u₂} C) _ X }, inv := { app := λ X, @category.id (ulift.{u₂} C) _ X } } def ulift_up_down : ulift_up.{u₁ v₁ u₂} C ⋙ ulift_down C ≅ functor.id C := { hom := { app := λ X, 𝟙 X }, inv := { app := λ X, 𝟙 X } } end end category_theory.functor
0b7da914bea802ff80ab215c5269bd49968a9d5c
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/set/sigma.lean
d66f01ca457dd42754240cd718514b2d1f142ddc
[ "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
8,001
lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import data.set.basic /-! # Sets in sigma types This file defines `set.sigma`, the indexed sum of sets. -/ namespace set variables {ι ι' : Type*} {α β : ι → Type*} {s s₁ s₂ : set ι} {t t₁ t₂ : Π i, set (α i)} {u : set (Σ i, α i)} {x : Σ i, α i} {i j : ι} {a : α i} @[simp] theorem range_sigma_mk (i : ι) : range (sigma.mk i : α i → sigma α) = sigma.fst ⁻¹' {i} := begin apply subset.antisymm, { rintros _ ⟨b, rfl⟩, simp }, { rintros ⟨x, y⟩ (rfl|_), exact mem_range_self y } end theorem preimage_image_sigma_mk_of_ne (h : i ≠ j) (s : set (α j)) : sigma.mk i ⁻¹' (sigma.mk j '' s) = ∅ := by { ext x, simp [h.symm] } lemma image_sigma_mk_preimage_sigma_map_subset {β : ι' → Type*} (f : ι → ι') (g : Π i, α i → β (f i)) (i : ι) (s : set (β (f i))) : sigma.mk i '' (g i ⁻¹' s) ⊆ sigma.map f g ⁻¹' (sigma.mk (f i) '' s) := image_subset_iff.2 $ λ x hx, ⟨g i x, hx, rfl⟩ lemma image_sigma_mk_preimage_sigma_map {β : ι' → Type*} {f : ι → ι'} (hf : function.injective f) (g : Π i, α i → β (f i)) (i : ι) (s : set (β (f i))) : sigma.mk i '' (g i ⁻¹' s) = sigma.map f g ⁻¹' (sigma.mk (f i) '' s) := begin refine (image_sigma_mk_preimage_sigma_map_subset f g i s).antisymm _, rintro ⟨j, x⟩ ⟨y, hys, hxy⟩, simp only [hf.eq_iff, sigma.map] at hxy, rcases hxy with ⟨rfl, hxy⟩, rw [heq_iff_eq] at hxy, subst y, exact ⟨x, hys, rfl⟩ end /-- Indexed sum of sets. `s.sigma t` is the set of dependent pairs `⟨i, a⟩` such that `i ∈ s` and `a ∈ t i`.-/ protected def sigma (s : set ι) (t : Π i, set (α i)) : set (Σ i, α i) := {x | x.1 ∈ s ∧ x.2 ∈ t x.1} @[simp] lemma mem_sigma_iff : x ∈ s.sigma t ↔ x.1 ∈ s ∧ x.2 ∈ t x.1 := iff.rfl @[simp] lemma mk_sigma_iff : (⟨i, a⟩ : Σ i, α i) ∈ s.sigma t ↔ i ∈ s ∧ a ∈ t i := iff.rfl lemma mk_mem_sigma (hi : i ∈ s) (ha : a ∈ t i) : (⟨i, a⟩ : Σ i, α i) ∈ s.sigma t := ⟨hi, ha⟩ lemma sigma_mono (hs : s₁ ⊆ s₂) (ht : ∀ i, t₁ i ⊆ t₂ i) : s₁.sigma t₁ ⊆ s₂.sigma t₂ := λ x hx, ⟨hs hx.1, ht _ hx.2⟩ lemma sigma_subset_iff : s.sigma t ⊆ u ↔ ∀ ⦃i⦄, i ∈ s → ∀ ⦃a⦄, a ∈ t i → (⟨i, a⟩ : Σ i, α i) ∈ u := ⟨λ h i hi a ha, h $ mk_mem_sigma hi ha, λ h ⟨i, a⟩ ha, h ha.1 ha.2⟩ lemma forall_sigma_iff {p : (Σ i, α i) → Prop} : (∀ x ∈ s.sigma t, p x) ↔ ∀ ⦃i⦄, i ∈ s → ∀ ⦃a⦄, a ∈ t i → p ⟨i, a⟩ := sigma_subset_iff lemma exists_sigma_iff {p : (Σ i, α i) → Prop} : (∃ x ∈ s.sigma t, p x) ↔ ∃ (i ∈ s) (a ∈ t i), p ⟨i, a⟩ := ⟨λ ⟨⟨i, a⟩, ha, h⟩, ⟨i, ha.1, a, ha.2, h⟩, λ ⟨i, hi, a, ha, h⟩, ⟨⟨i, a⟩, ⟨hi, ha⟩, h⟩⟩ @[simp] lemma sigma_empty : s.sigma (λ _, (∅ : set (α i))) = ∅ := ext $ λ _, and_false _ @[simp] lemma empty_sigma : (∅ : set ι).sigma t = ∅ := ext $ λ _, false_and _ lemma univ_sigma_univ : (@univ ι).sigma (λ _, @univ (α i)) = univ := ext $ λ _, true_and _ @[simp] lemma sigma_univ : s.sigma (λ _, univ : Π i, set (α i)) = sigma.fst ⁻¹' s := ext $ λ _, and_true _ @[simp] lemma singleton_sigma : ({i} : set ι).sigma t = sigma.mk i '' t i := ext $ λ x, begin split, { obtain ⟨j, a⟩ := x, rintro ⟨(rfl : j = i), ha⟩, exact mem_image_of_mem _ ha }, { rintro ⟨b, hb, rfl⟩, exact ⟨rfl, hb⟩ } end @[simp] lemma sigma_singleton {a : Π i, α i} : s.sigma (λ i, ({a i} : set (α i))) = (λ i, sigma.mk i $ a i) '' s := by { ext ⟨x, y⟩, simp [and.left_comm, eq_comm] } lemma singleton_sigma_singleton {a : Π i, α i} : ({i} : set ι).sigma (λ i, ({a i} : set (α i))) = {⟨i, a i⟩} := by rw [sigma_singleton, image_singleton] @[simp] lemma union_sigma : (s₁ ∪ s₂).sigma t = s₁.sigma t ∪ s₂.sigma t := ext $ λ _, or_and_distrib_right @[simp] lemma sigma_union : s.sigma (λ i, t₁ i ∪ t₂ i) = s.sigma t₁ ∪ s.sigma t₂ := ext $ λ _, and_or_distrib_left lemma sigma_inter_sigma : s₁.sigma t₁ ∩ s₂.sigma t₂ = (s₁ ∩ s₂).sigma (λ i, t₁ i ∩ t₂ i) := by { ext ⟨x, y⟩, simp [and_assoc, and.left_comm] } lemma insert_sigma : (insert i s).sigma t = (sigma.mk i '' t i) ∪ s.sigma t := by rw [insert_eq, union_sigma, singleton_sigma] lemma sigma_insert {a : Π i, α i} : s.sigma (λ i, insert (a i) (t i)) = ((λ i, ⟨i, a i⟩) '' s) ∪ s.sigma t := by simp_rw [insert_eq, sigma_union, sigma_singleton] lemma sigma_preimage_eq {f : ι' → ι} {g : Π i, β i → α i} : (f ⁻¹' s).sigma (λ i, g (f i) ⁻¹' t (f i)) = (λ p : Σ i, β (f i), sigma.mk _ (g _ p.2)) ⁻¹' (s.sigma t) := rfl lemma sigma_preimage_left {f : ι' → ι} : (f ⁻¹' s).sigma (λ i, t (f i)) = (λ p : Σ i, α (f i), sigma.mk _ p.2) ⁻¹' (s.sigma t) := rfl lemma sigma_preimage_right {g : Π i, β i → α i} : s.sigma (λ i, g i ⁻¹' t i) = (λ p : Σ i, β i, sigma.mk p.1 (g _ p.2)) ⁻¹' (s.sigma t) := rfl lemma preimage_sigma_map_sigma {α' : ι' → Type*} (f : ι → ι') (g : Π i, α i → α' (f i)) (s : set ι') (t : Π i, set (α' i)) : sigma.map f g ⁻¹' (s.sigma t) = (f ⁻¹' s).sigma (λ i, g i ⁻¹' t (f i)) := rfl @[simp] lemma mk_preimage_sigma (hi : i ∈ s) : sigma.mk i ⁻¹' s.sigma t = t i := ext $ λ _, and_iff_right hi @[simp] lemma mk_preimage_sigma_eq_empty (hi : i ∉ s) : sigma.mk i ⁻¹' s.sigma t = ∅ := ext $ λ _, iff_of_false (hi ∘ and.left) id lemma mk_preimage_sigma_eq_if [decidable_pred (∈ s)] : sigma.mk i ⁻¹' s.sigma t = if i ∈ s then t i else ∅ := by split_ifs; simp [h] lemma mk_preimage_sigma_fn_eq_if {β : Type*} [decidable_pred (∈ s)] (g : β → α i) : (λ b, sigma.mk i (g b)) ⁻¹' s.sigma t = if i ∈ s then g ⁻¹' t i else ∅ := ext $ λ _, by split_ifs; simp [h] lemma sigma_univ_range_eq {f : Π i, α i → β i} : (univ : set ι).sigma (λ i, range (f i)) = range (λ x : Σ i, α i, ⟨x.1, f _ x.2⟩) := ext $ by simp [range] protected lemma nonempty.sigma : s.nonempty → (∀ i, (t i).nonempty) → (s.sigma t : set _).nonempty := λ ⟨i, hi⟩ h, let ⟨a, ha⟩ := h i in ⟨⟨i, a⟩, hi, ha⟩ lemma nonempty.sigma_fst : (s.sigma t : set _).nonempty → s.nonempty := λ ⟨x, hx⟩, ⟨x.1, hx.1⟩ lemma nonempty.sigma_snd : (s.sigma t : set _).nonempty → ∃ i ∈ s, (t i).nonempty := λ ⟨x, hx⟩, ⟨x.1, hx.1, x.2, hx.2⟩ lemma sigma_nonempty_iff : (s.sigma t : set _).nonempty ↔ ∃ i ∈ s, (t i).nonempty := ⟨nonempty.sigma_snd, λ ⟨i, hi, a, ha⟩, ⟨⟨i, a⟩, hi, ha⟩⟩ lemma sigma_eq_empty_iff : s.sigma t = ∅ ↔ ∀ i ∈ s, t i = ∅ := not_nonempty_iff_eq_empty.symm.trans $ sigma_nonempty_iff.not.trans $ by simp only [not_nonempty_iff_eq_empty, not_exists] lemma image_sigma_mk_subset_sigma_left {a : Π i, α i} (ha : ∀ i, a i ∈ t i) : (λ i, sigma.mk i (a i)) '' s ⊆ s.sigma t := image_subset_iff.2 $ λ i hi, ⟨hi, ha _⟩ lemma image_sigma_mk_subset_sigma_right (hi : i ∈ s) : sigma.mk i '' t i ⊆ s.sigma t := image_subset_iff.2 $ λ a, and.intro hi lemma sigma_subset_preimage_fst (s : set ι) (t : Π i, set (α i)) : s.sigma t ⊆ sigma.fst ⁻¹' s := λ a, and.left lemma fst_image_sigma_subset (s : set ι) (t : Π i, set (α i)) : sigma.fst '' s.sigma t ⊆ s := image_subset_iff.2 $ λ a, and.left lemma fst_image_sigma (s : set ι) (ht : ∀ i, (t i).nonempty) : sigma.fst '' s.sigma t = s := (fst_image_sigma_subset _ _).antisymm $ λ i hi, let ⟨a, ha⟩ := ht i in ⟨⟨i, a⟩, ⟨hi, ha⟩, rfl⟩ lemma sigma_diff_sigma : s₁.sigma t₁ \ s₂.sigma t₂ = s₁.sigma (t₁ \ t₂) ∪ (s₁ \ s₂).sigma t₁ := ext $ λ x, by by_cases h₁ : x.1 ∈ s₁; by_cases h₂ : x.2 ∈ t₁ x.1; simp [*, ←imp_iff_or_not] end set
e863d64775b1827179188cf1d215c65c71a66cd8
8b9f17008684d796c8022dab552e42f0cb6fb347
/hott/init/util.hlean
650904a28d9c8ee2504792173d269e64ecd794f9
[ "Apache-2.0" ]
permissive
chubbymaggie/lean
0d06ae25f9dd396306fb02190e89422ea94afd7b
d2c7b5c31928c98f545b16420d37842c43b4ae9a
refs/heads/master
1,611,313,622,901
1,430,266,839,000
1,430,267,083,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
538
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: init.util Author: Leonardo de Moura Auxiliary definitions used by automation -/ prelude import init.trunc open is_trunc definition eq_rec_eq.{l₁ l₂} {A : Type.{l₁}} {B : A → Type.{l₂}} [h : is_hset A] {a : A} (b : B a) (p : a = a) : b = @eq.rec.{l₂ l₁} A a (λ (a' : A) (h : a = a'), B a') b a p := eq.rec_on (is_hset.elim (eq.refl a) p) (eq.refl (eq.rec_on (eq.refl a) b))
4b421357a37a63eed59da8b6d6a349a8fd7e6f57
2765b6350acb5144a537270d178c576b75af60e5
/abdullah-conjecture/abdullah.lean
fec5b6656e534d88eaac3e1755cb1b54843a7ebd
[]
no_license
Lambda-Jakarta/research
c46506173ef935f3670c02de8bd3dd8c80c8a257
6804cc0e6283fa1dbe7470c9fc4c770aaf6549f6
refs/heads/master
1,617,984,886,327
1,522,358,325,000
1,522,358,339,000
125,716,718
2
0
null
null
null
null
UTF-8
Lean
false
false
6,281
lean
-- 2018-01-04 -- Erik Dominikus -- These are the definitions required to state the things we want to prove. definition Cont (r : Type) (a : Type) : Type := (a → r) → r structure Functor (m : Type → Type) : Type 1 := mk :: (map : Π {a b}, (a → b) → m a → m b) (pure : Π {a}, a → m a) (p0 : Π {a}, @map a a id = id) (p1 : Π {a b c} (f : b → c) (g : a → b), map (f ∘ g) = map f ∘ map g) (p2 : Π {a b} (f : a → b) x, map f (pure x) = pure (f x)) structure Monad (m : Type → Type) : Type 1 := mk :: (functor : Functor m) (join : Π {a}, m (m a) → m a) definition Monad.pure : Π {m a}, Monad m → (a → m a) := λ _ _ mi, Functor.pure (Monad.functor mi) definition instance_Functor_Cont (r) : Functor (λ a, Cont r a) := { map := λ a b (f : a → b) (ma : (a → r) → r), λ (c : b → r), begin let d : a → r := λ x, c (f x), exact ma d end, pure := λ _ x, λ c, c x, p0 := begin intros, refl end, p1 := begin intros, refl end, p2 := begin intros, simp end, } definition instance_Monad_Cont : Π {r}, Monad (Cont r) := λ r, { functor := instance_Functor_Cont r, join := λ a (m : (((a → r) → r) → r) → r), begin intro c0, let d0 : ((a → r) → r) → r := λ c1, c1 c0, exact m d0 end, } definition sum.map_both {a b c d} (f : a → c) (g : b → d) (s : a ⊕ b) : c ⊕ d := match s with | sum.inl x := sum.inl (f x) | sum.inr x := sum.inr (g x) end -- Hom_1 and Hom_2 are the statements we want to prove. definition Hom_1 (f : Type → Type) := Π {a : Type}, (Π {m}, Monad m → f (m a)) → (Π {r : Type}, f (Cont r a)) definition Hom_2 (f : Type → Type) := Π {a : Type}, (Π {r : Type}, f (Cont r a)) → (Π {m}, Monad m → f (m a)) -- This is a proof of Hom_1. theorem hom_1_trivial (f : Type → Type) : Hom_1 f := begin intros a hm r, let m := Cont r, let j := hm instance_Monad_Cont, exact j end -- Here we tell Lean how to construct a Haskell 98 type endofunction. -- This describes all the possible ways to construct a rank-1 (Haskell 98) type endofunction. -- See `render` for what this represents. inductive endo | con : Π {t : Type}, t → endo -- c, and proof of inhabitedness | var : endo -- a (the only type variable in a rank-1 type endofunction body) | arr : endo → endo → endo | prod : endo → endo → endo | sum : endo → endo → endo -- `render e` is the type endofunction represented by `e`. definition render : endo → (Type → Type) | (@endo.con c _) := λ t, c | (endo.var) := λ t, t | (endo.arr a b) := λ t, render a t → render b t | (endo.prod a b) := λ t, render a t × render b t | (endo.sum a b) := λ t, render a t ⊕ render b t -- This is used in the theorem `hom_2`. -- `lem_render_m_to_cont` enables us to transform `m t` to `Cont (m t) t`. -- `lem_render_cont_to_m` enables us to transform `Cont (m t)` t to `m t`. mutual lemma lem_render_m_to_cont, lem_render_cont_to_m with lem_render_m_to_cont : Π (a : endo) (m : Type → Type) (mi : Monad m) t (ra : render a (m t)), render a (Cont (m t) t) | (@endo.con c i) := begin intros, exact i end | (endo.var) := begin intros, intros c, exact ra end | (endo.arr u v) := begin intros, let ra0 : render u (m t) → render v (m t) := ra, have goal : render u (Cont (m t) t) → render v (Cont (m t) t) := begin intros ru, apply lem_render_m_to_cont v m mi t, apply ra0, apply lem_render_cont_to_m u m mi t, exact ru end, exact goal end | (endo.prod u v) := begin intros, apply @prod.map (render u (m t)) (render u (Cont (m t) t)) (render v (m t)) (render v (Cont (m t) t)), apply lem_render_m_to_cont u m mi t, apply lem_render_m_to_cont v m mi t, exact ra end | (endo.sum u v) := begin intros, apply @sum.map_both (render u (m t)) (render v (m t)) (render u (Cont (m t) t)) (render v (Cont (m t) t)), apply lem_render_m_to_cont u m mi t, apply lem_render_m_to_cont v m mi t, exact ra end with lem_render_cont_to_m : Π a (m : Type → Type) (mi : Monad m) t (ra : render a (Cont (m t) t)), render a (m t) | (@endo.con c i) := begin intros, exact i end | (endo.var) := begin intros, exact ra (Monad.pure mi) end | (endo.arr u v) := begin intros, let ra0 : render u (Cont (m t) t) → render v (Cont (m t) t) := ra, have goal : render u (m t) → render v (m t) := begin intros ru, apply lem_render_cont_to_m v m mi t, apply ra0, apply lem_render_m_to_cont u m mi t, exact ru end, exact goal end | (endo.prod u v) := begin intros, apply @prod.map (render u (Cont (m t) t)) (render u (m t)) (render v (Cont (m t) t)) (render v (m t)), apply lem_render_cont_to_m u m mi t, apply lem_render_cont_to_m v m mi t, exact ra end | (endo.sum u v) := begin intros, apply @sum.map_both (render u (Cont (m t) t)) (render v (Cont (m t) t)) (render u (m t)) (render v (m t)), apply lem_render_cont_to_m u m mi t, apply lem_render_cont_to_m v m mi t, exact ra end -- This is the proposed proof of the non-trivial part of Abdullah conjecture for all Haskell 98 type endofunctions. theorem hom_2 : Π (e : endo), Hom_2 (render e) | (@endo.con c i) := begin intros t h m mi, exact i end | (endo.var) := begin intros t h m mi, exact @h (m t) (Monad.pure mi) end | (endo.arr u v) := begin intros t h m mi, have goal : render u (m t) → render v (m t) := begin intros ru, apply lem_render_cont_to_m v m mi t, let hh : render u (Cont (m t) t) → render v (Cont (m t) t) := @h (m t), apply hh, apply lem_render_m_to_cont u m mi t, exact ru end, exact goal end | (endo.prod u v) := begin intros t h m mi, apply @prod.map (render u (Cont (m t) t)) (render u (m t)) (render v (Cont (m t) t)) (render v (m t)), exact lem_render_cont_to_m u m mi t, exact lem_render_cont_to_m v m mi t, exact @h (m t) end | (endo.sum u v) := begin intros t h m mi, apply @sum.map_both (render u (Cont (m t) t)) (render v (Cont (m t) t)) (render u (m t)) (render v (m t)), exact lem_render_cont_to_m u m mi t, exact lem_render_cont_to_m v m mi t, exact @h (m t) end
d6dea95f57b85a0338d5b0c58f77b5a45aa391c8
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/change_tac.lean
da2b9cb838f44a7d541f38c6fadd68d7603f56ba
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
711
lean
example : 1 + 2 = 3 := begin change 2 + 1 = 3, trace_state, refl end example : 1 + 2 = 3 := begin change 2 + 2 = 3 -- ERROR end example (h : 1 + 2 = 3) : 2 + 2 = 4 := begin change 2 + 1 = 3 at h, trace_state, refl end example (h : 1 + 2 = 3) : 2 + 2 = 4 := begin change 2 + 1 = 3 at h h, -- ERROR end example (h : 1 + 2 = 3) : 2 + 2 = 4 := begin change 2 + 1 = 3 at *, -- ERROR end example (h : 1 + 2 = 3) : 1 + 2 = 3 := begin change 1 + 2 with 2 + 1 at h, trace_state, refl end example (h : 1 + 2 = 1 + 2 + 1) : 1 + 2 = 3 := begin change 1 + 2 with 3 at *, trace_state, refl end example (h : 1 + 2 = 1 + 2 + 1) : 1 + 2 = 3 := begin change 1 + 2 with 4 at *, -- ERROR end
c7c036a28d3bed500bfdb711922f4ed31764dc90
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/group_theory/coset_auto.lean
8ba77bc74d832dcc832ef07946b8ff8a7a127a1e
[]
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
9,757
lean
/- Copyright (c) 2018 Mitchell Rowett. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mitchell Rowett, Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.group_theory.subgroup import Mathlib.PostPort universes u_1 namespace Mathlib /-- The left coset `a*s` corresponding to an element `a : α` and a subset `s : set α` -/ def left_coset {α : Type u_1} [Mul α] (a : α) (s : set α) : set α := (fun (x : α) => a * x) '' s /-- The right coset `s*a` corresponding to an element `a : α` and a subset `s : set α` -/ def right_coset {α : Type u_1} [Mul α] (s : set α) (a : α) : set α := (fun (x : α) => x * a) '' s theorem mem_left_coset {α : Type u_1} [Mul α] {s : set α} {x : α} (a : α) (hxS : x ∈ s) : a * x ∈ left_coset a s := set.mem_image_of_mem (fun (b : α) => a * b) hxS theorem mem_right_coset {α : Type u_1} [Mul α] {s : set α} {x : α} (a : α) (hxS : x ∈ s) : x * a ∈ right_coset s a := set.mem_image_of_mem (fun (b : α) => b * a) hxS /-- Equality of two left cosets `a*s` and `b*s` -/ def left_coset_equiv {α : Type u_1} [Mul α] (s : set α) (a : α) (b : α) := left_coset a s = left_coset b s theorem left_add_coset_equiv_rel {α : Type u_1} [Add α] (s : set α) : equivalence (left_add_coset_equiv s) := mk_equivalence (left_add_coset_equiv s) (fun (a : α) => rfl) (fun (a b : α) => Eq.symm) fun (a b c : α) => Eq.trans @[simp] theorem left_coset_assoc {α : Type u_1} [semigroup α] (s : set α) (a : α) (b : α) : left_coset a (left_coset b s) = left_coset (a * b) s := sorry @[simp] theorem left_add_coset_assoc {α : Type u_1} [add_semigroup α] (s : set α) (a : α) (b : α) : left_add_coset a (left_add_coset b s) = left_add_coset (a + b) s := sorry @[simp] theorem right_coset_assoc {α : Type u_1} [semigroup α] (s : set α) (a : α) (b : α) : right_coset (right_coset s a) b = right_coset s (a * b) := sorry @[simp] theorem right_add_coset_assoc {α : Type u_1} [add_semigroup α] (s : set α) (a : α) (b : α) : right_add_coset (right_add_coset s a) b = right_add_coset s (a + b) := sorry theorem left_add_coset_right_add_coset {α : Type u_1} [add_semigroup α] (s : set α) (a : α) (b : α) : right_add_coset (left_add_coset a s) b = left_add_coset a (right_add_coset s b) := sorry @[simp] theorem one_left_coset {α : Type u_1} [monoid α] (s : set α) : left_coset 1 s = s := sorry @[simp] theorem zero_left_add_coset {α : Type u_1} [add_monoid α] (s : set α) : left_add_coset 0 s = s := sorry @[simp] theorem right_coset_one {α : Type u_1} [monoid α] (s : set α) : right_coset s 1 = s := sorry @[simp] theorem right_add_coset_zero {α : Type u_1} [add_monoid α] (s : set α) : right_add_coset s 0 = s := sorry theorem mem_own_left_coset {α : Type u_1} [monoid α] (s : submonoid α) (a : α) : a ∈ left_coset a ↑s := sorry theorem mem_own_right_add_coset {α : Type u_1} [add_monoid α] (s : add_submonoid α) (a : α) : a ∈ right_add_coset (↑s) a := sorry theorem mem_left_coset_left_coset {α : Type u_1} [monoid α] (s : submonoid α) {a : α} (ha : left_coset a ↑s = ↑s) : a ∈ s := eq.mpr (id (Eq._oldrec (Eq.refl (a ∈ s)) (Eq.symm (propext submonoid.mem_coe)))) (eq.mpr (id (Eq._oldrec (Eq.refl (a ∈ ↑s)) (Eq.symm ha))) (mem_own_left_coset s a)) theorem mem_right_add_coset_right_add_coset {α : Type u_1} [add_monoid α] (s : add_submonoid α) {a : α} (ha : right_add_coset (↑s) a = ↑s) : a ∈ s := eq.mpr (id (Eq._oldrec (Eq.refl (a ∈ s)) (Eq.symm (propext add_submonoid.mem_coe)))) (eq.mpr (id (Eq._oldrec (Eq.refl (a ∈ ↑s)) (Eq.symm ha))) (mem_own_right_add_coset s a)) theorem mem_left_coset_iff {α : Type u_1} [group α] {s : set α} {x : α} (a : α) : x ∈ left_coset a s ↔ a⁻¹ * x ∈ s := sorry theorem mem_right_coset_iff {α : Type u_1} [group α] {s : set α} {x : α} (a : α) : x ∈ right_coset s a ↔ x * (a⁻¹) ∈ s := sorry theorem left_coset_mem_left_coset {α : Type u_1} [group α] (s : subgroup α) {a : α} (ha : a ∈ s) : left_coset a ↑s = ↑s := sorry theorem right_add_coset_mem_right_add_coset {α : Type u_1} [add_group α] (s : add_subgroup α) {a : α} (ha : a ∈ s) : right_add_coset (↑s) a = ↑s := sorry theorem normal_of_eq_cosets {α : Type u_1} [group α] (s : subgroup α) (N : subgroup.normal s) (g : α) : left_coset g ↑s = right_coset (↑s) g := sorry theorem eq_cosets_of_normal {α : Type u_1} [group α] (s : subgroup α) (h : ∀ (g : α), left_coset g ↑s = right_coset (↑s) g) : subgroup.normal s := sorry theorem normal_iff_eq_add_cosets {α : Type u_1} [add_group α] (s : add_subgroup α) : add_subgroup.normal s ↔ ∀ (g : α), left_add_coset g ↑s = right_add_coset (↑s) g := { mp := normal_of_eq_add_cosets s, mpr := eq_add_cosets_of_normal s } namespace quotient_group /-- The equivalence relation corresponding to the partition of a group by left cosets of a subgroup.-/ def Mathlib.quotient_add_group.left_rel {α : Type u_1} [add_group α] (s : add_subgroup α) : setoid α := setoid.mk (fun (x y : α) => -x + y ∈ s) sorry protected instance left_rel_decidable {α : Type u_1} [group α] (s : subgroup α) [d : decidable_pred fun (a : α) => a ∈ s] : DecidableRel setoid.r := fun (_x _x_1 : α) => d (_x⁻¹ * _x_1) /-- `quotient s` is the quotient type representing the left cosets of `s`. If `s` is a normal subgroup, `quotient s` is a group -/ def quotient {α : Type u_1} [group α] (s : subgroup α) := quotient (left_rel s) end quotient_group namespace quotient_add_group /-- `quotient s` is the quotient type representing the left cosets of `s`. If `s` is a normal subgroup, `quotient s` is a group -/ def quotient {α : Type u_1} [add_group α] (s : add_subgroup α) := quotient (left_rel s) end quotient_add_group namespace quotient_group protected instance Mathlib.quotient_add_group.fintype {α : Type u_1} [add_group α] [fintype α] (s : add_subgroup α) [DecidableRel setoid.r] : fintype (quotient_add_group.quotient s) := quotient.fintype (quotient_add_group.left_rel s) /-- The canonical map from a group `α` to the quotient `α/s`. -/ def Mathlib.quotient_add_group.mk {α : Type u_1} [add_group α] {s : add_subgroup α} (a : α) : quotient_add_group.quotient s := quotient.mk' a theorem induction_on {α : Type u_1} [group α] {s : subgroup α} {C : quotient s → Prop} (x : quotient s) (H : ∀ (z : α), C (mk z)) : C x := quotient.induction_on' x H protected instance quotient.has_coe_t {α : Type u_1} [group α] {s : subgroup α} : has_coe_t α (quotient s) := has_coe_t.mk mk theorem induction_on' {α : Type u_1} [group α] {s : subgroup α} {C : quotient s → Prop} (x : quotient s) (H : ∀ (z : α), C ↑z) : C x := quotient.induction_on' x H protected instance quotient.inhabited {α : Type u_1} [group α] (s : subgroup α) : Inhabited (quotient s) := { default := ↑1 } protected theorem eq {α : Type u_1} [group α] {s : subgroup α} {a : α} {b : α} : ↑a = ↑b ↔ a⁻¹ * b ∈ s := quotient.eq' theorem Mathlib.quotient_add_group.eq_class_eq_left_coset {α : Type u_1} [add_group α] (s : add_subgroup α) (g : α) : (set_of fun (x : α) => ↑x = ↑g) = left_add_coset g ↑s := sorry theorem preimage_image_coe {α : Type u_1} [group α] (N : subgroup α) (s : set α) : coe ⁻¹' (coe '' s) = set.Union fun (x : ↥N) => (fun (y : α) => y * ↑x) '' s := sorry end quotient_group namespace subgroup /-- The natural bijection between the cosets `g*s` and `s` -/ def Mathlib.add_subgroup.left_coset_equiv_add_subgroup {α : Type u_1} [add_group α] {s : add_subgroup α} (g : α) : ↥(left_add_coset g ↑s) ≃ ↥s := equiv.mk (fun (x : ↥(left_add_coset g ↑s)) => { val := -g + subtype.val x, property := sorry }) (fun (x : ↥s) => { val := g + subtype.val x, property := sorry }) sorry sorry /-- A (non-canonical) bijection between a group `α` and the product `(α/s) × s` -/ def Mathlib.add_subgroup.add_group_equiv_quotient_times_add_subgroup {α : Type u_1} [add_group α] {s : add_subgroup α} : α ≃ quotient_add_group.quotient s × ↥s := equiv.trans (equiv.trans (equiv.trans (equiv.symm (equiv.sigma_preimage_equiv quotient_add_group.mk)) (equiv.sigma_congr_right fun (L : quotient_add_group.quotient s) => eq.mpr sorry (id (eq.mpr sorry (equiv.refl (Subtype fun (x : α) => quotient.mk' x = L)))))) (equiv.sigma_congr_right fun (L : quotient_add_group.quotient s) => add_subgroup.left_coset_equiv_add_subgroup (quotient.out' L))) (equiv.sigma_equiv_prod (quotient_add_group.quotient s) ↥s) end subgroup namespace quotient_group -- FIXME -- why is there no `to_additive`? /-- If `s` is a subgroup of the group `α`, and `t` is a subset of `α/s`, then there is a (typically non-canonical) bijection between the preimage of `t` in `α` and the product `s × t`. -/ def preimage_mk_equiv_subgroup_times_set {α : Type u_1} [group α] (s : subgroup α) (t : set (quotient s)) : ↥(mk ⁻¹' t) ≃ ↥s × ↥t := (fun (h : ∀ {x : quotient s} {a : α}, x ∈ t → a ∈ s → quotient.mk' (quotient.out' x * a) = quotient.mk' (quotient.out' x)) => equiv.mk (fun (_x : ↥(mk ⁻¹' t)) => sorry) (fun (_x : ↥s × ↥t) => sorry) sorry sorry) sorry end quotient_group /-- We use the class `has_coe_t` instead of `has_coe` if the first argument is a variable, end Mathlib
627fdfde0ea9f7995486950582041c4cfae19391
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/group_theory/perm/concrete_cycle.lean
e0cdd83978f47fa72820d5f24a75ed3d45bdc5a4
[ "Apache-2.0" ]
permissive
dexmagic/mathlib
ff48eefc56e2412429b31d4fddd41a976eb287ce
7a5d15a955a92a90e1d398b2281916b9c41270b2
refs/heads/master
1,693,481,322,046
1,633,360,193,000
1,633,360,193,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,944
lean
/- Copyright (c) 2021 Yakov Pechersky. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yakov Pechersky -/ import group_theory.perm.list import data.list.cycle import group_theory.perm.cycle_type /-! # Properties of cyclic permutations constructed from lists In the following, `{α : Type*} [fintype α] [decidable_eq α]`. ## Main definitions * `cycle.form_perm`: the cyclic permutation created by looping over a `cycle α` * `equiv.perm.to_list`: the list formed by iterating application of a permutation ## Main results * `list.is_cycle_form_perm`: a nontrivial list without duplicates, when interpreted as a permutation, is cyclic -/ open equiv equiv.perm list namespace list variables {α : Type*} [decidable_eq α] {l l' : list α} lemma form_perm_disjoint_iff (hl : nodup l) (hl' : nodup l') (hn : 2 ≤ l.length) (hn' : 2 ≤ l'.length) : perm.disjoint (form_perm l) (form_perm l') ↔ l.disjoint l' := begin rw [disjoint_iff_eq_or_eq, list.disjoint], split, { rintro h x hx hx', specialize h x, rw [form_perm_apply_mem_eq_self_iff _ hl _ hx, form_perm_apply_mem_eq_self_iff _ hl' _ hx'] at h, rcases h with hl | hl'; linarith }, { intros h x, by_cases hx : x ∈ l; by_cases hx' : x ∈ l', { exact (h hx hx').elim }, all_goals { have := form_perm_eq_self_of_not_mem _ _ ‹_›, tauto } } end lemma is_cycle_form_perm (hl : nodup l) (hn : 2 ≤ l.length) : is_cycle (form_perm l) := begin cases l with x l, { norm_num at hn }, induction l with y l IH generalizing x, { norm_num at hn }, { use x, split, { rwa form_perm_apply_mem_ne_self_iff _ hl _ (mem_cons_self _ _) }, { intros w hw, have : w ∈ (x :: y :: l) := mem_of_form_perm_ne_self _ _ hw, obtain ⟨k, hk, rfl⟩ := nth_le_of_mem this, use k, simp only [gpow_coe_nat, form_perm_pow_apply_head _ _ hl k, nat.mod_eq_of_lt hk] } } end lemma pairwise_same_cycle_form_perm (hl : nodup l) (hn : 2 ≤ l.length) : pairwise (l.form_perm.same_cycle) l := pairwise.imp_mem.mpr (pairwise_of_forall (λ x y hx hy, (is_cycle_form_perm hl hn).same_cycle ((form_perm_apply_mem_ne_self_iff _ hl _ hx).mpr hn) ((form_perm_apply_mem_ne_self_iff _ hl _ hy).mpr hn))) lemma cycle_of_form_perm (hl : nodup l) (hn : 2 ≤ l.length) (x) : cycle_of l.attach.form_perm x = l.attach.form_perm := have hn : 2 ≤ l.attach.length := by rwa ← length_attach at hn, have hl : l.attach.nodup := by rwa ← nodup_attach at hl, (is_cycle_form_perm hl hn).cycle_of_eq ((form_perm_apply_mem_ne_self_iff _ hl _ (mem_attach _ _)).mpr hn) lemma cycle_type_form_perm (hl : nodup l) (hn : 2 ≤ l.length) : cycle_type l.attach.form_perm = {l.length} := begin rw ←length_attach at hn, rw ←nodup_attach at hl, rw cycle_type_eq [l.attach.form_perm], { simp only [map, function.comp_app], rw [support_form_perm_of_nodup _ hl, card_to_finset, erase_dup_eq_self.mpr hl], { simpa }, { intros x h, simpa [h, nat.succ_le_succ_iff] using hn } }, { simp }, { simpa using is_cycle_form_perm hl hn }, { simp } end lemma form_perm_apply_mem_eq_next (hl : nodup l) (x : α) (hx : x ∈ l) : form_perm l x = next l x hx := begin obtain ⟨k, hk, rfl⟩ := nth_le_of_mem hx, rw [next_nth_le _ hl, form_perm_apply_nth_le _ hl] end end list namespace cycle variables {α : Type*} [decidable_eq α] (s s' : cycle α) /-- A cycle `s : cycle α` , given `nodup s` can be interpreted as a `equiv.perm α` where each element in the list is permuted to the next one, defined as `form_perm`. -/ def form_perm : Π (s : cycle α) (h : nodup s), equiv.perm α := λ s, quot.hrec_on s (λ l h, form_perm l) (λ l₁ l₂ (h : l₁ ~r l₂), begin ext, { exact h.nodup_iff }, { intros h₁ h₂ _, exact heq_of_eq (form_perm_eq_of_is_rotated h₁ h) } end) @[simp] lemma form_perm_coe (l : list α) (hl : l.nodup) : form_perm (l : cycle α) hl = l.form_perm := rfl lemma form_perm_subsingleton (s : cycle α) (h : subsingleton s) : form_perm s h.nodup = 1 := begin induction s using quot.induction_on, simp only [form_perm_coe, mk_eq_coe], simp only [length_subsingleton_iff, length_coe, mk_eq_coe] at h, cases s with hd tl, { simp }, { simp only [length_eq_zero, add_le_iff_nonpos_left, list.length, nonpos_iff_eq_zero] at h, simp [h] } end lemma is_cycle_form_perm (s : cycle α) (h : nodup s) (hn : nontrivial s) : is_cycle (form_perm s h) := begin induction s using quot.induction_on, exact list.is_cycle_form_perm h (length_nontrivial hn) end lemma support_form_perm [fintype α] (s : cycle α) (h : nodup s) (hn : nontrivial s) : support (form_perm s h) = s.to_finset := begin induction s using quot.induction_on, refine support_form_perm_of_nodup s h _, rintro _ rfl, simpa [nat.succ_le_succ_iff] using length_nontrivial hn end lemma form_perm_eq_self_of_not_mem (s : cycle α) (h : nodup s) (x : α) (hx : x ∉ s) : form_perm s h x = x := begin induction s using quot.induction_on, simpa using list.form_perm_eq_self_of_not_mem _ _ hx end lemma form_perm_apply_mem_eq_next (s : cycle α) (h : nodup s) (x : α) (hx : x ∈ s) : form_perm s h x = next s h x hx := begin induction s using quot.induction_on, simpa using list.form_perm_apply_mem_eq_next h _ _ end lemma form_perm_reverse (s : cycle α) (h : nodup s) : form_perm s.reverse (nodup_reverse_iff.mpr h) = (form_perm s h)⁻¹ := begin induction s using quot.induction_on, simpa using form_perm_reverse _ h end lemma form_perm_eq_form_perm_iff {α : Type*} [decidable_eq α] {s s' : cycle α} {hs : s.nodup} {hs' : s'.nodup} : s.form_perm hs = s'.form_perm hs' ↔ s = s' ∨ s.subsingleton ∧ s'.subsingleton := begin rw [cycle.length_subsingleton_iff, cycle.length_subsingleton_iff], revert s s', intros s s', apply quotient.induction_on₂' s s', intros l l', simpa using form_perm_eq_form_perm_iff end end cycle variables {α : Type*} namespace equiv.perm variables [fintype α] [decidable_eq α] (p : equiv.perm α) (x : α) /-- `equiv.perm.to_list (f : perm α) (x : α)` generates the list `[x, f x, f (f x), ...]` until looping. That means when `f x = x`, `to_list f x = []`. -/ def to_list : list α := (list.range (cycle_of p x).support.card).map (λ k, (p ^ k) x) @[simp] lemma to_list_one : to_list (1 : perm α) x = [] := by simp [to_list, cycle_of_one] @[simp] lemma to_list_eq_nil_iff {p : perm α} {x} : to_list p x = [] ↔ x ∉ p.support := by simp [to_list] @[simp] lemma length_to_list : length (to_list p x) = (cycle_of p x).support.card := by simp [to_list] lemma to_list_ne_singleton (y : α) : to_list p x ≠ [y] := begin intro H, simpa [card_support_ne_one] using congr_arg length H end lemma two_le_length_to_list_iff_mem_support {p : perm α} {x : α} : 2 ≤ length (to_list p x) ↔ x ∈ p.support := by simp lemma length_to_list_pos_of_mem_support (h : x ∈ p.support) : 0 < length (to_list p x) := zero_lt_two.trans_le (two_le_length_to_list_iff_mem_support.mpr h) lemma nth_le_to_list (n : ℕ) (hn : n < length (to_list p x)) : nth_le (to_list p x) n hn = (p ^ n) x := by simp [to_list] lemma to_list_nth_le_zero (h : x ∈ p.support) : (to_list p x).nth_le 0 (length_to_list_pos_of_mem_support _ _ h) = x := by simp [to_list] variables {p} {x} lemma mem_to_list_iff {y : α} : y ∈ to_list p x ↔ same_cycle p x y ∧ x ∈ p.support := begin simp only [to_list, mem_range, mem_map], split, { rintro ⟨n, hx, rfl⟩, refine ⟨⟨n, rfl⟩, _⟩, contrapose! hx, rw ←support_cycle_of_eq_nil_iff at hx, simp [hx] }, { rintro ⟨h, hx⟩, simpa using same_cycle.nat_of_mem_support _ h hx } end lemma nodup_to_list (p : perm α) (x : α) : nodup (to_list p x) := begin by_cases hx : p x = x, { rw [←not_mem_support, ←to_list_eq_nil_iff] at hx, simp [hx] }, have hc : is_cycle (cycle_of p x) := is_cycle_cycle_of p hx, rw nodup_iff_nth_le_inj, rintros n m hn hm, rw [length_to_list, ←order_of_is_cycle hc] at hm hn, rw [←cycle_of_apply_self, ←ne.def, ←mem_support] at hx, rw [nth_le_to_list, nth_le_to_list, ←cycle_of_pow_apply_self p x n, ←cycle_of_pow_apply_self p x m], cases n; cases m, { simp }, { rw [←hc.mem_support_pos_pow_iff_of_lt_order_of m.zero_lt_succ hm, mem_support, cycle_of_pow_apply_self] at hx, simp [hx.symm] }, { rw [←hc.mem_support_pos_pow_iff_of_lt_order_of n.zero_lt_succ hn, mem_support, cycle_of_pow_apply_self] at hx, simp [hx] }, intro h, have hn' : ¬ order_of (p.cycle_of x) ∣ n.succ := nat.not_dvd_of_pos_of_lt n.zero_lt_succ hn, have hm' : ¬ order_of (p.cycle_of x) ∣ m.succ := nat.not_dvd_of_pos_of_lt m.zero_lt_succ hm, rw ←hc.support_pow_eq_iff at hn' hm', rw [←nat.mod_eq_of_lt hn, ←nat.mod_eq_of_lt hm, ←pow_inj_mod], refine support_congr _ _, { rw [hm', hn'], exact finset.subset.refl _ }, { rw hm', intros y hy, obtain ⟨k, rfl⟩ := hc.exists_pow_eq (mem_support.mp hx) (mem_support.mp hy), rw [←mul_apply, (commute.pow_pow_self _ _ _).eq, mul_apply, h, ←mul_apply, ←mul_apply, (commute.pow_pow_self _ _ _).eq] } end lemma next_to_list_eq_apply (p : perm α) (x y : α) (hy : y ∈ to_list p x) : next (to_list p x) y hy = p y := begin rw mem_to_list_iff at hy, obtain ⟨k, hk, hk'⟩ := hy.left.nat_of_mem_support _ hy.right, rw ←nth_le_to_list p x k (by simpa using hk) at hk', simp_rw ←hk', rw [next_nth_le _ (nodup_to_list _ _), nth_le_to_list, nth_le_to_list, ←mul_apply, ←pow_succ, length_to_list, pow_apply_eq_pow_mod_order_of_cycle_of_apply p (k + 1), order_of_is_cycle], exact is_cycle_cycle_of _ (mem_support.mp hy.right) end lemma to_list_pow_apply_eq_rotate (p : perm α) (x : α) (k : ℕ) : p.to_list ((p ^ k) x) = (p.to_list x).rotate k := begin apply ext_le, { simp }, { intros n hn hn', rw [nth_le_to_list, nth_le_rotate, nth_le_to_list, length_to_list, pow_mod_card_support_cycle_of_self_apply, pow_add, mul_apply] } end lemma same_cycle.to_list_is_rotated {f : perm α} {x y : α} (h : same_cycle f x y) : to_list f x ~r to_list f y := begin by_cases hx : x ∈ f.support, { obtain ⟨_ | k, hk, hy⟩ := h.nat_of_mem_support _ hx, { simp only [coe_one, id.def, pow_zero] at hy, simp [hy] }, use k.succ, rw [←to_list_pow_apply_eq_rotate, hy] }, { rw [to_list_eq_nil_iff.mpr hx, is_rotated_nil_iff', eq_comm, to_list_eq_nil_iff], rwa ←h.mem_support_iff } end lemma pow_apply_mem_to_list_iff_mem_support {n : ℕ} : (p ^ n) x ∈ p.to_list x ↔ x ∈ p.support := begin rw [mem_to_list_iff, and_iff_right_iff_imp], refine λ _, same_cycle.symm _, rw same_cycle_pow_left_iff end lemma to_list_form_perm_nil (x : α) : to_list (form_perm ([] : list α)) x = [] := by simp lemma to_list_form_perm_singleton (x y : α) : to_list (form_perm [x]) y = [] := by simp lemma to_list_form_perm_nontrivial (l : list α) (hl : 2 ≤ l.length) (hn : nodup l) : to_list (form_perm l) (l.nth_le 0 (zero_lt_two.trans_le hl)) = l := begin have hc : l.form_perm.is_cycle := list.is_cycle_form_perm hn hl, have hs : l.form_perm.support = l.to_finset, { refine support_form_perm_of_nodup _ hn _, rintro _ rfl, simpa [nat.succ_le_succ_iff] using hl }, rw [to_list, hc.cycle_of_eq (mem_support.mp _), hs, card_to_finset, erase_dup_eq_self.mpr hn], { refine list.ext_le (by simp) (λ k hk hk', _), simp [form_perm_pow_apply_nth_le _ hn, nat.mod_eq_of_lt hk'] }, { simpa [hs] using nth_le_mem _ _ _ } end lemma to_list_form_perm_is_rotated_self (l : list α) (hl : 2 ≤ l.length) (hn : nodup l) (x : α) (hx : x ∈ l): to_list (form_perm l) x ~r l := begin obtain ⟨k, hk, rfl⟩ := nth_le_of_mem hx, have hr : l ~r l.rotate k := ⟨k, rfl⟩, rw form_perm_eq_of_is_rotated hn hr, rw ←nth_le_rotate' l k k, simp only [nat.mod_eq_of_lt hk, nat.sub_add_cancel hk.le, nat.mod_self], rw [to_list_form_perm_nontrivial], { simp }, { simpa using hl }, { simpa using hn } end lemma form_perm_to_list (f : perm α) (x : α) : form_perm (to_list f x) = f.cycle_of x := begin by_cases hx : f x = x, { rw [(cycle_of_eq_one_iff f).mpr hx, to_list_eq_nil_iff.mpr (not_mem_support.mpr hx), form_perm_nil] }, ext y, by_cases hy : same_cycle f x y, { obtain ⟨k, hk, rfl⟩ := hy.nat_of_mem_support _ (mem_support.mpr hx), rw [cycle_of_apply_apply_pow_self, list.form_perm_apply_mem_eq_next (nodup_to_list f x), next_to_list_eq_apply, pow_succ, mul_apply], rw mem_to_list_iff, exact ⟨⟨k, rfl⟩, mem_support.mpr hx⟩ }, { rw [cycle_of_apply_of_not_same_cycle hy, form_perm_apply_of_not_mem], simp [mem_to_list_iff, hy] } end lemma is_cycle.exists_unique_cycle {f : perm α} (hf : is_cycle f) : ∃! (s : cycle α), ∃ (h : s.nodup), s.form_perm h = f := begin obtain ⟨x, hx, hy⟩ := id hf, refine ⟨f.to_list x, ⟨nodup_to_list f x, _⟩, _⟩, { simp [form_perm_to_list, hf.cycle_of_eq hx] }, { rintro ⟨l⟩ ⟨hn, rfl⟩, simp only [cycle.mk_eq_coe, cycle.coe_eq_coe, subtype.coe_mk, cycle.form_perm_coe], refine (to_list_form_perm_is_rotated_self _ _ hn _ _).symm, { contrapose! hx, suffices : form_perm l = 1, { simp [this] }, rw form_perm_eq_one_iff _ hn, exact nat.le_of_lt_succ hx }, { rw ←mem_to_finset, refine support_form_perm_le l _, simpa using hx } } end lemma is_cycle.exists_unique_cycle_subtype {f : perm α} (hf : is_cycle f) : ∃! (s : {s : cycle α // s.nodup}), (s : cycle α).form_perm s.prop = f := begin obtain ⟨s, ⟨hs, rfl⟩, hs'⟩ := hf.exists_unique_cycle, refine ⟨⟨s, hs⟩, rfl, _⟩, rintro ⟨t, ht⟩ ht', simpa using hs' _ ⟨ht, ht'⟩ end end equiv.perm
e59a42f8ca0265fb631905b05f14267ff39729b6
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/library/type.lean
bc25cc3208e5595c6c6f2b041ef3ada29f25af47
[ "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
384
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 notation `Prop` := Type.{0} notation [parsing-only] `Type'` := Type.{_+1} notation [parsing-only] `Type₊` := Type.{_+1} notation `Type₁` := Type.{1} notation `Type₂` := Type.{2} notation `Type₃` := Type.{3}
1ecae59de7a4e27bdbf475d77ce4d2d2a28fea7b
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/tests/lean/run/unicode.lean
774efb2d0541d12b1b99c7bd3d32ac4382c8fbd4
[ "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
144
lean
import standard variable N : Type variable α : N variable β₁ : N check β₁ variable δ : N check δ variable δ₁₁ : N check δ₁₁
91b2338bb2fd46a3098bde24789d088ba769d113
df561f413cfe0a88b1056655515399c546ff32a5
/1-tutorial-world/l2.lean
188b99c9287d691d7176822b866355a48927b0c9
[]
no_license
nicholaspun/natural-number-game-solutions
31d5158415c6f582694680044c5c6469032c2a06
1e2aed86d2e76a3f4a275c6d99e795ad30cf6df0
refs/heads/main
1,675,123,625,012
1,607,633,548,000
1,607,633,548,000
318,933,860
3
1
null
null
null
null
UTF-8
Lean
false
false
95
lean
lemma example2 (x y : mynat) (h : y = x + 7) : 2 * y = 2 * (x + 7) := begin rw ← h, refl, end
1bd2a4c912f199c4b0d006455d838fdfcd7ad1b8
0845ae2ca02071debcfd4ac24be871236c01784f
/library/init/lean/parser/parser.lean
a65caba7371e134c24bd797feeded4a149db4970
[ "Apache-2.0" ]
permissive
GaloisInc/lean4
74c267eb0e900bfaa23df8de86039483ecbd60b7
228ddd5fdcd98dd4e9c009f425284e86917938aa
refs/heads/master
1,643,131,356,301
1,562,715,572,000
1,562,715,572,000
192,390,898
0
0
null
1,560,792,750,000
1,560,792,749,000
null
UTF-8
Lean
false
false
44,149
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ prelude import init.lean.position import init.lean.syntax import init.lean.toexpr import init.lean.environment import init.lean.attributes import init.lean.parser.trie import init.lean.parser.identifier import init.lean.compiler.initattr namespace Lean namespace Parser /- Function application precedence. In the standard lean language, only two tokens have precedence higher that `appPrec`. - The token `.` has precedence `appPrec+1`. Thus, field accesses like `g (h x).f` are parsed as `g ((h x).f)`, not `(g (h x)).f` - The token `[` when not preceded with whitespace has precedence `appPrec+1`. If there is whitespace before `[`, then its precedence is `appPrec`. Thus, `f a[i]` is parsed as `f (a[i])` where `a[i]` is an "find-like operation" (e.g., array access, map access, etc.). `f a [i]` is parsed as `(f a) [i]` where `[i]` is a singleton collection (e.g., a list). -/ def appPrec : Nat := 1024 structure TokenConfig := (val : String) (lbp : Option Nat := none) (lbpNoWs : Option Nat := none) -- optional left-binding power when there is not whitespace before the token. namespace TokenConfig def beq : TokenConfig → TokenConfig → Bool | ⟨val₁, lbp₁, lbpnws₁⟩ ⟨val₂, lbp₂, lbpnws₂⟩ := val₁ == val₂ && lbp₁ == lbp₂ && lbpnws₁ == lbpnws₂ instance : HasBeq TokenConfig := ⟨beq⟩ def toStr : TokenConfig → String | ⟨val, some lbp, some lbpnws⟩ := val ++ ":" ++ toString lbp ++ ":" ++ toString lbpnws | ⟨val, some lbp, none⟩ := val ++ ":" ++ toString lbp | ⟨val, none, some lbpnws⟩ := val ++ ":none:" ++ toString lbpnws | ⟨val, none, none⟩ := val instance : HasToString TokenConfig := ⟨toStr⟩ end TokenConfig structure TokenCacheEntry := (startPos stopPos : String.Pos := 0) (token : Syntax := Syntax.missing) structure ParserCache := (tokenCache : TokenCacheEntry := {}) def initCacheForInput (input : String) : ParserCache := { tokenCache := { startPos := input.bsize + 1 /- make sure it is not a valid position -/} } structure ParserContext := (env : Environment) (input : String) (filename : String) (fileMap : FileMap) (tokens : Trie TokenConfig) structure ParserState := (stxStack : Array Syntax := Array.empty) (pos : String.Pos := 0) (cache : ParserCache := {}) (errorMsg : Option String := none) namespace ParserState @[inline] def hasError (s : ParserState) : Bool := s.errorMsg != none @[inline] def stackSize (s : ParserState) : Nat := s.stxStack.size def restore (s : ParserState) (iniStackSz : Nat) (iniPos : Nat) : ParserState := { stxStack := s.stxStack.shrink iniStackSz, errorMsg := none, pos := iniPos, .. s} def setPos (s : ParserState) (pos : Nat) : ParserState := { pos := pos, .. s } def setCache (s : ParserState) (cache : ParserCache) : ParserState := { cache := cache, .. s } def pushSyntax (s : ParserState) (n : Syntax) : ParserState := { stxStack := s.stxStack.push n, .. s } def popSyntax (s : ParserState) : ParserState := { stxStack := s.stxStack.pop, .. s } def shrinkStack (s : ParserState) (iniStackSz : Nat) : ParserState := { stxStack := s.stxStack.shrink iniStackSz, .. s } def next (s : ParserState) (input : String) (pos : Nat) : ParserState := { pos := input.next pos, .. s } def toErrorMsg (ctx : ParserContext) (s : ParserState) : String := match s.errorMsg with | none => "" | some msg => let pos := ctx.fileMap.toPosition s.pos; ctx.filename ++ ":" ++ toString pos.line ++ ":" ++ toString pos.column ++ " " ++ msg def mkNode (s : ParserState) (k : SyntaxNodeKind) (iniStackSz : Nat) : ParserState := match s with | ⟨stack, pos, cache, err⟩ => if err != none && stack.size == iniStackSz then -- If there is an error but there are no new nodes on the stack, we just return `d` s else let newNode := Syntax.node k (stack.extract iniStackSz stack.size) []; let stack := stack.shrink iniStackSz; let stack := stack.push newNode; ⟨stack, pos, cache, err⟩ def mkError (s : ParserState) (msg : String) : ParserState := match s with | ⟨stack, pos, cache, _⟩ => ⟨stack, pos, cache, some msg⟩ def mkEOIError (s : ParserState) : ParserState := s.mkError "end of input" def mkErrorAt (s : ParserState) (msg : String) (pos : String.Pos) : ParserState := match s with | ⟨stack, _, cache, _⟩ => ⟨stack, pos, cache, some msg⟩ end ParserState inductive ParserKind | leading | trailing export ParserKind (leading trailing) def ParserArg : ParserKind → Type | ParserKind.leading := Nat | ParserKind.trailing := Syntax def BasicParserFn := ParserContext → ParserState → ParserState def ParserFn (k : ParserKind) := ParserArg k → BasicParserFn instance ParserFn.inhabited (k : ParserKind) : Inhabited (ParserFn k) := ⟨fun _ _ => id⟩ inductive FirstTokens | epsilon : FirstTokens | unknown : FirstTokens | tokens : List TokenConfig → FirstTokens namespace FirstTokens def merge : FirstTokens → FirstTokens → FirstTokens | epsilon tks := tks | tks epsilon := tks | (tokens s₁) (tokens s₂) := tokens (s₁ ++ s₂) | _ _ := unknown def seq : FirstTokens → FirstTokens → FirstTokens | epsilon tks := tks | tks _ := tks def toStr : FirstTokens → String | epsilon := "epsilon" | unknown := "unknown" | (tokens tks) := toString tks instance : HasToString FirstTokens := ⟨toStr⟩ end FirstTokens structure ParserInfo := (updateTokens : Trie TokenConfig → ExceptT String Id (Trie TokenConfig) := fun tks => pure tks) (firstTokens : FirstTokens := FirstTokens.unknown) structure Parser (k : ParserKind := leading) := (info : ParserInfo := {}) (fn : ParserFn k) instance Parser.inhabited {k : ParserKind} : Inhabited (Parser k) := ⟨{ fn := fun _ _ s => s }⟩ abbrev TrailingParser := Parser trailing @[noinline] def epsilonInfo : ParserInfo := { firstTokens := FirstTokens.epsilon } @[inline] def pushLeadingFn : ParserFn trailing := fun a c s => s.pushSyntax a @[inline] def pushLeading : TrailingParser := { info := epsilonInfo, fn := pushLeadingFn } @[inline] def checkLeadingFn (p : Syntax → Bool) : ParserFn trailing := fun a c s => if p a then s else s.mkError "invalid leading token" @[inline] def checkLeading (p : Syntax → Bool) : TrailingParser := { info := epsilonInfo, fn := checkLeadingFn p } @[inline] def andthenAux (p q : BasicParserFn) : BasicParserFn := fun c s => let s := p c s; if s.hasError then s else q c s @[inline] def andthenFn {k : ParserKind} (p q : ParserFn k) : ParserFn k := fun a c s => andthenAux (p a) (q a) c s @[noinline] def andthenInfo (p q : ParserInfo) : ParserInfo := { updateTokens := fun tks => q.updateTokens tks >>= p.updateTokens, firstTokens := p.firstTokens.seq q.firstTokens } @[inline] def andthen {k : ParserKind} (p q : Parser k) : Parser k := { info := andthenInfo p.info q.info, fn := andthenFn p.fn q.fn } instance hashAndthen {k : ParserKind} : HasAndthen (Parser k) := ⟨andthen⟩ @[inline] def nodeFn {k : ParserKind} (n : SyntaxNodeKind) (p : ParserFn k) : ParserFn k | a c s := let iniSz := s.stackSize; let s := p a c s; s.mkNode n iniSz @[noinline] def nodeInfo (p : ParserInfo) : ParserInfo := { updateTokens := p.updateTokens, firstTokens := p.firstTokens } @[inline] def node {k : ParserKind} (n : SyntaxNodeKind) (p : Parser k) : Parser k := { info := nodeInfo p.info, /- Remark: the compiler currently does not eta-expand structure fields. So, we force it here to trigger inlining at `node` combinators. -/ fn := nodeFn n p.fn } @[inline] def leadingNode (n : SyntaxNodeKind) (p : Parser leading) : Parser := node n p @[inline] def trailingNode (n : SyntaxNodeKind) (p : Parser trailing) : TrailingParser := node n p @[inline] def orelseFn {k : ParserKind} (p q : ParserFn k) : ParserFn k | a c s := let iniSz := s.stackSize; let iniPos := s.pos; let s := p a c s; if s.hasError && s.pos == iniPos then q a c (s.restore iniSz iniPos) else s @[noinline] def orelseInfo (p q : ParserInfo) : ParserInfo := { updateTokens := fun tks => q.updateTokens tks >>= p.updateTokens, firstTokens := p.firstTokens.merge q.firstTokens } @[inline] def orelse {k : ParserKind} (p q : Parser k) : Parser k := { info := orelseInfo p.info q.info, fn := orelseFn p.fn q.fn } instance hashOrelse {k : ParserKind} : HasOrelse (Parser k) := ⟨orelse⟩ @[noinline] def noFirstTokenInfo (info : ParserInfo) : ParserInfo := { updateTokens := info.updateTokens } @[inline] def tryFn {k : ParserKind} (p : ParserFn k ) : ParserFn k | a c s := let iniSz := s.stackSize; let iniPos := s.pos; match p a c s with | ⟨stack, _, cache, some msg⟩ => ⟨stack.shrink iniSz, iniPos, cache, some msg⟩ | other => other @[inline] def try {k : ParserKind} (p : Parser k) : Parser k := { info := p.info, fn := tryFn p.fn } @[inline] def optionalFn {k : ParserKind} (p : ParserFn k) : ParserFn k := fun a c s => let iniSz := s.stackSize; let iniPos := s.pos; let s := p a c s; let s := if s.hasError && s.pos == iniPos then s.restore iniSz iniPos else s; s.mkNode nullKind iniSz @[inline] def optional {k : ParserKind} (p : Parser k) : Parser k := { info := noFirstTokenInfo p.info, fn := optionalFn p.fn } @[specialize] partial def manyAux {k : ParserKind} (p : ParserFn k) : ParserFn k | a c s := let iniSz := s.stackSize; let iniPos := s.pos; let s := p a c s; if s.hasError then s.restore iniSz iniPos else if iniPos == s.pos then s.mkError "invalid 'many' parser combinator application, parser did not consume anything" else manyAux a c s @[inline] def manyFn {k : ParserKind} (p : ParserFn k) : ParserFn k := fun a c s => let iniSz := s.stackSize; let s := manyAux p a c s; s.mkNode nullKind iniSz @[inline] def many {k : ParserKind} (p : Parser k) : Parser k := { info := noFirstTokenInfo p.info, fn := manyFn p.fn } @[inline] def many1Fn {k : ParserKind} (p : ParserFn k) : ParserFn k := fun a c s => let iniSz := s.stackSize; let s := andthenFn p (manyAux p) a c s; s.mkNode nullKind iniSz @[inline] def many1 {k : ParserKind} (p : Parser k) : Parser k := { info := p.info, fn := many1Fn p.fn } @[specialize] private partial def sepByFnAux {k : ParserKind} (p : ParserFn k) (sep : ParserFn k) (allowTrailingSep : Bool) (iniSz : Nat) : Bool → ParserFn k | pOpt a c s := let sz := s.stackSize; let pos := s.pos; let s := p a c s; if s.hasError then if pOpt then let s := s.restore sz pos; s.mkNode nullKind iniSz else -- append `Syntax.missing` to make clear that List is incomplete let s := s.pushSyntax Syntax.missing; s.mkNode nullKind iniSz else let sz := s.stackSize; let pos := s.pos; let s := sep a c s; if s.hasError then let s := s.restore sz pos; s.mkNode nullKind iniSz else sepByFnAux allowTrailingSep a c s @[specialize] def sepByFn {k : ParserKind} (allowTrailingSep : Bool) (p : ParserFn k) (sep : ParserFn k) : ParserFn k | a c s := let iniSz := s.stackSize; sepByFnAux p sep allowTrailingSep iniSz true a c s @[specialize] def sepBy1Fn {k : ParserKind} (allowTrailingSep : Bool) (p : ParserFn k) (sep : ParserFn k) : ParserFn k | a c s := let iniSz := s.stackSize; sepByFnAux p sep allowTrailingSep iniSz false a c s @[noinline] def sepByInfo (p sep : ParserInfo) : ParserInfo := { updateTokens := fun tks => p.updateTokens tks >>= sep.updateTokens } @[noinline] def sepBy1Info (p sep : ParserInfo) : ParserInfo := { updateTokens := fun tks => p.updateTokens tks >>= sep.updateTokens, firstTokens := p.firstTokens } @[inline] def sepBy {k : ParserKind} (p sep : Parser k) (allowTrailingSep : Bool := false) : Parser k := { info := sepByInfo p.info sep.info, fn := sepByFn allowTrailingSep p.fn sep.fn } @[inline] def sepBy1 {k : ParserKind} (p sep : Parser k) (allowTrailingSep : Bool := false) : Parser k := { info := sepBy1Info p.info sep.info, fn := sepBy1Fn allowTrailingSep p.fn sep.fn } @[specialize] partial def satisfyFn (p : Char → Bool) (errorMsg : String := "unexpected character") : BasicParserFn | c s := let i := s.pos; if c.input.atEnd i then s.mkEOIError else if p (c.input.get i) then s.next c.input i else s.mkError errorMsg @[specialize] partial def takeUntilFn (p : Char → Bool) : BasicParserFn | c s := let i := s.pos; if c.input.atEnd i then s else if p (c.input.get i) then s else takeUntilFn c (s.next c.input i) @[specialize] def takeWhileFn (p : Char → Bool) : BasicParserFn := takeUntilFn (fun c => !p c) @[inline] def takeWhile1Fn (p : Char → Bool) (errorMsg : String) : BasicParserFn := andthenAux (satisfyFn p errorMsg) (takeWhileFn p) partial def finishCommentBlock : Nat → BasicParserFn | nesting c s := let input := c.input; let i := s.pos; if input.atEnd i then s.mkEOIError else let curr := input.get i; let i := input.next i; if curr == '-' then if input.atEnd i then s.mkEOIError else let curr := input.get i; if curr == '/' then -- "-/" end of comment if nesting == 1 then s.next input i else finishCommentBlock (nesting-1) c (s.next input i) else finishCommentBlock nesting c (s.next input i) else if curr == '/' then if input.atEnd i then s.mkEOIError else let curr := input.get i; if curr == '-' then finishCommentBlock (nesting+1) c (s.next input i) else finishCommentBlock nesting c (s.setPos i) else finishCommentBlock nesting c (s.setPos i) /- Consume whitespace and comments -/ partial def whitespace : BasicParserFn | c s := let input := c.input; let i := s.pos; if input.atEnd i then s else let curr := input.get i; if curr.isWhitespace then whitespace c (s.next input i) else if curr == '-' then let i := input.next i; let curr := input.get i; if curr == '-' then andthenAux (takeUntilFn (fun c => c = '\n')) whitespace c (s.next input i) else s else if curr == '/' then let i := input.next i; let curr := input.get i; if curr == '-' then let i := input.next i; let curr := input.get i; if curr == '-' then s -- "/--" doc comment is an actual token else andthenAux (finishCommentBlock 1) whitespace c (s.next input i) else s else s def mkEmptySubstringAt (s : String) (p : Nat) : Substring := {str := s, startPos := p, stopPos := p } private def rawAux {k : ParserKind} (startPos : Nat) (trailingWs : Bool) : ParserFn k | a c s := let input := c.input; let stopPos := s.pos; let leading := mkEmptySubstringAt input startPos; let val := input.extract startPos stopPos; if trailingWs then let s := whitespace c s; let stopPos' := s.pos; let trailing := { Substring . str := input, startPos := stopPos, stopPos := stopPos' }; let atom := Syntax.atom (some { leading := leading, pos := startPos, trailing := trailing }) val; s.pushSyntax atom else let trailing := mkEmptySubstringAt input stopPos; let atom := Syntax.atom (some { leading := leading, pos := startPos, trailing := trailing }) val; s.pushSyntax atom /-- Match an arbitrary Parser and return the consumed String in a `Syntax.atom`. -/ @[inline] def rawFn {k : ParserKind} (p : ParserFn k) (trailingWs := false) : ParserFn k | a c s := let startPos := s.pos; let s := p a c s; if s.hasError then s else rawAux startPos trailingWs a c s def hexDigitFn : BasicParserFn | c s := let input := c.input; let i := s.pos; if input.atEnd i then s.mkEOIError else let curr := input.get i; let i := input.next i; if curr.isDigit || ('a' <= curr && curr <= 'f') || ('A' <= curr && curr <= 'F') then s.setPos i else s.mkError "invalid hexadecimal numeral, hexadecimal digit expected" def quotedCharFn : BasicParserFn | c s := let input := c.input; let i := s.pos; if input.atEnd i then s.mkEOIError else let curr := input.get i; if curr == '\\' || curr == '\"' || curr == '\'' || curr == '\n' || curr == '\t' then s.next input i else if curr == 'x' then andthenAux hexDigitFn hexDigitFn c (s.next input i) else if curr == 'u' then andthenAux hexDigitFn (andthenAux hexDigitFn (andthenAux hexDigitFn hexDigitFn)) c (s.next input i) else s.mkError "invalid escape sequence" /-- Push `(Syntax.node tk <new-atom>)` into syntax stack -/ def mkNodeToken (n : SyntaxNodeKind) (startPos : Nat) : BasicParserFn := fun c s => let input := c.input; let stopPos := s.pos; let leading := mkEmptySubstringAt input startPos; let val := input.extract startPos stopPos; let s := whitespace c s; let wsStopPos := s.pos; let trailing := { Substring . str := input, startPos := stopPos, stopPos := wsStopPos }; let info := { SourceInfo . leading := leading, pos := startPos, trailing := trailing }; s.pushSyntax (mkLit n val (some info)) partial def strLitFnAux (startPos : Nat) : BasicParserFn | c s := let input := c.input; let i := s.pos; if input.atEnd i then s.mkEOIError else let curr := input.get i; let s := s.setPos (input.next i); if curr == '\"' then mkNodeToken strLitKind startPos c s else if curr == '\\' then andthenAux quotedCharFn strLitFnAux c s else strLitFnAux c s def decimalNumberFn (startPos : Nat) : BasicParserFn := fun c s => let s := takeWhileFn (fun c => c.isDigit) c s; let input := c.input; let i := s.pos; let curr := input.get i; let s := /- TODO(Leo): should we use a different kind for numerals containing decimal points? -/ if curr == '.' then let i := input.next i; let curr := input.get i; if curr.isDigit then takeWhileFn (fun c => c.isDigit) c (s.setPos i) else s else s; mkNodeToken numLitKind startPos c s def binNumberFn (startPos : Nat) : BasicParserFn := fun c s => let s := takeWhile1Fn (fun c => c == '0' || c == '1') "expected binary number" c s; mkNodeToken numLitKind startPos c s def octalNumberFn (startPos : Nat) : BasicParserFn := fun c s => let s := takeWhile1Fn (fun c => '0' ≤ c && c ≤ '7') "expected octal number" c s; mkNodeToken numLitKind startPos c s def hexNumberFn (startPos : Nat) : BasicParserFn := fun c s => let s := takeWhile1Fn (fun c => ('0' ≤ c && c ≤ '9') || ('a' ≤ c && c ≤ 'f') || ('A' ≤ c && c ≤ 'F')) "expected hexadecimal number" c s; mkNodeToken numLitKind startPos c s def numberFnAux : BasicParserFn := fun c s => let input := c.input; let startPos := s.pos; if input.atEnd startPos then s.mkEOIError else let curr := input.get startPos; if curr == '0' then let i := input.next startPos; let curr := input.get i; if curr == 'b' || curr == 'B' then binNumberFn startPos c (s.next input i) else if curr == 'o' || curr == 'O' then octalNumberFn startPos c (s.next input i) else if curr == 'x' || curr == 'X' then hexNumberFn startPos c (s.next input i) else decimalNumberFn startPos c (s.setPos i) else if curr.isDigit then decimalNumberFn startPos c (s.next input startPos) else s.mkError "expected numeral" def isIdCont : String → ParserState → Bool | input s := let i := s.pos; let curr := input.get i; if curr == '.' then let i := input.next i; if input.atEnd i then false else let curr := input.get i; isIdFirst curr || isIdBeginEscape curr else false private def isToken (idStartPos idStopPos : Nat) (tk : Option TokenConfig) : Bool := match tk with | none => false | some tk => -- if a token is both a symbol and a valid identifier (i.e. a keyword), -- we want it to be recognized as a symbol tk.val.bsize ≥ idStopPos - idStopPos def mkTokenAndFixPos (startPos : Nat) (tk : Option TokenConfig) : BasicParserFn := fun c s => match tk with | none => s.mkErrorAt "token expected" startPos | some tk => let input := c.input; let leading := mkEmptySubstringAt input startPos; let val := tk.val; let stopPos := startPos + val.bsize; let s := s.setPos stopPos; let s := whitespace c s; let wsStopPos := s.pos; let trailing := { Substring . str := input, startPos := stopPos, stopPos := wsStopPos }; let atom := Syntax.atom (some { leading := leading, pos := startPos, trailing := trailing }) val; s.pushSyntax atom def mkIdResult (startPos : Nat) (tk : Option TokenConfig) (val : Name) : BasicParserFn := fun c s => let stopPos := s.pos; if isToken startPos stopPos tk then mkTokenAndFixPos startPos tk c s else let input := c.input; let rawVal := { Substring . str := input, startPos := startPos, stopPos := stopPos }; let s := whitespace c s; let trailingStopPos := s.pos; let leading := mkEmptySubstringAt input startPos; let trailing := { Substring . str := input, startPos := stopPos, stopPos := trailingStopPos }; let info := { SourceInfo . leading := leading, trailing := trailing, pos := startPos }; let atom := Syntax.ident (some info) rawVal val [] []; s.pushSyntax atom partial def identFnAux (startPos : Nat) (tk : Option TokenConfig) : Name → BasicParserFn | r c s := let input := c.input; let i := s.pos; if input.atEnd i then s.mkEOIError else let curr := input.get i; if isIdBeginEscape curr then let startPart := input.next i; let s := takeUntilFn isIdEndEscape c (s.setPos startPart); let stopPart := s.pos; let s := satisfyFn isIdEndEscape "end of escaped identifier expected" c s; if s.hasError then s else let r := Name.mkString r (input.extract startPart stopPart); if isIdCont input s then let s := s.next input s.pos; identFnAux r c s else mkIdResult startPos tk r c s else if isIdFirst curr then let startPart := i; let s := takeWhileFn isIdRest c (s.next input i); let stopPart := s.pos; let r := Name.mkString r (input.extract startPart stopPart); if isIdCont input s then let s := s.next input s.pos; identFnAux r c s else mkIdResult startPart tk r c s else mkTokenAndFixPos startPos tk c s private def tokenFnAux : BasicParserFn | c s := let input := c.input; let i := s.pos; let curr := input.get i; if curr == '\"' then strLitFnAux i c (s.next input i) else if curr.isDigit then numberFnAux c s else let (_, tk) := c.tokens.matchPrefix input i; identFnAux i tk Name.anonymous c s private def updateCache (startPos : Nat) (s : ParserState) : ParserState := match s with | ⟨stack, pos, cache, none⟩ => if stack.size == 0 then s else let tk := stack.back; ⟨stack, pos, { tokenCache := { startPos := startPos, stopPos := pos, token := tk } }, none⟩ | other => other def tokenFn : BasicParserFn := fun c s => let input := c.input; let i := s.pos; if input.atEnd i then s.mkEOIError else let tkc := s.cache.tokenCache; if tkc.startPos == i then let s := s.pushSyntax tkc.token; s.setPos tkc.stopPos else let s := tokenFnAux c s; updateCache i s def peekToken (c : ParserContext) (s : ParserState) : ParserState × Option Syntax := let iniSz := s.stackSize; let iniPos := s.pos; let s := tokenFn c s; if s.hasError then (s.restore iniSz iniPos, none) else let stx := s.stxStack.back; (s.restore iniSz iniPos, some stx) @[inline] def satisfySymbolFn (p : String → Bool) (errorMsg : String) : BasicParserFn := fun c s => let startPos := s.pos; let s := tokenFn c s; if s.hasError then s.mkErrorAt errorMsg startPos else match s.stxStack.back with | Syntax.atom _ sym => if p sym then s else s.mkErrorAt errorMsg startPos | _ => s.mkErrorAt errorMsg startPos def symbolFnAux (sym : String) (errorMsg : String) : BasicParserFn := satisfySymbolFn (fun s => s == sym) errorMsg def insertToken (sym : String) (lbp : Option Nat) (tks : Trie TokenConfig) : ExceptT String Id (Trie TokenConfig) := if sym == "" then throw "invalid empty symbol" else match tks.find sym, lbp with | none, _ => pure (tks.insert sym { val := sym, lbp := lbp }) | some _, none => pure tks | some tk, some newLbp => match tk.lbp with | none => pure (tks.insert sym { lbp := lbp, .. tk }) | some oldLbp => if newLbp == oldLbp then pure tks else throw ("precedence mismatch for '" ++ toString sym ++ "', previous: " ++ toString oldLbp ++ ", new: " ++ toString newLbp) def symbolInfo (sym : String) (lbp : Option Nat) : ParserInfo := { updateTokens := insertToken sym lbp, firstTokens := FirstTokens.tokens [ { val := sym, lbp := lbp } ] } @[inline] def symbolFn {k : ParserKind} (sym : String) : ParserFn k := fun _ => symbolFnAux sym ("expected '" ++ sym ++ "'") @[inline] def symbolAux {k : ParserKind} (sym : String) (lbp : Option Nat := none) : Parser k := let sym := sym.trim; { info := symbolInfo sym lbp, fn := symbolFn sym } @[inline] def symbol {k : ParserKind} (sym : String) (lbp : Nat) : Parser k := symbolAux sym lbp partial def strAux (sym : String) (errorMsg : String) : Nat → BasicParserFn | j c s := if sym.atEnd j then s else let i := s.pos; let input := c.input; if input.atEnd i || sym.get j != input.get i then s.mkError errorMsg else strAux (sym.next j) c (s.next input i) def insertNoWsToken (sym : String) (lbpNoWs : Option Nat) (tks : Trie TokenConfig) : ExceptT String Id (Trie TokenConfig) := if sym == "" then throw "invalid empty symbol" else match tks.find sym, lbpNoWs with | none, _ => pure (tks.insert sym { val := sym, lbpNoWs := lbpNoWs }) | some _, none => pure tks | some tk, some newLbp => match tk.lbpNoWs with | none => pure (tks.insert sym { lbpNoWs := lbpNoWs, .. tk }) | some oldLbp => if newLbp == oldLbp then pure tks else throw ("(no whitespace) precedence mismatch for '" ++ toString sym ++ "', previous: " ++ toString oldLbp ++ ", new: " ++ toString newLbp) def symbolNoWsInfo (sym : String) (lbpNoWs : Option Nat) : ParserInfo := { updateTokens := insertNoWsToken sym lbpNoWs, firstTokens := FirstTokens.tokens [ { val := sym, lbpNoWs := lbpNoWs } ] } def checkTailNoWs (left : Syntax) : Bool := match left.getTailInfo with | some info => info.trailing.stopPos == info.trailing.startPos | none => false @[inline] def symbolNoWsFnAux (sym : String) (errorMsg : String) : ParserFn trailing := fun left c s => if checkTailNoWs left then strAux sym errorMsg 0 c s else s.mkError errorMsg @[inline] def symbolNoWsFn (sym : String) : ParserFn trailing := symbolNoWsFnAux sym ("expected '" ++ sym ++ "' without whitespaces arount it") /- Similar to `symbol`, but succeeds only if there is no space whitespace after leading term and after `sym`. -/ @[inline] def symbolNoWsAux (sym : String) (lbp : Option Nat) : TrailingParser := let sym := sym.trim; { info := symbolNoWsInfo sym lbp, fn := symbolNoWsFn sym } @[inline] def symbolNoWs (sym : String) (lbp : Nat) : TrailingParser := symbolNoWsAux sym lbp def unicodeSymbolFnAux (sym asciiSym : String) (errorMsg : String) : BasicParserFn := satisfySymbolFn (fun s => s == sym || s == asciiSym) errorMsg def unicodeSymbolInfo (sym asciiSym : String) (lbp : Option Nat) : ParserInfo := { updateTokens := fun tks => insertToken sym lbp tks >>= insertToken asciiSym lbp, firstTokens := FirstTokens.tokens [ { val := sym, lbp := lbp }, { val := asciiSym, lbp := lbp } ] } @[inline] def unicodeSymbolFn {k : ParserKind} (sym asciiSym : String) : ParserFn k := fun _ => unicodeSymbolFnAux sym asciiSym ("expected '" ++ sym ++ "' or '" ++ asciiSym ++ "'") @[inline] def unicodeSymbol {k : ParserKind} (sym asciiSym : String) (lbp : Option Nat := none) : Parser k := let sym := sym.trim; let asciiSym := asciiSym.trim; { info := unicodeSymbolInfo sym asciiSym lbp, fn := unicodeSymbolFn sym asciiSym } def unicodeSymbolCheckPrecFnAux (sym asciiSym : String) (lbp : Nat) (errorMsg : String) (precErrorMsg : String) : ParserFn leading := fun (rbp : Nat) c s => if rbp > lbp then s.mkError precErrorMsg else satisfySymbolFn (fun s => s == sym || s == asciiSym) errorMsg c s @[inline] def unicodeSymbolCheckPrecFn (sym asciiSym : String) (lbp : Nat) : ParserFn leading := unicodeSymbolCheckPrecFnAux sym asciiSym lbp ("expected '" ++ sym ++ "' or '" ++ asciiSym ++ "'") ("found '" ++ sym ++ "' as expected, but brackets are needed") -- improve error message @[inline] def unicodeSymbolCheckPrec (sym asciiSym : String) (lbp : Nat) : Parser leading := let sym := sym.trim; let asciiSym := asciiSym.trim; { info := unicodeSymbolInfo sym asciiSym lbp, fn := unicodeSymbolCheckPrecFn sym asciiSym lbp } def mkAtomicInfo (k : String) : ParserInfo := { firstTokens := FirstTokens.tokens [ { val := k } ] } def numLitFn {k : ParserKind} : ParserFn k := fun _ c s => let iniPos := s.pos; let s := tokenFn c s; if s.hasError || !(s.stxStack.back.isOfKind numLitKind) then s.mkErrorAt "expected numeral" iniPos else s @[inline] def numLit {k : ParserKind} : Parser k := { fn := numLitFn, info := mkAtomicInfo "numLit" } def strLitFn {k : ParserKind} : ParserFn k := fun _ c s => let iniPos := s.pos; let s := tokenFn c s; if s.hasError || !(s.stxStack.back.isOfKind strLitKind) then s.mkErrorAt "expected string literal" iniPos else s @[inline] def strLit {k : ParserKind} : Parser k := { fn := strLitFn, info := mkAtomicInfo "strLit" } def identFn {k : ParserKind} : ParserFn k := fun _ c s => let iniPos := s.pos; let s := tokenFn c s; if s.hasError || !(s.stxStack.back.isIdent) then s.mkErrorAt "expected identifier" iniPos else s @[inline] def ident {k : ParserKind} : Parser k := { fn := identFn, info := mkAtomicInfo "ident" } def fieldIdxFn : BasicParserFn := fun c s => let iniPos := s.pos; let curr := c.input.get iniPos; if curr.isDigit && curr != '0' then let s := takeWhileFn (fun c => c.isDigit) c s; mkNodeToken fieldIdxKind iniPos c s else s.mkErrorAt "expected field index" iniPos @[inline] def fieldIdx {k : ParserKind} : Parser k := { fn := fun _ => fieldIdxFn, info := mkAtomicInfo "fieldIdx" } instance string2basic {k : ParserKind} : HasCoe String (Parser k) := ⟨symbolAux⟩ namespace ParserState def keepNewError (s : ParserState) (oldStackSize : Nat) : ParserState := match s with | ⟨stack, pos, cache, err⟩ => ⟨stack.shrink oldStackSize, pos, cache, err⟩ def keepPrevError (s : ParserState) (oldStackSize : Nat) (oldStopPos : String.Pos) (oldError : Option String) : ParserState := match s with | ⟨stack, _, cache, _⟩ => ⟨stack.shrink oldStackSize, oldStopPos, cache, oldError⟩ def mergeErrors (s : ParserState) (oldStackSize : Nat) (oldError : String) : ParserState := match s with | ⟨stack, pos, cache, some err⟩ => if oldError == err then s else ⟨stack.shrink oldStackSize, pos, cache, some (err ++ "; " ++ oldError)⟩ | other => other def mkLongestNodeAlt (s : ParserState) (startSize : Nat) : ParserState := match s with | ⟨stack, pos, cache, _⟩ => if stack.size == startSize then ⟨stack.push Syntax.missing, pos, cache, none⟩ -- parser did not create any node, then we just add `Syntax.missing` else if stack.size == startSize + 1 then s else -- parser created more than one node, combine them into a single node let node := Syntax.node nullKind (stack.extract startSize stack.size) []; let stack := stack.shrink startSize; ⟨stack.push node, pos, cache, none⟩ def keepLatest (s : ParserState) (startStackSize : Nat) : ParserState := match s with | ⟨stack, pos, cache, _⟩ => let node := stack.back; let stack := stack.shrink startStackSize; let stack := stack.push node; ⟨stack, pos, cache, none⟩ def replaceLongest (s : ParserState) (startStackSize : Nat) (prevStackSize : Nat) : ParserState := let s := s.mkLongestNodeAlt prevStackSize; s.keepLatest startStackSize end ParserState def longestMatchStep {k : ParserKind} (startSize : Nat) (startPos : String.Pos) (p : ParserFn k) : ParserFn k := fun a c s => let prevErrorMsg := s.errorMsg; let prevStopPos := s.pos; let prevSize := s.stackSize; let s := s.restore prevSize startPos; let s := p a c s; match prevErrorMsg, s.errorMsg with | none, none => -- both succeeded if s.pos > prevStopPos then s.replaceLongest startSize prevSize -- replace else if s.pos < prevStopPos then s.restore prevSize prevStopPos -- keep prev else s.mkLongestNodeAlt prevSize -- keep both | none, some _ => -- prev succeeded, current failed s.restore prevSize prevStopPos | some oldError, some _ => -- both failed if s.pos > prevStopPos then s.keepNewError prevSize else if s.pos < prevStopPos then s.keepPrevError prevSize prevStopPos prevErrorMsg else s.mergeErrors prevSize oldError | some _, none => -- prev failed, current succeeded s.mkLongestNodeAlt startSize def longestMatchMkResult (startSize : Nat) (s : ParserState) : ParserState := if !s.hasError && s.stackSize > startSize + 1 then s.mkNode choiceKind startSize else s def longestMatchFnAux {k : ParserKind} (startSize : Nat) (startPos : String.Pos) : List (Parser k) → ParserFn k | [] := fun _ _ s => longestMatchMkResult startSize s | (p::ps) := fun a c s => let s := longestMatchStep startSize startPos p.fn a c s; longestMatchFnAux ps a c s def longestMatchFn₁ {k : ParserKind} (p : ParserFn k) : ParserFn k := fun a c s => let startSize := s.stackSize; let s := p a c s; if s.hasError then s else s.mkLongestNodeAlt startSize def longestMatchFn {k : ParserKind} : List (Parser k) → ParserFn k | [] := fun _ _ s => s.mkError "longestMatch: empty list" | [p] := longestMatchFn₁ p.fn | (p::ps) := fun a c s => let startSize := s.stackSize; let startPos := s.pos; let s := p.fn a c s; if s.hasError then let s := s.shrinkStack startSize; longestMatchFnAux startSize startPos ps a c s else let s := s.mkLongestNodeAlt startSize; longestMatchFnAux startSize startPos ps a c s def anyOfFn {k : ParserKind} : List (Parser k) → ParserFn k | [] _ _ s := s.mkError "anyOf: empty list" | [p] a c s := p.fn a c s | (p::ps) a c s := orelseFn p.fn (anyOfFn ps) a c s /-- A multimap indexed by tokens. Used for indexing parsers by their leading token. -/ def TokenMap (α : Type) := RBMap Name (List α) Name.quickLt namespace TokenMap def insert {α : Type} (map : TokenMap α) (k : Name) (v : α) : TokenMap α := match map.find k with | none => map.insert k [v] | some vs => map.insert k (v::vs) instance {α : Type} : Inhabited (TokenMap α) := ⟨RBMap.empty⟩ instance {α : Type} : HasEmptyc (TokenMap α) := ⟨RBMap.empty⟩ end TokenMap structure ParsingTables := (leadingTable : TokenMap Parser := {}) (trailingTable : TokenMap TrailingParser := {}) (trailingParsers : List TrailingParser := []) -- for supporting parsers such as function application (tokens : Trie TokenConfig := {}) def currLbp (left : Syntax) (c : ParserContext) (s : ParserState) : ParserState × Nat := let (s, stx) := peekToken c s; match stx with | some (Syntax.atom _ sym) => match c.tokens.matchPrefix sym 0 with | (_, some tk) => match tk.lbp, tk.lbpNoWs with | some lbp, none => (s, lbp) | none, some lbpNoWs => (s, lbpNoWs) | some lbp, some lbpNoWs => if checkTailNoWs left then (s, lbpNoWs) else (s, lbp) | none, none => (s, 0) | _ => (s, 0) | some (Syntax.ident _ _ _ _ _) => (s, appPrec) -- TODO(Leo): add support for associating lbp with syntax node kinds. | some (Syntax.node k _ _) => if k == numLitKind || k == strLitKind || k == fieldIdxKind then (s, appPrec) else (s, 0) | _ => (s, 0) def indexed {α : Type} (map : TokenMap α) (c : ParserContext) (s : ParserState) : ParserState × List α := let (s, stx) := peekToken c s; let find (n : Name) : ParserState × List α := match map.find n with | some as => (s, as) | _ => (s, []); match stx with | some (Syntax.atom _ sym) => find (mkSimpleName sym) | some (Syntax.ident _ _ _ _ _) => find `ident | some (Syntax.node k _ _) => find k | _ => (s, []) private def mkResult (s : ParserState) (iniSz : Nat) : ParserState := if s.stackSize == iniSz + 1 then s else s.mkNode nullKind iniSz -- throw error instead? def leadingParser (kind : String) (tables : ParsingTables) : ParserFn leading := fun a c s => let iniSz := s.stackSize; let (s, ps) := indexed tables.leadingTable c s; if ps.isEmpty then s.mkError ("expected " ++ kind) else let s := longestMatchFn ps a c s; mkResult s iniSz partial def trailingLoop (kind : String) (tables : ParsingTables) (rbp : Nat) (c : ParserContext) : Syntax → ParserState → ParserState | left s := let (s, lbp) := currLbp left c s; if rbp ≥ lbp then s.pushSyntax left else let iniSz := s.stackSize; let (s, ps) := indexed tables.trailingTable c s; if ps.isEmpty && tables.trailingParsers.isEmpty then s.pushSyntax left -- no available trailing parser else let s := orelseFn (longestMatchFn ps) (anyOfFn tables.trailingParsers) left c s; if s.hasError then s else let s := mkResult s iniSz; let left := s.stxStack.back; let s := s.popSyntax; trailingLoop left s def prattParser (kind : String) (tables : ParsingTables) : ParserFn leading := fun rbp c s => let c := { tokens := tables.tokens, .. c }; let s := leadingParser kind tables rbp c s; if s.hasError then s else let left := s.stxStack.back; let s := s.popSyntax; trailingLoop kind tables rbp c left s def mkParserContext (env : Environment) (input : String) (filename : String) : ParserContext := { env := env, input := input, filename := filename, fileMap := input.toFileMap, tokens := {} } def mkParserState (input : String) : ParserState := { cache := initCacheForInput input } def runParser (env : Environment) (tables : ParsingTables) (input : String) (fileName := "<input>") (kind := "<main>") : Except String Syntax := let c := mkParserContext env input fileName; let s := mkParserState input; let s := whitespace c s; let s := prattParser kind tables (0 : Nat) c s; if s.hasError then Except.error (s.toErrorMsg c) else Except.ok s.stxStack.back def mkBuiltinParsingTablesRef : IO (IO.Ref ParsingTables) := IO.mkRef {} private def updateTokens (tables : ParsingTables) (info : ParserInfo) (declName : Name) : IO ParsingTables := match info.updateTokens tables.tokens with | Except.ok newTokens => pure { tokens := newTokens, .. tables } | Except.error msg => throw (IO.userError ("invalid builtin parser '" ++ toString declName ++ "', " ++ msg)) def addBuiltinLeadingParser (tablesRef : IO.Ref ParsingTables) (declName : Name) (p : Parser) : IO Unit := do tables ← tablesRef.get; tablesRef.reset; tables ← updateTokens tables p.info declName; match p.info.firstTokens with | FirstTokens.tokens tks => let tables := tks.foldl (fun (tables : ParsingTables) tk => { leadingTable := tables.leadingTable.insert (mkSimpleName tk.val) p, .. tables }) tables; tablesRef.set tables | _ => throw (IO.userError ("invalid builtin parser '" ++ toString declName ++ "', initial token is not statically known")) def addBuiltinTrailingParser (tablesRef : IO.Ref ParsingTables) (declName : Name) (p : TrailingParser) : IO Unit := do tables ← tablesRef.get; tablesRef.reset; tables ← updateTokens tables p.info declName; match p.info.firstTokens with | FirstTokens.tokens tks => let tables := tks.foldl (fun (tables : ParsingTables) tk => { trailingTable := tables.trailingTable.insert (mkSimpleName tk.val) p, .. tables }) tables; tablesRef.set tables | _ => let tables := { trailingParsers := p :: tables.trailingParsers, .. tables }; tablesRef.set tables def declareBuiltinParser (env : Environment) (addFnName : Name) (refDeclName : Name) (declName : Name) : IO Environment := let name := `_regBuiltinParser ++ declName; let type := Expr.app (mkConst `IO) (mkConst `Unit); let val := mkCApp addFnName [mkConst refDeclName, toExpr declName, mkConst declName]; let decl := Declaration.defnDecl { name := name, lparams := [], type := type, value := val, hints := ReducibilityHints.opaque, isUnsafe := false }; match env.addAndCompile {} decl with | none => throw (IO.userError ("failed to emit registration code for builtin parser '" ++ toString declName ++ "'")) | some env => IO.ofExcept (setInitAttr env name) def declareLeadingBuiltinParser (env : Environment) (refDeclName : Name) (declName : Name) : IO Environment := declareBuiltinParser env `Lean.Parser.addBuiltinLeadingParser refDeclName declName def declareTrailingBuiltinParser (env : Environment) (refDeclName : Name) (declName : Name) : IO Environment := declareBuiltinParser env `Lean.Parser.addBuiltinTrailingParser refDeclName declName /- The parsing tables for builtin parsers are "stored" in the extracted source code. -/ def registerBuiltinParserAttribute (attrName : Name) (refDeclName : Name) : IO Unit := registerAttribute { name := attrName, descr := "Builtin parser", add := fun env declName args persistent => do { unless args.isMissing $ throw (IO.userError ("invalid attribute '" ++ toString attrName ++ "', unexpected argument")); unless persistent $ throw (IO.userError ("invalid attribute '" ++ toString attrName ++ "', must be persistent")); match env.find declName with | none => throw "unknown declaration" | some decl => match decl.type with | Expr.const `Lean.Parser.TrailingParser _ => declareTrailingBuiltinParser env refDeclName declName | Expr.app (Expr.const `Lean.Parser.Parser _) (Expr.const `Lean.Parser.ParserKind.leading _) => declareLeadingBuiltinParser env refDeclName declName | _ => throw (IO.userError ("unexpected parser type at '" ++ toString declName ++ "' (`Parser` or `TrailingParser` expected")) }, applicationTime := AttributeApplicationTime.afterCompilation } @[init mkBuiltinParsingTablesRef] constant builtinCommandParsingTable : IO.Ref ParsingTables := default _ @[init] def regBuiltinCommandParserAttr : IO Unit := registerBuiltinParserAttribute `builtinCommandParser `Lean.Parser.builtinCommandParsingTable @[noinline] unsafe def runBuiltinParserUnsafe (kind : String) (ref : IO.Ref ParsingTables) : ParserFn leading := fun a c s => match unsafeIO (do tables ← ref.get; pure $ prattParser kind tables a c s) with | some s => s | none => s.mkError "failed to access builtin reference" @[implementedBy runBuiltinParserUnsafe] constant runBuiltinParser (kind : String) (ref : IO.Ref ParsingTables) : ParserFn leading := default _ def commandParser (rbp : Nat := 0) : Parser := { fn := fun _ => runBuiltinParser "command" builtinCommandParsingTable rbp } /- TODO(Leo): delete -/ @[init mkBuiltinParsingTablesRef] constant builtinTestParsingTable : IO.Ref ParsingTables := default _ @[init] def regBuiltinTestParserAttr : IO Unit := registerBuiltinParserAttribute `builtinTestParser `Lean.Parser.builtinTestParsingTable def testParser (rbp : Nat := 0) : Parser := { fn := fun _ => runBuiltinParser "testExpr" builtinTestParsingTable rbp } end Parser end Lean
517ee95a0ccf2e80340b084a2261eaac180b81f5
abd85493667895c57a7507870867b28124b3998f
/src/ring_theory/algebra_operations.lean
2b3f0a0cb725d11e5d8d7adc2212caf0b0db8e45
[ "Apache-2.0" ]
permissive
pechersky/mathlib
d56eef16bddb0bfc8bc552b05b7270aff5944393
f1df14c2214ee114c9738e733efd5de174deb95d
refs/heads/master
1,666,714,392,571
1,591,747,567,000
1,591,747,567,000
270,557,274
0
0
Apache-2.0
1,591,597,975,000
1,591,597,974,000
null
UTF-8
Lean
false
false
9,594
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau Multiplication and division of submodules of an algebra. -/ import ring_theory.algebra import ring_theory.ideals import algebra.pointwise universes u v open algebra local attribute [instance] set.pointwise_mul_semiring namespace submodule variables {R : Type u} [comm_ring R] section ring variables {A : Type v} [ring A] [algebra R A] variables (S T : set A) {M N P Q : submodule R A} {m n : A} instance : has_one (submodule R A) := ⟨submodule.map (of_id R A).to_linear_map (⊤ : ideal R)⟩ theorem one_eq_map_top : (1 : submodule R A) = submodule.map (of_id R A).to_linear_map (⊤ : ideal R) := rfl theorem one_eq_span : (1 : submodule R A) = span R {1} := begin apply submodule.ext, intro a, erw [mem_map, mem_span_singleton], apply exists_congr, intro r, simpa [smul_def], end theorem one_le : (1 : submodule R A) ≤ P ↔ (1 : A) ∈ P := by simpa only [one_eq_span, span_le, set.singleton_subset_iff] instance : has_mul (submodule R A) := ⟨λ M N, ⨆ s : M, N.map $ algebra.lmul R A s.1⟩ theorem mul_mem_mul (hm : m ∈ M) (hn : n ∈ N) : m * n ∈ M * N := (le_supr _ ⟨m, hm⟩ : _ ≤ M * N) ⟨n, hn, rfl⟩ theorem mul_le : M * N ≤ P ↔ ∀ (m ∈ M) (n ∈ N), m * n ∈ P := ⟨λ H m hm n hn, H $ mul_mem_mul hm hn, λ H, supr_le $ λ ⟨m, hm⟩, map_le_iff_le_comap.2 $ λ n hn, H m hm n hn⟩ @[elab_as_eliminator] protected theorem mul_induction_on {C : A → Prop} {r : A} (hr : r ∈ M * N) (hm : ∀ (m ∈ M) (n ∈ N), C (m * n)) (h0 : C 0) (ha : ∀ x y, C x → C y → C (x + y)) (hs : ∀ (r : R) x, C x → C (r • x)) : C r := (@mul_le _ _ _ _ _ _ _ ⟨C, h0, ha, hs⟩).2 hm hr variables R theorem span_mul_span : span R S * span R T = span R (S * T) := begin apply le_antisymm, { rw mul_le, intros a ha b hb, apply span_induction ha, work_on_goal 0 { intros, apply span_induction hb, work_on_goal 0 { intros, exact subset_span ⟨_, ‹_›, _, ‹_›, rfl⟩ } }, all_goals { intros, simp only [mul_zero, zero_mul, zero_mem, left_distrib, right_distrib, mul_smul_comm, smul_mul_assoc], try {apply add_mem _ _ _}, try {apply smul_mem _ _ _} }, assumption' }, { rw span_le, rintros _ ⟨a, ha, b, hb, rfl⟩, exact mul_mem_mul (subset_span ha) (subset_span hb) } end variables {R} variables (M N P Q) protected theorem mul_assoc : (M * N) * P = M * (N * P) := le_antisymm (mul_le.2 $ λ mn hmn p hp, suffices M * N ≤ (M * (N * P)).comap ((algebra.lmul R A).flip p), from this hmn, mul_le.2 $ λ m hm n hn, show m * n * p ∈ M * (N * P), from (mul_assoc m n p).symm ▸ mul_mem_mul hm (mul_mem_mul hn hp)) (mul_le.2 $ λ m hm np hnp, suffices N * P ≤ (M * N * P).comap (algebra.lmul R A m), from this hnp, mul_le.2 $ λ n hn p hp, show m * (n * p) ∈ M * N * P, from mul_assoc m n p ▸ mul_mem_mul (mul_mem_mul hm hn) hp) @[simp] theorem mul_bot : M * ⊥ = ⊥ := eq_bot_iff.2 $ mul_le.2 $ λ m hm n hn, by rw [submodule.mem_bot] at hn ⊢; rw [hn, mul_zero] @[simp] theorem bot_mul : ⊥ * M = ⊥ := eq_bot_iff.2 $ mul_le.2 $ λ m hm n hn, by rw [submodule.mem_bot] at hm ⊢; rw [hm, zero_mul] @[simp] protected theorem one_mul : (1 : submodule R A) * M = M := by { conv_lhs { rw [one_eq_span, ← span_eq M] }, erw [span_mul_span, one_mul, span_eq] } @[simp] protected theorem mul_one : M * 1 = M := by { conv_lhs { rw [one_eq_span, ← span_eq M] }, erw [span_mul_span, mul_one, span_eq] } variables {M N P Q} @[mono] theorem mul_le_mul (hmp : M ≤ P) (hnq : N ≤ Q) : M * N ≤ P * Q := mul_le.2 $ λ m hm n hn, mul_mem_mul (hmp hm) (hnq hn) theorem mul_le_mul_left (h : M ≤ N) : M * P ≤ N * P := mul_le_mul h (le_refl P) theorem mul_le_mul_right (h : N ≤ P) : M * N ≤ M * P := mul_le_mul (le_refl M) h variables (M N P) theorem mul_sup : M * (N ⊔ P) = M * N ⊔ M * P := le_antisymm (mul_le.2 $ λ m hm np hnp, let ⟨n, hn, p, hp, hnp⟩ := mem_sup.1 hnp in mem_sup.2 ⟨_, mul_mem_mul hm hn, _, mul_mem_mul hm hp, hnp ▸ (mul_add m n p).symm⟩) (sup_le (mul_le_mul_right le_sup_left) (mul_le_mul_right le_sup_right)) theorem sup_mul : (M ⊔ N) * P = M * P ⊔ N * P := le_antisymm (mul_le.2 $ λ mn hmn p hp, let ⟨m, hm, n, hn, hmn⟩ := mem_sup.1 hmn in mem_sup.2 ⟨_, mul_mem_mul hm hp, _, mul_mem_mul hn hp, hmn ▸ (add_mul m n p).symm⟩) (sup_le (mul_le_mul_left le_sup_left) (mul_le_mul_left le_sup_right)) lemma mul_subset_mul : (↑M : set A) * (↑N : set A) ⊆ (↑(M * N) : set A) := begin rintros _ ⟨i, hi, j, hj, rfl⟩, exact mul_mem_mul hi hj end lemma map_mul {A'} [ring A'] [algebra R A'] (f : A →ₐ[R] A') : map f.to_linear_map (M * N) = map f.to_linear_map M * map f.to_linear_map N := calc map f.to_linear_map (M * N) = ⨆ (i : M), (N.map (lmul R A i)).map f.to_linear_map : map_supr _ _ ... = map f.to_linear_map M * map f.to_linear_map N : begin apply congr_arg Sup, ext S, split; rintros ⟨y, hy⟩, { use [f y, mem_map.mpr ⟨y.1, y.2, rfl⟩], refine trans _ hy, ext, simp }, { obtain ⟨y', hy', fy_eq⟩ := mem_map.mp y.2, use [y', hy'], refine trans _ hy, rw f.to_linear_map_apply at fy_eq, ext, simp [fy_eq] } end variables {M N P} instance : semiring (submodule R A) := { one_mul := submodule.one_mul, mul_one := submodule.mul_one, mul_assoc := submodule.mul_assoc, zero_mul := bot_mul, mul_zero := mul_bot, left_distrib := mul_sup, right_distrib := sup_mul, ..submodule.add_comm_monoid_submodule, ..submodule.has_one, ..submodule.has_mul } variables (M) lemma pow_subset_pow {n : ℕ} : (↑M : set A)^n ⊆ ↑(M^n : submodule R A) := begin induction n with n ih, { erw [pow_zero, pow_zero, set.singleton_subset_iff], rw [mem_coe, ← one_le], exact le_refl _ }, { rw [pow_succ, pow_succ], refine set.subset.trans (set.pointwise_mul_subset_mul (set.subset.refl _) ih) _, apply mul_subset_mul } end instance span.is_semiring_hom : is_semiring_hom (submodule.span R : set A → submodule R A) := { map_zero := span_empty, map_one := show _ = map _ ⊤, by erw [← ideal.span_singleton_one, ← span_image, set.image_singleton, alg_hom.map_one]; refl, map_add := span_union, map_mul := λ s t, by erw [span_mul_span, set.pointwise_mul_eq_image] } end ring section comm_ring variables {A : Type v} [comm_ring A] [algebra R A] variables {M N : submodule R A} {m n : A} theorem mul_mem_mul_rev (hm : m ∈ M) (hn : n ∈ N) : n * m ∈ M * N := mul_comm m n ▸ mul_mem_mul hm hn variables (M N) protected theorem mul_comm : M * N = N * M := le_antisymm (mul_le.2 $ λ r hrm s hsn, mul_mem_mul_rev hsn hrm) (mul_le.2 $ λ r hrn s hsm, mul_mem_mul_rev hsm hrn) instance : comm_semiring (submodule R A) := { mul_comm := submodule.mul_comm, .. submodule.semiring } variables (R A) instance semimodule_set : semimodule (set A) (submodule R A) := { smul := λ s P, span R s * P, smul_add := λ _ _ _, mul_add _ _ _, add_smul := λ s t P, show span R (s ⊔ t) * P = _, by { erw [span_union, right_distrib] }, mul_smul := λ s t P, show _ = _ * (_ * _), by { rw [← mul_assoc, span_mul_span, set.pointwise_mul_eq_image] }, one_smul := λ P, show span R {(1 : A)} * P = _, by { conv_lhs {erw ← span_eq P}, erw [span_mul_span, one_mul, span_eq] }, zero_smul := λ P, show span R ∅ * P = ⊥, by erw [span_empty, bot_mul], smul_zero := λ _, mul_bot _ } variables {R A} lemma smul_def {s : set A} {P : submodule R A} : s • P = span R s * P := rfl lemma smul_le_smul {s t : set A} {M N : submodule R A} (h₁ : s ≤ t) (h₂ : M ≤ N) : s • M ≤ t • N := mul_le_mul (span_mono h₁) h₂ lemma smul_singleton (a : A) (M : submodule R A) : ({a} : set A) • M = M.map (lmul_left _ _ a) := begin conv_lhs {rw ← span_eq M}, change span _ _ * span _ _ = _, rw [span_mul_span], apply le_antisymm, { rw span_le, rintros _ ⟨b, hb, m, hm, rfl⟩, erw [mem_map, set.mem_singleton_iff.mp hb], exact ⟨m, hm, rfl⟩ }, { rintros _ ⟨m, hm, rfl⟩, exact subset_span ⟨a, set.mem_singleton a, m, hm, rfl⟩ } end section quotient local attribute [instance] set.smul_set_action /-- The elements of `I / J` are the `x` such that `x • J ⊆ I`. In fact, we define `x ∈ I / J` to be `∀ y ∈ J, x * y ∈ I` (see `mem_div_iff_forall_mul_mem`), which is equivalent to `x • J ⊆ I` (see `mem_div_iff_smul_subset`), but nicer to use in proofs. This is the general form of the ideal quotient, traditionally written $I : J$. -/ instance : has_div (submodule R A) := ⟨ λ I J, { carrier := { x | ∀ y ∈ J, x * y ∈ I }, zero := λ y hy, by { rw zero_mul, apply submodule.zero }, add := λ a b ha hb y hy, by { rw add_mul, exact submodule.add _ (ha _ hy) (hb _ hy) }, smul := λ r x hx y hy, by { rw algebra.smul_mul_assoc, exact submodule.smul _ _ (hx _ hy) } } ⟩ lemma mem_div_iff_forall_mul_mem {x : A} {I J : submodule R A} : x ∈ I / J ↔ ∀ y ∈ J, x * y ∈ I := iff.refl _ lemma mem_div_iff_smul_subset {x : A} {I J : submodule R A} : x ∈ I / J ↔ x • (J : set A) ⊆ I := ⟨ λ h y ⟨y', hy', y_eq_xy'⟩, by { rw y_eq_xy', apply h, assumption }, λ h y hy, h (set.smul_mem_smul_set _ hy)⟩ lemma le_div_iff {I J K : submodule R A} : I ≤ J / K ↔ ∀ (x ∈ I) (z ∈ K), x * z ∈ J := iff.refl _ end quotient end comm_ring end submodule
160b19c3945a3c9a709e4d9dc192226aa70b9834
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/tactic/linarith/datatypes.lean
e94ab033e108f6fc7156c135b5161666b56c7a8f
[ "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
12,771
lean
/- Copyright (c) 2020 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import meta.rb_map import tactic.ring import tactic.linarith.lemmas /-! # Datatypes for `linarith` Some of the data structures here are used in multiple parts of the tactic. We split them into their own file. This file also contains a few convenient auxiliary functions. -/ declare_trace linarith open native namespace linarith /-- A shorthand for tracing when the `trace.linarith` option is set to true. -/ meta def linarith_trace {α} [has_to_tactic_format α] (s : α) : tactic unit := tactic.when_tracing `linarith (tactic.trace s) /-- A shorthand for tracing the types of a list of proof terms when the `trace.linarith` option is set to true. -/ meta def linarith_trace_proofs (s : string := "") (l : list expr) : tactic unit := tactic.when_tracing `linarith $ do tactic.trace s, l.mmap tactic.infer_type >>= tactic.trace /-! ### Linear expressions -/ /-- A linear expression is a list of pairs of variable indices and coefficients, representing the sum of the products of each coefficient with its corresponding variable. Some functions on `linexp` assume that `n : ℕ` occurs at most once as the first element of a pair, and that the list is sorted in decreasing order of the first argument. This is not enforced by the type but the operations here preserve it. -/ @[reducible] def linexp : Type := list (ℕ × ℤ) namespace linexp /-- Add two `linexp`s together componentwise. Preserves sorting and uniqueness of the first argument. -/ meta def add : linexp → linexp → linexp | [] a := a | a [] := a | (a@(n1,z1)::t1) (b@(n2,z2)::t2) := if n1 < n2 then b::add (a::t1) t2 else if n2 < n1 then a::add t1 (b::t2) else let sum := z1 + z2 in if sum = 0 then add t1 t2 else (n1, sum)::add t1 t2 /-- `l.scale c` scales the values in `l` by `c` without modifying the order or keys. -/ def scale (c : ℤ) (l : linexp) : linexp := if c = 0 then [] else if c = 1 then l else l.map $ λ ⟨n, z⟩, (n, z*c) /-- `l.get n` returns the value in `l` associated with key `n`, if it exists, and `none` otherwise. This function assumes that `l` is sorted in decreasing order of the first argument, that is, it will return `none` as soon as it finds a key smaller than `n`. -/ def get (n : ℕ) : linexp → option ℤ | [] := none | ((a, b)::t) := if a < n then none else if a = n then some b else get t /-- `l.contains n` is true iff `n` is the first element of a pair in `l`. -/ def contains (n : ℕ) : linexp → bool := option.is_some ∘ get n /-- `l.zfind n` returns the value associated with key `n` if there is one, and 0 otherwise. -/ def zfind (n : ℕ) (l : linexp) : ℤ := match l.get n with | none := 0 | some v := v end /-- `l.vars` returns the list of variables that occur in `l`. -/ def vars (l : linexp) : list ℕ := l.map prod.fst /-- Defines a lex ordering on `linexp`. This function is performance critical. -/ def cmp : linexp → linexp → ordering | [] [] := ordering.eq | [] _ := ordering.lt | _ [] := ordering.gt | ((n1,z1)::t1) ((n2,z2)::t2) := if n1 < n2 then ordering.lt else if n2 < n1 then ordering.gt else if z1 < z2 then ordering.lt else if z2 < z1 then ordering.gt else cmp t1 t2 end linexp /-! ### Inequalities -/ /-- The three-element type `ineq` is used to represent the strength of a comparison between terms. -/ @[derive decidable_eq, derive inhabited] inductive ineq : Type | eq | le | lt namespace ineq /-- `max R1 R2` computes the strength of the sum of two inequalities. If `t1 R1 0` and `t2 R2 0`, then `t1 + t2 (max R1 R2) 0`. -/ def max : ineq → ineq → ineq | lt a := lt | a lt := lt | le a := le | a le := le | eq eq := eq /-- `ineq` is ordered `eq < le < lt`. -/ def cmp : ineq → ineq → ordering | eq eq := ordering.eq | eq _ := ordering.lt | le le := ordering.eq | le lt := ordering.lt | lt lt := ordering.eq | _ _ := ordering.gt /-- Prints an `ineq` as the corresponding infix symbol. -/ def to_string : ineq → string | eq := "=" | le := "≤" | lt := "<" /-- Finds the name of a multiplicative lemma corresponding to an inequality strength. -/ meta def to_const_mul_nm : ineq → name | lt := ``mul_neg | le := ``mul_nonpos | eq := ``mul_eq instance : has_to_string ineq := ⟨ineq.to_string⟩ meta instance : has_to_format ineq := ⟨λ i, ineq.to_string i⟩ end ineq /-! ### Comparisons with 0 -/ /-- The main datatype for FM elimination. Variables are represented by natural numbers, each of which has an integer coefficient. Index 0 is reserved for constants, i.e. `coeffs.find 0` is the coefficient of 1. The represented term is `coeffs.sum (λ ⟨k, v⟩, v * Var[k])`. str determines the strength of the comparison -- is it < 0, ≤ 0, or = 0? -/ @[derive inhabited] structure comp : Type := (str : ineq) (coeffs : linexp) /-- `c.vars` returns the list of variables that appear in the linear expression contained in `c`. -/ def comp.vars : comp → list ℕ := linexp.vars ∘ comp.coeffs /-- `comp.coeff_of c a` projects the coefficient of variable `a` out of `c`. -/ def comp.coeff_of (c : comp) (a : ℕ) : ℤ := c.coeffs.zfind a /-- `comp.scale c n` scales the coefficients of `c` by `n`. -/ def comp.scale (c : comp) (n : ℕ) : comp := { c with coeffs := c.coeffs.scale n } /-- `comp.add c1 c2` adds the expressions represented by `c1` and `c2`. The coefficient of variable `a` in `c1.add c2` is the sum of the coefficients of `a` in `c1` and `c2`. -/ meta def comp.add (c1 c2 : comp) : comp := ⟨c1.str.max c2.str, c1.coeffs.add c2.coeffs⟩ /-- `comp` has a lex order. First the `ineq`s are compared, then the `coeff`s. -/ meta def comp.cmp : comp → comp → ordering | ⟨str1, coeffs1⟩ ⟨str2, coeffs2⟩ := match str1.cmp str2 with | ordering.lt := ordering.lt | ordering.gt := ordering.gt | ordering.eq := coeffs1.cmp coeffs2 end /-- A `comp` represents a contradiction if its expression has no coefficients and its strength is <, that is, it represents the fact `0 < 0`. -/ meta def comp.is_contr (c : comp) : bool := c.coeffs.empty ∧ c.str = ineq.lt meta instance comp.to_format : has_to_format comp := ⟨λ p, to_fmt p.coeffs ++ to_string p.str ++ "0"⟩ /-! ### Parsing into linear form -/ /-! ### Control -/ /-- A preprocessor transforms a proof of a proposition into a proof of a different propositon. The return type is `list expr`, since some preprocessing steps may create multiple new hypotheses, and some may remove a hypothesis from the list. A "no-op" preprocessor should return its input as a singleton list. -/ meta structure preprocessor : Type := (name : string) (transform : expr → tactic (list expr)) /-- Some preprocessors need to examine the full list of hypotheses instead of working item by item. As with `preprocessor`, the input to a `global_preprocessor` is replaced by, not added to, its output. -/ meta structure global_preprocessor : Type := (name : string) (transform : list expr → tactic (list expr)) /-- Some preprocessors perform branching case splits. A `branch` is used to track one of these case splits. The first component, an `expr`, is the goal corresponding to this branch of the split, given as a metavariable. The `list expr` component is the list of hypotheses for `linarith` in this branch. Every `expr` in this list should be type correct in the context of the associated goal. -/ meta def branch : Type := expr × list expr /-- Some preprocessors perform branching case splits. A `global_branching_preprocessor` produces a list of branches to run. Each branch is independent, so hypotheses that appear in multiple branches should be duplicated. The preprocessor is responsible for making sure that each branch contains the correct goal metavariable. -/ meta structure global_branching_preprocessor : Type := (name : string) (transform : list expr → tactic (list branch)) /-- A `preprocessor` lifts to a `global_preprocessor` by folding it over the input list. -/ meta def preprocessor.globalize (pp : preprocessor) : global_preprocessor := { name := pp.name, transform := list.mfoldl (λ ret e, do l' ← pp.transform e, return (l' ++ ret)) [] } /-- A `global_preprocessor` lifts to a `global_branching_preprocessor` by producing only one branch. -/ meta def global_preprocessor.branching (pp : global_preprocessor) : global_branching_preprocessor := { name := pp.name, transform := λ l, do g ← tactic.get_goal, singleton <$> prod.mk g <$> pp.transform l } /-- `process pp l` runs `pp.transform` on `l` and returns the result, tracing the result if `trace.linarith` is on. -/ meta def global_branching_preprocessor.process (pp : global_branching_preprocessor) (l : list expr) : tactic (list branch) := do l ← pp.transform l, when (l.length > 1) $ linarith_trace format!"Preprocessing: {pp.name} has branched, with branches:", l.mmap' $ λ l, tactic.set_goals [l.1] >> linarith_trace_proofs (to_string format!"Preprocessing: {pp.name}") l.2, return l meta instance preprocessor_to_gb_preprocessor : has_coe preprocessor global_branching_preprocessor := ⟨global_preprocessor.branching ∘ preprocessor.globalize⟩ meta instance global_preprocessor_to_gb_preprocessor : has_coe global_preprocessor global_branching_preprocessor := ⟨global_preprocessor.branching⟩ /-- A `certificate_oracle` is a function `produce_certificate : list comp → ℕ → tactic (rb_map ℕ ℕ)`. `produce_certificate hyps max_var` tries to derive a contradiction from the comparisons in `hyps` by eliminating all variables ≤ `max_var`. If successful, it returns a map `coeff : ℕ → ℕ` as a certificate. This map represents that we can find a contradiction by taking the sum `∑ (coeff i) * hyps[i]`. The default `certificate_oracle` used by `linarith` is `linarith.fourier_motzkin.produce_certificate`. -/ meta def certificate_oracle : Type := list comp → ℕ → tactic (rb_map ℕ ℕ) /-- A configuration object for `linarith`. -/ meta structure linarith_config : Type := (discharger : tactic unit := `[ring]) (restrict_type : option Type := none) (restrict_type_reflect : reflected restrict_type . tactic.apply_instance) (exfalso : bool := tt) (transparency : tactic.transparency := reducible) (split_hypotheses : bool := tt) (split_ne : bool := ff) (preprocessors : option (list global_branching_preprocessor) := none) (oracle : option certificate_oracle := none) /-- `cfg.update_reducibility reduce_semi` will change the transparency setting of `cfg` to `semireducible` if `reduce_semi` is true. In this case, it also sets the discharger to `ring!`, since this is typically needed when using stronger unification. -/ meta def linarith_config.update_reducibility (cfg : linarith_config) (reduce_semi : bool) : linarith_config := if reduce_semi then { cfg with transparency := semireducible, discharger := `[ring!] } else cfg /-! ### Auxiliary functions These functions are used by multiple modules, so we put them here for accessibility. -/ open tactic /-- `get_rel_sides e` returns the left and right hand sides of `e` if `e` is a comparison, and fails otherwise. This function is more naturally in the `option` monad, but it is convenient to put in `tactic` for compositionality. -/ meta def get_rel_sides : expr → tactic (expr × expr) | `(%%a < %%b) := return (a, b) | `(%%a ≤ %%b) := return (a, b) | `(%%a = %%b) := return (a, b) | `(%%a ≥ %%b) := return (a, b) | `(%%a > %%b) := return (a, b) | _ := tactic.failed /-- `parse_into_comp_and_expr e` checks if `e` is of the form `t < 0`, `t ≤ 0`, or `t = 0`. If it is, it returns the comparison along with `t`. -/ meta def parse_into_comp_and_expr : expr → option (ineq × expr) | `(%%e < 0) := (ineq.lt, e) | `(%%e ≤ 0) := (ineq.le, e) | `(%%e = 0) := (ineq.eq, e) | _ := none /-- `mk_single_comp_zero_pf c h` assumes that `h` is a proof of `t R 0`. It produces a pair `(R', h')`, where `h'` is a proof of `c*t R' 0`. Typically `R` and `R'` will be the same, except when `c = 0`, in which case `R'` is `=`. If `c = 1`, `h'` is the same as `h` -- specifically, it does *not* change the type to `1*t R 0`. -/ meta def mk_single_comp_zero_pf (c : ℕ) (h : expr) : tactic (ineq × expr) := do tp ← infer_type h, some (iq, e) ← return $ parse_into_comp_and_expr tp, if c = 0 then do e' ← mk_app ``zero_mul [e], return (ineq.eq, e') else if c = 1 then return (iq, h) else do tp ← (prod.snd <$> (infer_type h >>= get_rel_sides)) >>= infer_type, c ← tp.of_nat c, cpos ← to_expr ``(%%c > 0), (_, ex) ← solve_aux cpos `[norm_num, done], e' ← mk_app iq.to_const_mul_nm [h, ex], return (iq, e') end linarith
8b2d85a374ac6a2a27ae9442c97e95f8010ad9a7
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/tropical/basic.lean
463ad1f35fec0b9a1ae2ee4de523da58a009eaa1
[ "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
16,427
lean
/- Copyright (c) 2021 Yakov Pechersky. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yakov Pechersky -/ import algebra.group_power.order import algebra.order.monoid.with_top import algebra.smul_with_zero import algebra.order.monoid.min_max /-! # Tropical algebraic structures > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines algebraic structures of the (min-)tropical numbers, up to the tropical semiring. Some basic lemmas about conversion from the base type `R` to `tropical R` are provided, as well as the expected implementations of tropical addition and tropical multiplication. ## Main declarations * `tropical R`: The type synonym of the tropical interpretation of `R`. If `[linear_order R]`, then addition on `R` is via `min`. * `semiring (tropical R)`: A `linear_ordered_add_comm_monoid_with_top R` induces a `semiring (tropical R)`. If one solely has `[linear_ordered_add_comm_monoid R]`, then the "tropicalization of `R`" would be `tropical (with_top R)`. ## Implementation notes The tropical structure relies on `has_top` and `min`. For the max-tropical numbers, use `order_dual R`. Inspiration was drawn from the implementation of `additive`/`multiplicative`/`opposite`, where a type synonym is created with some barebones API, and quickly made irreducible. Algebraic structures are provided with as few typeclass assumptions as possible, even though most references rely on `semiring (tropical R)` for building up the whole theory. ## References followed * https://arxiv.org/pdf/math/0408099.pdf * https://www.mathenjeans.fr/sites/default/files/sujets/tropical_geometry_-_casagrande.pdf -/ universes u v variables (R : Type u) /-- The tropicalization of a type `R`. -/ def tropical : Type u := R variables {R} namespace tropical /-- Reinterpret `x : R` as an element of `tropical R`. See `tropical.trop_equiv` for the equivalence. -/ @[pp_nodot] def trop : R → tropical R := id /-- Reinterpret `x : tropical R` as an element of `R`. See `tropical.trop_equiv` for the equivalence. -/ @[pp_nodot] def untrop : tropical R → R := id lemma trop_injective : function.injective (trop : R → tropical R) := λ _ _, id lemma untrop_injective : function.injective (untrop : tropical R → R) := λ _ _, id @[simp] lemma trop_inj_iff (x y : R) : trop x = trop y ↔ x = y := iff.rfl @[simp] lemma untrop_inj_iff (x y : tropical R) : untrop x = untrop y ↔ x = y := iff.rfl @[simp] lemma trop_untrop (x : tropical R) : trop (untrop x) = x := rfl @[simp] lemma untrop_trop (x : R) : untrop (trop x) = x := rfl lemma left_inverse_trop : function.left_inverse (trop : R → tropical R) untrop := trop_untrop lemma right_inverse_trop : function.right_inverse (trop : R → tropical R) untrop := trop_untrop attribute [irreducible] tropical /-- Reinterpret `x : R` as an element of `tropical R`. See `tropical.trop_order_iso` for the order-preserving equivalence. -/ def trop_equiv : R ≃ tropical R := { to_fun := trop, inv_fun := untrop, left_inv := untrop_trop, right_inv := trop_untrop } @[simp] lemma trop_equiv_coe_fn : (trop_equiv : R → tropical R) = trop := rfl @[simp] lemma trop_equiv_symm_coe_fn : (trop_equiv.symm : tropical R → R) = untrop := rfl lemma trop_eq_iff_eq_untrop {x : R} {y} : trop x = y ↔ x = untrop y := trop_equiv.apply_eq_iff_eq_symm_apply lemma untrop_eq_iff_eq_trop {x} {y : R} : untrop x = y ↔ x = trop y := trop_equiv.symm.apply_eq_iff_eq_symm_apply lemma injective_trop : function.injective (trop : R → tropical R) := trop_equiv.injective lemma injective_untrop : function.injective (untrop : tropical R → R) := trop_equiv.symm.injective lemma surjective_trop : function.surjective (trop : R → tropical R) := trop_equiv.surjective lemma surjective_untrop : function.surjective (untrop : tropical R → R) := trop_equiv.symm.surjective instance [inhabited R] : inhabited (tropical R) := ⟨trop default⟩ /-- Recursing on a `x' : tropical R` is the same as recursing on an `x : R` reinterpreted as a term of `tropical R` via `trop x`. -/ @[simp] def trop_rec {F : Π (X : tropical R), Sort v} (h : Π X, F (trop X)) : Π X, F X := λ X, h (untrop X) instance [decidable_eq R] : decidable_eq (tropical R) := λ x y, decidable_of_iff _ injective_untrop.eq_iff section order instance [has_le R] : has_le (tropical R) := { le := λ x y, untrop x ≤ untrop y } @[simp] lemma untrop_le_iff [has_le R] {x y : tropical R} : untrop x ≤ untrop y ↔ x ≤ y := iff.rfl instance decidable_le [has_le R] [decidable_rel ((≤) : R → R → Prop)] : decidable_rel ((≤) : tropical R → tropical R → Prop) := λ x y, ‹decidable_rel (≤)› (untrop x) (untrop y) instance [has_lt R] : has_lt (tropical R) := { lt := λ x y, untrop x < untrop y } @[simp] lemma untrop_lt_iff [has_lt R] {x y : tropical R} : untrop x < untrop y ↔ x < y := iff.rfl instance decidable_lt [has_lt R] [decidable_rel ((<) : R → R → Prop)] : decidable_rel ((<) : tropical R → tropical R → Prop) := λ x y, ‹decidable_rel (<)› (untrop x) (untrop y) instance [preorder R] : preorder (tropical R) := { le_refl := λ _, le_rfl, le_trans := λ _ _ _ h h', le_trans h h', lt_iff_le_not_le := λ _ _, lt_iff_le_not_le, ..tropical.has_le, ..tropical.has_lt } /-- Reinterpret `x : R` as an element of `tropical R`, preserving the order. -/ def trop_order_iso [preorder R] : R ≃o tropical R := { map_rel_iff' := λ _ _, untrop_le_iff, ..trop_equiv } @[simp] lemma trop_order_iso_coe_fn [preorder R] : (trop_order_iso : R → tropical R) = trop := rfl @[simp] lemma trop_order_iso_symm_coe_fn [preorder R] : (trop_order_iso.symm : tropical R → R) = untrop := rfl lemma trop_monotone [preorder R] : monotone (trop : R → tropical R) := λ _ _, id lemma untrop_monotone [preorder R] : monotone (untrop : tropical R → R) := λ _ _, id instance [partial_order R] : partial_order (tropical R) := { le_antisymm := λ _ _ h h', untrop_injective (le_antisymm h h'), ..tropical.preorder } instance [has_top R] : has_zero (tropical R) := ⟨trop ⊤⟩ instance [has_top R] : has_top (tropical R) := ⟨0⟩ @[simp] lemma untrop_zero [has_top R] : untrop (0 : tropical R) = ⊤ := rfl @[simp] lemma trop_top [has_top R] : trop (⊤ : R) = 0 := rfl @[simp] lemma trop_coe_ne_zero (x : R) : trop (x : with_top R) ≠ 0 . @[simp] lemma zero_ne_trop_coe (x : R) : (0 : tropical (with_top R)) ≠ trop x . @[simp] lemma le_zero [has_le R] [order_top R] (x : tropical R) : x ≤ 0 := le_top instance [has_le R] [order_top R] : order_top (tropical R) := { le_top := λ _, le_top, ..tropical.has_top } variable [linear_order R] /-- Tropical addition is the minimum of two underlying elements of `R`. -/ instance : has_add (tropical R) := ⟨λ x y, trop (min (untrop x) (untrop y))⟩ instance : add_comm_semigroup (tropical R) := { add := (+), add_assoc := λ _ _ _, untrop_injective (min_assoc _ _ _), add_comm := λ _ _, untrop_injective (min_comm _ _) } @[simp] lemma untrop_add (x y : tropical R) : untrop (x + y) = min (untrop x) (untrop y) := rfl @[simp] lemma trop_min (x y : R) : trop (min x y) = trop x + trop y := rfl @[simp] lemma trop_inf (x y : R) : trop (x ⊓ y) = trop x + trop y := rfl lemma trop_add_def (x y : tropical R) : x + y = trop (min (untrop x) (untrop y)) := rfl instance : linear_order (tropical R) := { le_total := λ a b, le_total (untrop a) (untrop b), decidable_le := tropical.decidable_le, decidable_lt := tropical.decidable_lt, decidable_eq := tropical.decidable_eq, max := λ a b, trop (max (untrop a) (untrop b)), max_def := begin ext x y, rw [max_default, max_def, apply_ite trop, trop_untrop, trop_untrop, if_congr untrop_le_iff rfl rfl], end, min := (+), min_def := begin ext x y, rw [trop_add_def, min_default, min_def, apply_ite trop, trop_untrop, trop_untrop, if_congr untrop_le_iff rfl rfl], end, ..tropical.partial_order } @[simp] lemma untrop_sup (x y : tropical R) : untrop (x ⊔ y) = untrop x ⊔ untrop y := rfl @[simp] lemma untrop_max (x y : tropical R) : untrop (max x y) = max (untrop x) (untrop y) := rfl @[simp] lemma min_eq_add : (min : tropical R → tropical R → tropical R) = (+) := rfl @[simp] lemma inf_eq_add : ((⊓) : tropical R → tropical R → tropical R) = (+) := rfl lemma trop_max_def (x y : tropical R) : max x y = trop (max (untrop x) (untrop y)) := rfl lemma trop_sup_def (x y : tropical R) : x ⊔ y = trop (untrop x ⊔ untrop y) := rfl @[simp] lemma add_eq_left ⦃x y : tropical R⦄ (h : x ≤ y) : x + y = x := untrop_injective (by simpa using h) @[simp] lemma add_eq_right ⦃x y : tropical R⦄ (h : y ≤ x) : x + y = y := untrop_injective (by simpa using h) lemma add_eq_left_iff {x y : tropical R} : x + y = x ↔ x ≤ y := by rw [trop_add_def, trop_eq_iff_eq_untrop, ←untrop_le_iff, min_eq_left_iff] lemma add_eq_right_iff {x y : tropical R} : x + y = y ↔ y ≤ x := by rw [trop_add_def, trop_eq_iff_eq_untrop, ←untrop_le_iff, min_eq_right_iff] @[simp] lemma add_self (x : tropical R) : x + x = x := untrop_injective (min_eq_right le_rfl) @[simp] lemma bit0 (x : tropical R) : bit0 x = x := add_self x lemma add_eq_iff {x y z : tropical R} : x + y = z ↔ x = z ∧ x ≤ y ∨ y = z ∧ y ≤ x := by { rw [trop_add_def, trop_eq_iff_eq_untrop], simp [min_eq_iff] } @[simp] lemma add_eq_zero_iff {a b : tropical (with_top R)} : a + b = 0 ↔ a = 0 ∧ b = 0 := begin rw add_eq_iff, split, { rintro (⟨rfl, h⟩|⟨rfl, h⟩), { exact ⟨rfl, le_antisymm (le_zero _) h⟩ }, { exact ⟨le_antisymm (le_zero _) h, rfl⟩ } }, { rintro ⟨rfl, rfl⟩, simp } end instance [order_top R] : add_comm_monoid (tropical R) := { zero_add := λ _, untrop_injective (min_top_left _), add_zero := λ _, untrop_injective (min_top_right _), ..tropical.has_zero, ..tropical.add_comm_semigroup } end order section monoid /-- Tropical multiplication is the addition in the underlying `R`. -/ instance [has_add R] : has_mul (tropical R) := ⟨λ x y, trop (untrop x + untrop y)⟩ @[simp] lemma trop_add [has_add R] (x y : R) : trop (x + y) = trop x * trop y := rfl @[simp] lemma untrop_mul [has_add R] (x y : tropical R) : untrop (x * y) = untrop x + untrop y := rfl lemma trop_mul_def [has_add R] (x y : tropical R) : x * y = trop (untrop x + untrop y) := rfl instance [has_zero R] : has_one (tropical R) := ⟨trop 0⟩ @[simp] lemma trop_zero [has_zero R] : trop (0 : R) = 1 := rfl @[simp] lemma untrop_one [has_zero R] : untrop (1 : tropical R) = 0 := rfl instance [linear_order R] [order_top R] [has_zero R] : add_monoid_with_one (tropical R) := { nat_cast := λ n, if n = 0 then 0 else 1, nat_cast_zero := rfl, nat_cast_succ := λ n, (untrop_inj_iff _ _).1 (by cases n; simp [nat.cast]), .. tropical.has_one, .. tropical.add_comm_monoid } instance [has_zero R] : nontrivial (tropical (with_top R)) := ⟨⟨0, 1, trop_injective.ne with_top.top_ne_coe⟩⟩ instance [has_neg R] : has_inv (tropical R) := ⟨λ x, trop (- untrop x)⟩ @[simp] lemma untrop_inv [has_neg R] (x : tropical R) : untrop x⁻¹ = - untrop x := rfl instance [has_sub R] : has_div (tropical R) := ⟨λ x y, trop (untrop x - untrop y)⟩ @[simp] lemma untrop_div [has_sub R] (x y : tropical R) : untrop (x / y) = untrop x - untrop y := rfl instance [add_semigroup R] : semigroup (tropical R) := { mul := (*), mul_assoc := λ _ _ _, untrop_injective (add_assoc _ _ _) } instance [add_comm_semigroup R] : comm_semigroup (tropical R) := { mul_comm := λ _ _, untrop_injective (add_comm _ _), ..tropical.semigroup } instance {α : Type*} [has_smul α R] : has_pow (tropical R) α := { pow := λ x n, trop $ n • untrop x } @[simp] lemma untrop_pow {α : Type*} [has_smul α R] (x : tropical R) (n : α) : untrop (x ^ n) = n • untrop x := rfl @[simp] lemma trop_smul {α : Type*} [has_smul α R] (x : R) (n : α) : trop (n • x) = trop x ^ n := rfl instance [add_zero_class R] : mul_one_class (tropical R) := { one := 1, mul := (*), one_mul := λ _, untrop_injective $ zero_add _, mul_one := λ _, untrop_injective $ add_zero _ } instance [add_monoid R] : monoid (tropical R) := { npow := λ n x, x ^ n, npow_zero' := λ _, untrop_injective $ zero_smul _ _, npow_succ' := λ _ _, untrop_injective $ succ_nsmul _ _, ..tropical.mul_one_class, ..tropical.semigroup } @[simp] lemma trop_nsmul [add_monoid R] (x : R) (n : ℕ) : trop (n • x) = trop x ^ n := rfl instance [add_comm_monoid R] : comm_monoid (tropical R) := { ..tropical.monoid, ..tropical.comm_semigroup } instance [add_group R] : group (tropical R) := { inv := has_inv.inv, mul_left_inv := λ _, untrop_injective $ add_left_neg _, zpow := λ n x, trop $ n • untrop x, zpow_zero' := λ _, untrop_injective $ zero_zsmul _, zpow_succ' := λ _ _, untrop_injective $ add_group.zsmul_succ' _ _, zpow_neg' := λ _ _, untrop_injective $ add_group.zsmul_neg' _ _, ..tropical.monoid } instance [add_comm_group R] : comm_group (tropical R) := { mul_comm := λ _ _, untrop_injective (add_comm _ _), ..tropical.group } @[simp] lemma untrop_zpow [add_group R] (x : tropical R) (n : ℤ) : untrop (x ^ n) = n • untrop x := rfl @[simp] lemma trop_zsmul [add_group R] (x : R) (n : ℤ) : trop (n • x) = trop x ^ n := rfl end monoid section distrib instance covariant_mul [has_le R] [has_add R] [covariant_class R R (+) (≤)] : covariant_class (tropical R) (tropical R) (*) (≤) := ⟨λ x y z h, add_le_add_left h _⟩ instance covariant_swap_mul [has_le R] [has_add R] [covariant_class R R (function.swap (+)) (≤)] : covariant_class (tropical R) (tropical R) (function.swap (*)) (≤) := ⟨λ x y z h, add_le_add_right h _⟩ instance covariant_add [linear_order R] : covariant_class (tropical R) (tropical R) (+) (≤) := ⟨λ x y z h, begin cases le_total x y with hx hy, { rw [add_eq_left hx, add_eq_left (hx.trans h)] }, { rw [add_eq_right hy], cases le_total x z with hx hx, { rwa [add_eq_left hx] }, { rwa [add_eq_right hx] } } end⟩ instance covariant_mul_lt [has_lt R] [has_add R] [covariant_class R R (+) (<)] : covariant_class (tropical R) (tropical R) (*) (<) := ⟨λ x y z h, add_lt_add_left h _⟩ instance covariant_swap_mul_lt [preorder R] [has_add R] [covariant_class R R (function.swap (+)) (<)] : covariant_class (tropical R) (tropical R) (function.swap (*)) (<) := ⟨λ x y z h, add_lt_add_right h _⟩ instance [linear_order R] [has_add R] [covariant_class R R (+) (≤)] [covariant_class R R (function.swap (+)) (≤)] : distrib (tropical R) := { mul := (*), add := (+), left_distrib := λ _ _ _, untrop_injective (min_add_add_left _ _ _).symm, right_distrib := λ _ _ _, untrop_injective (min_add_add_right _ _ _).symm } @[simp] lemma add_pow [linear_order R] [add_monoid R] [covariant_class R R (+) (≤)] [covariant_class R R (function.swap (+)) (≤)] (x y : tropical R) (n : ℕ) : (x + y) ^ n = x ^ n + y ^ n := begin cases le_total x y with h h, { rw [add_eq_left h, add_eq_left (pow_le_pow_of_le_left' h _)] }, { rw [add_eq_right h, add_eq_right (pow_le_pow_of_le_left' h _)] } end end distrib section semiring variable [linear_ordered_add_comm_monoid_with_top R] instance : comm_semiring (tropical R) := { zero_mul := λ _, untrop_injective (top_add _), mul_zero := λ _, untrop_injective (add_top _), ..tropical.add_monoid_with_one, ..tropical.distrib, ..tropical.add_comm_monoid, ..tropical.comm_monoid } @[simp] lemma succ_nsmul {R} [linear_order R] [order_top R] (x : tropical R) (n : ℕ) : (n + 1) • x = x := begin induction n with n IH, { simp }, { rw [add_nsmul, IH, one_nsmul, add_self] } end -- TODO: find/create the right classes to make this hold (for enat, ennreal, etc) -- Requires `zero_eq_bot` to be true -- lemma add_eq_zero_iff {a b : tropical R} : -- a + b = 1 ↔ a = 1 ∨ b = 1 := sorry @[simp] lemma mul_eq_zero_iff {R : Type*} [linear_ordered_add_comm_monoid R] {a b : tropical (with_top R)} : a * b = 0 ↔ a = 0 ∨ b = 0 := by simp [←untrop_inj_iff, with_top.add_eq_top] instance {R : Type*} [linear_ordered_add_comm_monoid R] : no_zero_divisors (tropical (with_top R)) := ⟨λ _ _, mul_eq_zero_iff.mp⟩ end semiring end tropical
12a74f939fe25c0ff5b875be29bf628bb6c881ca
0ddf2dd8409bcb923d11603846800bd9699616ea
/chapter9.lean
8c7a91b0b3881ddca503521674e2b989f1dd7793
[]
no_license
tounaishouta/Lean
0cbaaa9340e7f8f884504ea170243e07a54f0566
1d75311f5506ca2bfd8b7ccec0b7d70c3319d555
refs/heads/master
1,610,229,383,935
1,459,950,226,000
1,459,950,226,000
50,836,185
0
0
null
null
null
null
UTF-8
Lean
false
false
2,854
lean
import standard print classes print instances inhabited open nat print default eval default ℕ check (rfl : 0 = default ℕ) print arbitrary eval arbitrary ℕ check (rfl : 0 = arbitrary ℕ) --> Error definition func_is_inhabited [instance] {A B : Type} [inhabited B] : inhabited (A → B) := inhabited.mk (λ x : A, default B) definition pi_is_inhabited [instance] {A : Type} {C : A → Type} [Π x : A, inhabited (C x)] : inhabited (Π x : A, C x) := inhabited.mk (λ x : A, default (C x)) definition sum_is_inhabited_l [instance] {A B : Type} [inhabited A] : inhabited (sum A B) := inhabited.mk (sum.inl (default A)) definition sum_is_inhabited_r [instance] {A B : Type} [inhabited B] : inhabited (sum A B) := inhabited.mk (sum.inr (default B)) eval default (sum nat nat) eval default (sum nat empty) eval default (sum empty nat) namespace my_has_add inductive has_add [class] (A : Type) : Type := | mk : (A → A → A) → has_add A definition add {A : Type} [H : has_add A] : A → A → A := has_add.rec id H infix + := add definition bool_has_add [instance] : has_add bool := has_add.mk bool.bxor definition nat_has_add [instance] : has_add nat := has_add.mk nat.add private definition add_prod {A B : Type} [has_add A] [has_add B] : A × B → A × B → A × B | add_prod (a1, b1) (a2, b2) := (a1 + a2, b1 + b2) definition prod_has_add [instance] {A B : Type} [has_add A] [has_add B] : has_add (A × B) | prod_has_add := has_add.mk add_prod eval ((1, 2) + (3, 4) : nat × nat) private definition add_fun {A B : Type} [has_add B] : (A → B) → (A → B) → (A → B) | add_fun f g a := f a + g a definition fun_has_add [instance] {A B : Type} [has_add B] : has_add (A → B) | fun_has_add := has_add.mk add_fun eval ((λ n : ℕ, n + 1) + (λ n : ℕ, 2 * n)) 3 open list private definition add_list {A : Type} [has_add A] : list A → list A → list A | add_list nil _ := nil | add_list _ nil := nil | add_list (x :: xs) (y :: ys) := (x + y) :: add_list xs ys definition list_has_add [instance] {A : Type} [has_add A] : has_add (list A) | list_has_add := has_add.mk add_list eval ([1, 2, 3] + [4, 5, 6] : list nat) namespace vector inductive vector (A : Type) : ℕ → Type := | nil {} : vector A 0 | cons : Π {n : ℕ}, A → vector A n → vector A (succ n) open vector notation x `::` xs := cons x xs private definition add_vector {A : Type} [has_add A] : Π {n : ℕ}, vector A n → vector A n → vector A n | add_vector nil nil := nil | add_vector (x :: xs) (y :: ys) := (x + y) :: add_vector xs ys definition vector_has_add [instance] {A : Type} [has_add A] {n : ℕ} : has_add (vector A n) | vector_has_add := has_add.mk add_vector eval (1 :: 2 :: 3 :: nil + 4 :: 5 :: 6 :: nil : vector ℕ 3) end vector end my_has_add
8d267787633f326bdbc89af149c72b05994b111f
271e26e338b0c14544a889c31c30b39c989f2e0f
/stage0/src/Init/Data/RBTree/Basic.lean
a4b379d9032a65bc219bed8d7b4cf13dea005e9d
[ "Apache-2.0" ]
permissive
dgorokho/lean4
805f99b0b60c545b64ac34ab8237a8504f89d7d4
e949a052bad59b1c7b54a82d24d516a656487d8a
refs/heads/master
1,607,061,363,851
1,578,006,086,000
1,578,006,086,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,883
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Data.RBMap.Basic universes u v w def RBTree (α : Type u) (lt : α → α → Bool) : Type u := RBMap α Unit lt @[inline] def mkRBTree (α : Type u) (lt : α → α → Bool) : RBTree α lt := mkRBMap α Unit lt instance (α : Type u) (lt : α → α → Bool) : HasEmptyc (RBTree α lt) := ⟨mkRBTree α lt⟩ namespace RBTree variables {α : Type u} {β : Type v} {lt : α → α → Bool} @[inline] def empty : RBTree α lt := RBMap.empty @[inline] def depth (f : Nat → Nat → Nat) (t : RBTree α lt) : Nat := RBMap.depth f t @[inline] def fold (f : β → α → β) (b : β) (t : RBTree α lt) : β := RBMap.fold (fun r a _ => f r a) b t @[inline] def revFold (f : β → α → β) (b : β) (t : RBTree α lt) : β := RBMap.revFold (fun r a _ => f r a) b t @[inline] def mfold {m : Type v → Type w} [Monad m] (f : β → α → m β) (b : β) (t : RBTree α lt) : m β := RBMap.mfold (fun r a _ => f r a) b t @[inline] def mfor {m : Type v → Type w} [Monad m] (f : α → m β) (t : RBTree α lt) : m PUnit := t.mfold (fun _ a => f a *> pure ⟨⟩) ⟨⟩ @[inline] def isEmpty (t : RBTree α lt) : Bool := RBMap.isEmpty t @[specialize] def toList (t : RBTree α lt) : List α := t.revFold (fun as a => a::as) [] @[inline] protected def min (t : RBTree α lt) : Option α := match RBMap.min t with | some ⟨a, _⟩ => some a | none => none @[inline] protected def max (t : RBTree α lt) : Option α := match RBMap.max t with | some ⟨a, _⟩ => some a | none => none instance [HasRepr α] : HasRepr (RBTree α lt) := ⟨fun t => "rbtreeOf " ++ repr t.toList⟩ @[inline] def insert (t : RBTree α lt) (a : α) : RBTree α lt := RBMap.insert t a () @[inline] def erase (t : RBTree α lt) (a : α) : RBTree α lt := RBMap.erase t a @[specialize] def ofList : List α → RBTree α lt | [] => mkRBTree _ _ | x::xs => (ofList xs).insert x @[inline] def find (t : RBTree α lt) (a : α) : Option α := match RBMap.findCore t a with | some ⟨a, _⟩ => some a | none => none @[inline] def contains (t : RBTree α lt) (a : α) : Bool := (t.find a).isSome def fromList (l : List α) (lt : α → α → Bool) : RBTree α lt := l.foldl insert (mkRBTree α lt) @[inline] def all (t : RBTree α lt) (p : α → Bool) : Bool := RBMap.all t (fun a _ => p a) @[inline] def any (t : RBTree α lt) (p : α → Bool) : Bool := RBMap.any t (fun a _ => p a) def subset (t₁ t₂ : RBTree α lt) : Bool := t₁.all $ fun a => (t₂.find a).toBool def seteq (t₁ t₂ : RBTree α lt) : Bool := subset t₁ t₂ && subset t₂ t₁ end RBTree def rbtreeOf {α : Type u} (l : List α) (lt : α → α → Bool) : RBTree α lt := RBTree.fromList l lt
ab95c8b47eb236e02095803a865bbedfd6aa762c
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/precissues.lean
5de542cb418a5f4a2426c662e25c7c0f63d6b302
[ "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
703
lean
new_frontend #check id fun x => x -- should work #check 0 def f (x : Nat) (g : Nat → Nat) := g x #check f 1 fun x => x -- should fail #check 0 #check f 1 (fun x => x) #check id have True from ⟨⟩; this -- should fail #check id let x := 10; x #check 1 #check id (have True from ⟨⟩; this) #check 0 = have Nat from 1; this #check 0 = let x := 0; x variables (p q r : Prop) macro_rules `(¬ $p) => `(Not $p) #check p ↔ ¬ q #check True = ¬ False #check p ∧ ¬q #check ¬p ∧ q #check ¬p ↔ q #check ¬(p = q) #check ¬ p = q #check id ¬p #check Nat → ∀ (a : Nat), a = a macro "foo!" x:term : term => `($x + 1) #check id foo! 10 -- error, `foo! x` precedence is leadPrec
51882c99b0e577767222f93921a7e6917763efc1
88fb7558b0636ec6b181f2a548ac11ad3919f8a5
/tests/lean/run/pi_patterns.lean
f3cd6347bede82eb9bf7150ea31226b15a90650d
[ "Apache-2.0" ]
permissive
moritayasuaki/lean
9f666c323cb6fa1f31ac597d777914aed41e3b7a
ae96ebf6ee953088c235ff7ae0e8c95066ba8001
refs/heads/master
1,611,135,440,814
1,493,852,869,000
1,493,852,869,000
90,269,903
0
0
null
1,493,906,291,000
1,493,906,291,000
null
UTF-8
Lean
false
false
335
lean
open tactic run_cmd do ```(%%a → %%b) ← pure ```(nat → nat) | failed, skip run_cmd do ```(%%a → %%b) ← pure ```(Π (b : nat), nat) | failed, skip run_cmd do ```(λ a : %%a, (%%b : %%c)) ← pure ```(λ n, n + 1) | failed, skip run_cmd do ```(let a := (%%a : %%c) in (%%b : %%d)) ← pure ```(let n := 1 in n) | failed, skip
a92949dab5467ee68528722f78c12869a94d0f85
968e2f50b755d3048175f176376eff7139e9df70
/examples/prop_logic_theory/unnamed_1576.lean
cf1f54f26c76fcd913c23c0149063ba51f6881d6
[]
no_license
gihanmarasingha/mth1001_sphinx
190a003269ba5e54717b448302a27ca26e31d491
05126586cbf5786e521be1ea2ef5b4ba3c44e74a
refs/heads/master
1,672,913,933,677
1,604,516,583,000
1,604,516,583,000
309,245,750
1
0
null
null
null
null
UTF-8
Lean
false
false
231
lean
variables p q r : Prop -- BEGIN example (h₁ : p ↔ q) (h₂ : q ↔ r) : p ↔ r := begin rw h₁, -- Rewriting using `h₁`, the goal is to prove `q ↔ r`. exact h₂, -- This holds by reiteration on `h₂`. end -- END
65add4f2ba1b5c3e8a2cd669035b8d48c65f8c17
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/order/conditionally_complete_lattice.lean
f7bdaac992079c20ea9cba854cf9db5de6ee9992
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
35,516
lean
/- Copyright (c) 2018 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import data.nat.enat import data.set.intervals.ord_connected /-! # Theory of conditionally complete lattices. A conditionally complete lattice is a lattice in which every non-empty bounded subset s has a least upper bound and a greatest lower bound, denoted below by Sup s and Inf s. Typical examples are real, nat, int with their usual orders. The theory is very comparable to the theory of complete lattices, except that suitable boundedness and nonemptiness assumptions have to be added to most statements. We introduce two predicates bdd_above and bdd_below to express this boundedness, prove their basic properties, and then go on to prove most useful properties of Sup and Inf in conditionally complete lattices. To differentiate the statements between complete lattices and conditionally complete lattices, we prefix Inf and Sup in the statements by c, giving cInf and cSup. For instance, Inf_le is a statement in complete lattices ensuring Inf s ≤ x, while cInf_le is the same statement in conditionally complete lattices with an additional assumption that s is bounded below. -/ set_option old_structure_cmd true open set variables {α β : Type*} {ι : Sort*} section /-! Extension of Sup and Inf from a preorder `α` to `with_top α` and `with_bot α` -/ open_locale classical noncomputable instance {α : Type*} [preorder α] [has_Sup α] : has_Sup (with_top α) := ⟨λ S, if ⊤ ∈ S then ⊤ else if bdd_above (coe ⁻¹' S : set α) then ↑(Sup (coe ⁻¹' S : set α)) else ⊤⟩ noncomputable instance {α : Type*} [has_Inf α] : has_Inf (with_top α) := ⟨λ S, if S ⊆ {⊤} then ⊤ else ↑(Inf (coe ⁻¹' S : set α))⟩ noncomputable instance {α : Type*} [has_Sup α] : has_Sup (with_bot α) := ⟨(@with_top.has_Inf (order_dual α) _).Inf⟩ noncomputable instance {α : Type*} [preorder α] [has_Inf α] : has_Inf (with_bot α) := ⟨(@with_top.has_Sup (order_dual α) _ _).Sup⟩ end -- section /-- A conditionally complete lattice is a lattice in which every nonempty subset which is bounded above has a supremum, and every nonempty subset which is bounded below has an infimum. Typical examples are real numbers or natural numbers. To differentiate the statements from the corresponding statements in (unconditional) complete lattices, we prefix Inf and Sup by a c everywhere. The same statements should hold in both worlds, sometimes with additional assumptions of nonemptiness or boundedness.-/ class conditionally_complete_lattice (α : Type*) extends lattice α, has_Sup α, has_Inf α := (le_cSup : ∀s a, bdd_above s → a ∈ s → a ≤ Sup s) (cSup_le : ∀ s a, set.nonempty s → a ∈ upper_bounds s → Sup s ≤ a) (cInf_le : ∀s a, bdd_below s → a ∈ s → Inf s ≤ a) (le_cInf : ∀s a, set.nonempty s → a ∈ lower_bounds s → a ≤ Inf s) class conditionally_complete_linear_order (α : Type*) extends conditionally_complete_lattice α, decidable_linear_order α class conditionally_complete_linear_order_bot (α : Type*) extends conditionally_complete_linear_order α, order_bot α := (cSup_empty : Sup ∅ = ⊥) /- A complete lattice is a conditionally complete lattice, as there are no restrictions on the properties of Inf and Sup in a complete lattice.-/ @[priority 100] -- see Note [lower instance priority] instance conditionally_complete_lattice_of_complete_lattice [complete_lattice α]: conditionally_complete_lattice α := { le_cSup := by intros; apply le_Sup; assumption, cSup_le := by intros; apply Sup_le; assumption, cInf_le := by intros; apply Inf_le; assumption, le_cInf := by intros; apply le_Inf; assumption, ..‹complete_lattice α› } @[priority 100] -- see Note [lower instance priority] instance conditionally_complete_linear_order_of_complete_linear_order [complete_linear_order α]: conditionally_complete_linear_order α := { ..conditionally_complete_lattice_of_complete_lattice, .. ‹complete_linear_order α› } section conditionally_complete_lattice variables [conditionally_complete_lattice α] {s t : set α} {a b : α} theorem le_cSup (h₁ : bdd_above s) (h₂ : a ∈ s) : a ≤ Sup s := conditionally_complete_lattice.le_cSup s a h₁ h₂ theorem cSup_le (h₁ : s.nonempty) (h₂ : ∀b∈s, b ≤ a) : Sup s ≤ a := conditionally_complete_lattice.cSup_le s a h₁ h₂ theorem cInf_le (h₁ : bdd_below s) (h₂ : a ∈ s) : Inf s ≤ a := conditionally_complete_lattice.cInf_le s a h₁ h₂ theorem le_cInf (h₁ : s.nonempty) (h₂ : ∀b∈s, a ≤ b) : a ≤ Inf s := conditionally_complete_lattice.le_cInf s a h₁ h₂ theorem le_cSup_of_le (_ : bdd_above s) (hb : b ∈ s) (h : a ≤ b) : a ≤ Sup s := le_trans h (le_cSup ‹bdd_above s› hb) theorem cInf_le_of_le (_ : bdd_below s) (hb : b ∈ s) (h : b ≤ a) : Inf s ≤ a := le_trans (cInf_le ‹bdd_below s› hb) h theorem cSup_le_cSup (_ : bdd_above t) (_ : s.nonempty) (h : s ⊆ t) : Sup s ≤ Sup t := cSup_le ‹_› (assume (a) (ha : a ∈ s), le_cSup ‹bdd_above t› (h ha)) theorem cInf_le_cInf (_ : bdd_below t) (_ : s.nonempty) (h : s ⊆ t) : Inf t ≤ Inf s := le_cInf ‹_› (assume (a) (ha : a ∈ s), cInf_le ‹bdd_below t› (h ha)) lemma is_lub_cSup (ne : s.nonempty) (H : bdd_above s) : is_lub s (Sup s) := ⟨assume x, le_cSup H, assume x, cSup_le ne⟩ lemma is_glb_cInf (ne : s.nonempty) (H : bdd_below s) : is_glb s (Inf s) := ⟨assume x, cInf_le H, assume x, le_cInf ne⟩ lemma is_lub.cSup_eq (H : is_lub s a) (ne : s.nonempty) : Sup s = a := (is_lub_cSup ne ⟨a, H.1⟩).unique H /-- A greatest element of a set is the supremum of this set. -/ lemma is_greatest.cSup_eq (H : is_greatest s a) : Sup s = a := H.is_lub.cSup_eq H.nonempty lemma is_glb.cInf_eq (H : is_glb s a) (ne : s.nonempty) : Inf s = a := (is_glb_cInf ne ⟨a, H.1⟩).unique H /-- A least element of a set is the infimum of this set. -/ lemma is_least.cInf_eq (H : is_least s a) : Inf s = a := H.is_glb.cInf_eq H.nonempty lemma subset_Icc_cInf_cSup (hb : bdd_below s) (ha : bdd_above s) : s ⊆ Icc (Inf s) (Sup s) := λ x hx, ⟨cInf_le hb hx, le_cSup ha hx⟩ theorem cSup_le_iff (hb : bdd_above s) (ne : s.nonempty) : Sup s ≤ a ↔ (∀b ∈ s, b ≤ a) := is_lub_le_iff (is_lub_cSup ne hb) theorem le_cInf_iff (hb : bdd_below s) (ne : s.nonempty) : a ≤ Inf s ↔ (∀b ∈ s, a ≤ b) := le_is_glb_iff (is_glb_cInf ne hb) lemma cSup_lower_bounds_eq_cInf {s : set α} (h : bdd_below s) (hs : s.nonempty) : Sup (lower_bounds s) = Inf s := (is_lub_cSup h $ hs.mono $ λ x hx y hy, hy hx).unique (is_glb_cInf hs h).is_lub lemma cInf_upper_bounds_eq_cSup {s : set α} (h : bdd_above s) (hs : s.nonempty) : Inf (upper_bounds s) = Sup s := (is_glb_cInf h $ hs.mono $ λ x hx y hy, hy hx).unique (is_lub_cSup hs h).is_glb /--Introduction rule to prove that b is the supremum of s: it suffices to check that b is larger than all elements of s, and that this is not the case of any `w<b`.-/ theorem cSup_intro (_ : s.nonempty) (_ : ∀a∈s, a ≤ b) (H : ∀w, w < b → (∃a∈s, w < a)) : Sup s = b := have bdd_above s := ⟨b, by assumption⟩, have (Sup s < b) ∨ (Sup s = b) := lt_or_eq_of_le (cSup_le ‹_› ‹∀a∈s, a ≤ b›), have ¬(Sup s < b) := assume: Sup s < b, let ⟨a, _, _⟩ := (H (Sup s) ‹Sup s < b›) in /- a ∈ s, Sup s < a-/ have Sup s < Sup s := lt_of_lt_of_le ‹Sup s < a› (le_cSup ‹bdd_above s› ‹a ∈ s›), show false, by finish [lt_irrefl (Sup s)], show Sup s = b, by finish /--Introduction rule to prove that b is the infimum of s: it suffices to check that b is smaller than all elements of s, and that this is not the case of any `w>b`.-/ theorem cInf_intro (_ : s.nonempty) (_ : ∀a∈s, b ≤ a) (H : ∀w, b < w → (∃a∈s, a < w)) : Inf s = b := have bdd_below s := ⟨b, by assumption⟩, have (b < Inf s) ∨ (b = Inf s) := lt_or_eq_of_le (le_cInf ‹_› ‹∀a∈s, b ≤ a›), have ¬(b < Inf s) := assume: b < Inf s, let ⟨a, _, _⟩ := (H (Inf s) ‹b < Inf s›) in /- a ∈ s, a < Inf s-/ have Inf s < Inf s := lt_of_le_of_lt (cInf_le ‹bdd_below s› ‹a ∈ s›) ‹a < Inf s› , show false, by finish [lt_irrefl (Inf s)], show Inf s = b, by finish /--b < Sup s when there is an element a in s with b < a, when s is bounded above. This is essentially an iff, except that the assumptions for the two implications are slightly different (one needs boundedness above for one direction, nonemptiness and linear order for the other one), so we formulate separately the two implications, contrary to the complete_lattice case.-/ lemma lt_cSup_of_lt (_ : bdd_above s) (_ : a ∈ s) (_ : b < a) : b < Sup s := lt_of_lt_of_le ‹b < a› (le_cSup ‹bdd_above s› ‹a ∈ s›) /--Inf s < b when there is an element a in s with a < b, when s is bounded below. This is essentially an iff, except that the assumptions for the two implications are slightly different (one needs boundedness below for one direction, nonemptiness and linear order for the other one), so we formulate separately the two implications, contrary to the complete_lattice case.-/ lemma cInf_lt_of_lt (_ : bdd_below s) (_ : a ∈ s) (_ : a < b) : Inf s < b := lt_of_le_of_lt (cInf_le ‹bdd_below s› ‹a ∈ s›) ‹a < b› /-- If all elements of a nonempty set `s` are less than or equal to all elements of a nonempty set `t`, then there exists an element between these sets. -/ lemma exists_between_of_forall_le (sne : s.nonempty) (tne : t.nonempty) (hst : ∀ (x ∈ s) (y ∈ t), x ≤ y) : (upper_bounds s ∩ lower_bounds t).nonempty := ⟨Inf t, λ x hx, le_cInf tne $ hst x hx, λ y hy, cInf_le (sne.mono hst) hy⟩ /--The supremum of a singleton is the element of the singleton-/ @[simp] theorem cSup_singleton (a : α) : Sup {a} = a := is_greatest_singleton.cSup_eq /--The infimum of a singleton is the element of the singleton-/ @[simp] theorem cInf_singleton (a : α) : Inf {a} = a := is_least_singleton.cInf_eq /--If a set is bounded below and above, and nonempty, its infimum is less than or equal to its supremum.-/ theorem cInf_le_cSup (hb : bdd_below s) (ha : bdd_above s) (ne : s.nonempty) : Inf s ≤ Sup s := is_glb_le_is_lub (is_glb_cInf ne hb) (is_lub_cSup ne ha) ne /--The sup of a union of two sets is the max of the suprema of each subset, under the assumptions that all sets are bounded above and nonempty.-/ theorem cSup_union (hs : bdd_above s) (sne : s.nonempty) (ht : bdd_above t) (tne : t.nonempty) : Sup (s ∪ t) = Sup s ⊔ Sup t := ((is_lub_cSup sne hs).union (is_lub_cSup tne ht)).cSup_eq sne.inl /--The inf of a union of two sets is the min of the infima of each subset, under the assumptions that all sets are bounded below and nonempty.-/ theorem cInf_union (hs : bdd_below s) (sne : s.nonempty) (ht : bdd_below t) (tne : t.nonempty) : Inf (s ∪ t) = Inf s ⊓ Inf t := ((is_glb_cInf sne hs).union (is_glb_cInf tne ht)).cInf_eq sne.inl /--The supremum of an intersection of two sets is bounded by the minimum of the suprema of each set, if all sets are bounded above and nonempty.-/ theorem cSup_inter_le (_ : bdd_above s) (_ : bdd_above t) (hst : (s ∩ t).nonempty) : Sup (s ∩ t) ≤ Sup s ⊓ Sup t := begin apply cSup_le hst, simp only [le_inf_iff, and_imp, set.mem_inter_eq], intros b _ _, split, apply le_cSup ‹bdd_above s› ‹b ∈ s›, apply le_cSup ‹bdd_above t› ‹b ∈ t› end /--The infimum of an intersection of two sets is bounded below by the maximum of the infima of each set, if all sets are bounded below and nonempty.-/ theorem le_cInf_inter (_ : bdd_below s) (_ : bdd_below t) (hst : (s ∩ t).nonempty) : Inf s ⊔ Inf t ≤ Inf (s ∩ t) := begin apply le_cInf hst, simp only [and_imp, set.mem_inter_eq, sup_le_iff], intros b _ _, split, apply cInf_le ‹bdd_below s› ‹b ∈ s›, apply cInf_le ‹bdd_below t› ‹b ∈ t› end /-- The supremum of insert a s is the maximum of a and the supremum of s, if s is nonempty and bounded above.-/ theorem cSup_insert (hs : bdd_above s) (sne : s.nonempty) : Sup (insert a s) = a ⊔ Sup s := ((is_lub_cSup sne hs).insert a).cSup_eq (insert_nonempty a s) /-- The infimum of insert a s is the minimum of a and the infimum of s, if s is nonempty and bounded below.-/ theorem cInf_insert (hs : bdd_below s) (sne : s.nonempty) : Inf (insert a s) = a ⊓ Inf s := ((is_glb_cInf sne hs).insert a).cInf_eq (insert_nonempty a s) @[simp] lemma cInf_Ici : Inf (Ici a) = a := is_least_Ici.cInf_eq @[simp] lemma cSup_Iic : Sup (Iic a) = a := is_greatest_Iic.cSup_eq /--The indexed supremum of two functions are comparable if the functions are pointwise comparable-/ lemma csupr_le_csupr {f g : ι → α} (B : bdd_above (range g)) (H : ∀x, f x ≤ g x) : supr f ≤ supr g := begin classical, by_cases hι : nonempty ι, { have Rf : (range f).nonempty, { exactI range_nonempty _ }, apply cSup_le Rf, rintros y ⟨x, rfl⟩, have : g x ∈ range g := ⟨x, rfl⟩, exact le_cSup_of_le B this (H x) }, { have Rf : range f = ∅, from range_eq_empty.2 hι, have Rg : range g = ∅, from range_eq_empty.2 hι, unfold supr, rw [Rf, Rg] } end /--The indexed supremum of a function is bounded above by a uniform bound-/ lemma csupr_le [nonempty ι] {f : ι → α} {c : α} (H : ∀x, f x ≤ c) : supr f ≤ c := cSup_le (range_nonempty f) (by rwa forall_range_iff) /--The indexed supremum of a function is bounded below by the value taken at one point-/ lemma le_csupr {f : ι → α} (H : bdd_above (range f)) (c : ι) : f c ≤ supr f := le_cSup H (mem_range_self _) /--The indexed infimum of two functions are comparable if the functions are pointwise comparable-/ lemma cinfi_le_cinfi {f g : ι → α} (B : bdd_below (range f)) (H : ∀x, f x ≤ g x) : infi f ≤ infi g := begin classical, by_cases hι : nonempty ι, { have Rg : (range g).nonempty, { exactI range_nonempty _ }, apply le_cInf Rg, rintros y ⟨x, rfl⟩, have : f x ∈ range f := ⟨x, rfl⟩, exact cInf_le_of_le B this (H x) }, { have Rf : range f = ∅, from range_eq_empty.2 hι, have Rg : range g = ∅, from range_eq_empty.2 hι, unfold infi, rw [Rf, Rg] } end /--The indexed minimum of a function is bounded below by a uniform lower bound-/ lemma le_cinfi [nonempty ι] {f : ι → α} {c : α} (H : ∀x, c ≤ f x) : c ≤ infi f := le_cInf (range_nonempty f) (by rwa forall_range_iff) /--The indexed infimum of a function is bounded above by the value taken at one point-/ lemma cinfi_le {f : ι → α} (H : bdd_below (range f)) (c : ι) : infi f ≤ f c := cInf_le H (mem_range_self _) @[simp] theorem cinfi_const [hι : nonempty ι] {a : α} : (⨅ b:ι, a) = a := by rw [infi, range_const, cInf_singleton] @[simp] theorem csupr_const [hι : nonempty ι] {a : α} : (⨆ b:ι, a) = a := by rw [supr, range_const, cSup_singleton] end conditionally_complete_lattice section conditionally_complete_linear_order variables [conditionally_complete_linear_order α] {s t : set α} {a b : α} /-- When b < Sup s, there is an element a in s with b < a, if s is nonempty and the order is a linear order. -/ lemma exists_lt_of_lt_cSup (hs : s.nonempty) (hb : b < Sup s) : ∃a∈s, b < a := begin classical, contrapose! hb, exact cSup_le hs hb end /-- Indexed version of the above lemma `exists_lt_of_lt_cSup`. When `b < supr f`, there is an element `i` such that `b < f i`. -/ lemma exists_lt_of_lt_csupr [nonempty ι] {f : ι → α} (h : b < supr f) : ∃i, b < f i := let ⟨_, ⟨i, rfl⟩, h⟩ := exists_lt_of_lt_cSup (range_nonempty f) h in ⟨i, h⟩ /--When Inf s < b, there is an element a in s with a < b, if s is nonempty and the order is a linear order.-/ lemma exists_lt_of_cInf_lt (hs : s.nonempty) (hb : Inf s < b) : ∃a∈s, a < b := begin classical, contrapose! hb, exact le_cInf hs hb end /-- Indexed version of the above lemma `exists_lt_of_cInf_lt` When `infi f < a`, there is an element `i` such that `f i < a`. -/ lemma exists_lt_of_cinfi_lt [nonempty ι] {f : ι → α} (h : infi f < a) : (∃i, f i < a) := let ⟨_, ⟨i, rfl⟩, h⟩ := exists_lt_of_cInf_lt (range_nonempty f) h in ⟨i, h⟩ /--Introduction rule to prove that b is the supremum of s: it suffices to check that 1) b is an upper bound 2) every other upper bound b' satisfies b ≤ b'.-/ theorem cSup_intro' (_ : s.nonempty) (h_is_ub : ∀ a ∈ s, a ≤ b) (h_b_le_ub : ∀ub, (∀ a ∈ s, a ≤ ub) → (b ≤ ub)) : Sup s = b := le_antisymm (show Sup s ≤ b, from cSup_le ‹s.nonempty› h_is_ub) (show b ≤ Sup s, from h_b_le_ub _ $ assume a, le_cSup ⟨b, h_is_ub⟩) end conditionally_complete_linear_order section conditionally_complete_linear_order_bot lemma cSup_empty [conditionally_complete_linear_order_bot α] : (Sup ∅ : α) = ⊥ := conditionally_complete_linear_order_bot.cSup_empty end conditionally_complete_linear_order_bot namespace nat open_locale classical noncomputable instance : has_Inf ℕ := ⟨λs, if h : ∃n, n ∈ s then @nat.find (λn, n ∈ s) _ h else 0⟩ noncomputable instance : has_Sup ℕ := ⟨λs, if h : ∃n, ∀a∈s, a ≤ n then @nat.find (λn, ∀a∈s, a ≤ n) _ h else 0⟩ lemma Inf_def {s : set ℕ} (h : s.nonempty) : Inf s = @nat.find (λn, n ∈ s) _ h := dif_pos _ lemma Sup_def {s : set ℕ} (h : ∃n, ∀a∈s, a ≤ n) : Sup s = @nat.find (λn, ∀a∈s, a ≤ n) _ h := dif_pos _ @[simp] lemma Inf_eq_zero {s : set ℕ} : Inf s = 0 ↔ 0 ∈ s ∨ s = ∅ := begin cases eq_empty_or_nonempty s, { subst h, simp only [or_true, eq_self_iff_true, iff_true, Inf, has_Inf.Inf, mem_empty_eq, exists_false, dif_neg, not_false_iff] }, { have := ne_empty_iff_nonempty.mpr h, simp only [this, or_false, nat.Inf_def, h, nat.find_eq_zero] } end lemma Inf_mem {s : set ℕ} (h : s.nonempty) : Inf s ∈ s := by { rw [nat.Inf_def h], exact nat.find_spec h } lemma not_mem_of_lt_Inf {s : set ℕ} {m : ℕ} (hm : m < Inf s) : m ∉ s := begin cases eq_empty_or_nonempty s, { subst h, apply not_mem_empty }, { rw [nat.Inf_def h] at hm, exact nat.find_min h hm } end protected lemma Inf_le {s : set ℕ} {m : ℕ} (hm : m ∈ s) : Inf s ≤ m := by { rw [nat.Inf_def ⟨m, hm⟩], exact nat.find_min' ⟨m, hm⟩ hm } /-- This instance is necessary, otherwise the lattice operations would be derived via conditionally_complete_linear_order_bot and marked as noncomputable. -/ instance : lattice ℕ := lattice_of_decidable_linear_order noncomputable instance : conditionally_complete_linear_order_bot ℕ := { Sup := Sup, Inf := Inf, le_cSup := assume s a hb ha, by rw [Sup_def hb]; revert a ha; exact @nat.find_spec _ _ hb, cSup_le := assume s a hs ha, by rw [Sup_def ⟨a, ha⟩]; exact nat.find_min' _ ha, le_cInf := assume s a hs hb, by rw [Inf_def hs]; exact hb (@nat.find_spec (λn, n ∈ s) _ _), cInf_le := assume s a hb ha, by rw [Inf_def ⟨a, ha⟩]; exact nat.find_min' _ ha, cSup_empty := begin simp only [Sup_def, set.mem_empty_eq, forall_const, forall_prop_of_false, not_false_iff, exists_const], apply bot_unique (nat.find_min' _ _), trivial end, .. (infer_instance : order_bot ℕ), .. (lattice_of_decidable_linear_order : lattice ℕ), .. (infer_instance : decidable_linear_order ℕ) } end nat namespace with_top open_locale classical variables [conditionally_complete_linear_order_bot α] /-- The Sup of a non-empty set is its least upper bound for a conditionally complete lattice with a top. -/ lemma is_lub_Sup' {β : Type*} [conditionally_complete_lattice β] {s : set (with_top β)} (hs : s.nonempty) : is_lub s (Sup s) := begin split, { show ite _ _ _ ∈ _, split_ifs, { intros _ _, exact le_top }, { rintro (⟨⟩|a) ha, { contradiction }, apply some_le_some.2, exact le_cSup h_1 ha }, { intros _ _, exact le_top } }, { show ite _ _ _ ∈ _, split_ifs, { rintro (⟨⟩|a) ha, { exact _root_.le_refl _ }, { exact false.elim (not_top_le_coe a (ha h)) } }, { rintro (⟨⟩|b) hb, { exact le_top }, refine some_le_some.2 (cSup_le _ _), { rcases hs with ⟨⟨⟩|b, hb⟩, { exact absurd hb h }, { exact ⟨b, hb⟩ } }, { intros a ha, exact some_le_some.1 (hb ha) } }, { rintro (⟨⟩|b) hb, { exact _root_.le_refl _ }, { exfalso, apply h_1, use b, intros a ha, exact some_le_some.1 (hb ha) } } } end lemma is_lub_Sup (s : set (with_top α)) : is_lub s (Sup s) := begin cases s.eq_empty_or_nonempty with hs hs, { rw hs, show is_lub ∅ (ite _ _ _), split_ifs, { cases h }, { rw [preimage_empty, cSup_empty], exact is_lub_empty }, { exfalso, apply h_1, use ⊥, rintro a ⟨⟩ } }, exact is_lub_Sup' hs, end /-- The Inf of a bounded-below set is its greatest lower bound for a conditionally complete lattice with a top. -/ lemma is_glb_Inf' {β : Type*} [conditionally_complete_lattice β] {s : set (with_top β)} (hs : bdd_below s) : is_glb s (Inf s) := begin split, { show ite _ _ _ ∈ _, split_ifs, { intros a ha, exact top_le_iff.2 (set.mem_singleton_iff.1 (h ha)) }, { rintro (⟨⟩|a) ha, { exact le_top }, refine some_le_some.2 (cInf_le _ ha), rcases hs with ⟨⟨⟩|b, hb⟩, { exfalso, apply h, intros c hc, rw [mem_singleton_iff, ←top_le_iff], exact hb hc }, use b, intros c hc, exact some_le_some.1 (hb hc) } }, { show ite _ _ _ ∈ _, split_ifs, { intros _ _, exact le_top }, { rintro (⟨⟩|a) ha, { exfalso, apply h, intros b hb, exact set.mem_singleton_iff.2 (top_le_iff.1 (ha hb)) }, { refine some_le_some.2 (le_cInf _ _), { classical, contrapose! h, rintros (⟨⟩|a) ha, { exact mem_singleton ⊤ }, { exact (h ⟨a, ha⟩).elim }}, { intros b hb, rw ←some_le_some, exact ha hb } } } } end lemma is_glb_Inf (s : set (with_top α)) : is_glb s (Inf s) := begin by_cases hs : bdd_below s, { exact is_glb_Inf' hs }, { exfalso, apply hs, use ⊥, intros _ _, exact bot_le }, end noncomputable instance : complete_linear_order (with_top α) := { Sup := Sup, le_Sup := assume s, (is_lub_Sup s).1, Sup_le := assume s, (is_lub_Sup s).2, Inf := Inf, le_Inf := assume s, (is_glb_Inf s).2, Inf_le := assume s, (is_glb_Inf s).1, decidable_le := classical.dec_rel _, .. with_top.linear_order, ..with_top.lattice, ..with_top.order_top, ..with_top.order_bot } lemma coe_Sup {s : set α} (hb : bdd_above s) : (↑(Sup s) : with_top α) = (⨆a∈s, ↑a) := begin cases s.eq_empty_or_nonempty with hs hs, { rw [hs, cSup_empty], simp only [set.mem_empty_eq, supr_bot, supr_false], refl }, apply le_antisymm, { refine ((coe_le_iff _ _).2 $ assume b hb, cSup_le hs $ assume a has, coe_le_coe.1 $ hb ▸ _), exact (le_supr_of_le a $ le_supr_of_le has $ _root_.le_refl _) }, { exact (supr_le $ assume a, supr_le $ assume ha, coe_le_coe.2 $ le_cSup hb ha) } end lemma coe_Inf {s : set α} (hs : s.nonempty) : (↑(Inf s) : with_top α) = (⨅a∈s, ↑a) := let ⟨x, hx⟩ := hs in have (⨅a∈s, ↑a : with_top α) ≤ x, from infi_le_of_le x $ infi_le_of_le hx $ _root_.le_refl _, let ⟨r, r_eq, hr⟩ := (le_coe_iff _ _).1 this in le_antisymm (le_infi $ assume a, le_infi $ assume ha, coe_le_coe.2 $ cInf_le (order_bot.bdd_below s) ha) begin refine (r_eq.symm ▸ coe_le_coe.2 $ le_cInf hs $ assume a has, coe_le_coe.1 $ _), refine (r_eq ▸ infi_le_of_le a _), exact (infi_le_of_le has $ _root_.le_refl _), end end with_top namespace enat open_locale classical noncomputable instance : complete_linear_order enat := { Sup := λ s, with_top_equiv.symm $ Sup (with_top_equiv '' s), Inf := λ s, with_top_equiv.symm $ Inf (with_top_equiv '' s), le_Sup := by intros; rw ← with_top_equiv_le; simp; apply le_Sup _; simpa, Inf_le := by intros; rw ← with_top_equiv_le; simp; apply Inf_le _; simpa, Sup_le := begin intros s a h1, rw [← with_top_equiv_le, with_top_equiv.right_inverse_symm], apply Sup_le _, rintros b ⟨x, h2, rfl⟩, rw with_top_equiv_le, apply h1, assumption end, le_Inf := begin intros s a h1, rw [← with_top_equiv_le, with_top_equiv.right_inverse_symm], apply le_Inf _, rintros b ⟨x, h2, rfl⟩, rw with_top_equiv_le, apply h1, assumption end, ..enat.decidable_linear_order, ..enat.bounded_lattice } end enat section order_dual instance (α : Type*) [conditionally_complete_lattice α] : conditionally_complete_lattice (order_dual α) := { le_cSup := @cInf_le α _, cSup_le := @le_cInf α _, le_cInf := @cSup_le α _, cInf_le := @le_cSup α _, ..order_dual.has_Inf α, ..order_dual.has_Sup α, ..order_dual.lattice α } instance (α : Type*) [conditionally_complete_linear_order α] : conditionally_complete_linear_order (order_dual α) := { ..order_dual.conditionally_complete_lattice α, ..order_dual.decidable_linear_order α } end order_dual namespace monotone variables [preorder α] [conditionally_complete_lattice β] {f : α → β} (h_mono : monotone f) /-! A monotone function into a conditionally complete lattice preserves the ordering properties of `Sup` and `Inf`. -/ lemma le_cSup_image {s : set α} {c : α} (hcs : c ∈ s) (h_bdd : bdd_above s) : f c ≤ Sup (f '' s) := le_cSup (map_bdd_above h_mono h_bdd) (mem_image_of_mem f hcs) lemma cSup_image_le {s : set α} (hs : s.nonempty) {B : α} (hB: B ∈ upper_bounds s) : Sup (f '' s) ≤ f B := cSup_le (nonempty.image f hs) (h_mono.mem_upper_bounds_image hB) lemma cInf_image_le {s : set α} {c : α} (hcs : c ∈ s) (h_bdd : bdd_below s) : Inf (f '' s) ≤ f c := @le_cSup_image (order_dual α) (order_dual β) _ _ _ (λ x y hxy, h_mono hxy) _ _ hcs h_bdd lemma le_cInf_image {s : set α} (hs : s.nonempty) {B : α} (hB: B ∈ lower_bounds s) : f B ≤ Inf (f '' s) := @cSup_image_le (order_dual α) (order_dual β) _ _ _ (λ x y hxy, h_mono hxy) _ hs _ hB end monotone section with_top_bot /-! ### Complete lattice structure on `with_top (with_bot α)` If `α` is a `conditionally_complete_lattice`, then we show that `with_top α` and `with_bot α` also inherit the structure of conditionally complete lattices. Furthermore, we show that `with_top (with_bot α)` naturally inherits the structure of a complete lattice. Note that for α a conditionally complete lattice, `Sup` and `Inf` both return junk values for sets which are empty or unbounded. The extension of `Sup` to `with_top α` fixes the unboundedness problem and the extension to `with_bot α` fixes the problem with the empty set. This result can be used to show that the extended reals [-∞, ∞] are a complete lattice. -/ open_locale classical /-- Adding a top element to a conditionally complete lattice gives a conditionally complete lattice -/ noncomputable instance with_top.conditionally_complete_lattice {α : Type*} [conditionally_complete_lattice α] : conditionally_complete_lattice (with_top α) := { le_cSup := λ S a hS haS, (with_top.is_lub_Sup' ⟨a, haS⟩).1 haS, cSup_le := λ S a hS haS, (with_top.is_lub_Sup' hS).2 haS, cInf_le := λ S a hS haS, (with_top.is_glb_Inf' hS).1 haS, le_cInf := λ S a hS haS, (with_top.is_glb_Inf' ⟨a, haS⟩).2 haS, ..with_top.lattice, ..with_top.has_Sup, ..with_top.has_Inf } /-- Adding a bottom element to a conditionally complete lattice gives a conditionally complete lattice -/ noncomputable instance with_bot.conditionally_complete_lattice {α : Type*} [conditionally_complete_lattice α] : conditionally_complete_lattice (with_bot α) := { le_cSup := (@with_top.conditionally_complete_lattice (order_dual α) _).cInf_le, cSup_le := (@with_top.conditionally_complete_lattice (order_dual α) _).le_cInf, cInf_le := (@with_top.conditionally_complete_lattice (order_dual α) _).le_cSup, le_cInf := (@with_top.conditionally_complete_lattice (order_dual α) _).cSup_le, ..with_bot.lattice, ..with_bot.has_Sup, ..with_bot.has_Inf } /-- Adding a bottom and a top to a conditionally complete lattice gives a bounded lattice-/ noncomputable instance with_top.with_bot.bounded_lattice {α : Type*} [conditionally_complete_lattice α] : bounded_lattice (with_top (with_bot α)) := { ..with_top.order_bot, ..with_top.order_top, ..conditionally_complete_lattice.to_lattice _ } theorem with_bot.cSup_empty {α : Type*} [conditionally_complete_lattice α] : Sup (∅ : set (with_bot α)) = ⊥ := begin show ite _ _ _ = ⊥, split_ifs; finish, end noncomputable instance with_top.with_bot.complete_lattice {α : Type*} [conditionally_complete_lattice α] : complete_lattice (with_top (with_bot α)) := { le_Sup := λ S a haS, (with_top.is_lub_Sup' ⟨a, haS⟩).1 haS, Sup_le := λ S a ha, begin cases S.eq_empty_or_nonempty with h, { show ite _ _ _ ≤ a, split_ifs, { rw h at h_1, cases h_1 }, { convert bot_le, convert with_bot.cSup_empty, rw h, refl }, { exfalso, apply h_2, use ⊥, rw h, rintro b ⟨⟩ } }, { refine (with_top.is_lub_Sup' h).2 ha } end, Inf_le := λ S a haS, show ite _ _ _ ≤ a, begin split_ifs, { cases a with a, exact _root_.le_refl _, cases (h haS); tauto }, { cases a, { exact le_top }, { apply with_top.some_le_some.2, refine cInf_le _ haS, use ⊥, intros b hb, exact bot_le } } end, le_Inf := λ S a haS, (with_top.is_glb_Inf' ⟨a, haS⟩).2 haS, ..with_top.has_Inf, ..with_top.has_Sup, ..with_top.with_bot.bounded_lattice } end with_top_bot section subtype variables (s : set α) /-! ### Subtypes of conditionally complete linear orders In this section we give conditions on a subset of a conditionally complete linear order, to ensure that the subtype is itself conditionally complete. We check that an `ord_connected` set satisfies these conditions. TODO There are several possible variants; the `conditionally_complete_linear_order` could be changed to `conditionally_complete_linear_order_bot` or `complete_linear_order`. -/ open_locale classical section has_Sup variables [has_Sup α] /-- `has_Sup` structure on a nonempty subset `s` of an object with `has_Sup`. This definition is non-canonical (it uses `default s`); it should be used only as here, as an auxiliary instance in the construction of the `conditionally_complete_linear_order` structure. -/ noncomputable def subset_has_Sup [inhabited s] : has_Sup s := {Sup := λ t, if ht : Sup (coe '' t : set α) ∈ s then ⟨Sup (coe '' t : set α), ht⟩ else default s} local attribute [instance] subset_has_Sup @[simp] lemma subset_Sup_def [inhabited s] : @Sup s _ = λ t, if ht : Sup (coe '' t : set α) ∈ s then ⟨Sup (coe '' t : set α), ht⟩ else default s := rfl lemma subset_Sup_of_within [inhabited s] {t : set s} (h : Sup (coe '' t : set α) ∈ s) : Sup (coe '' t : set α) = (@Sup s _ t : α) := by simp [dif_pos h] end has_Sup section has_Inf variables [has_Inf α] /-- `has_Inf` structure on a nonempty subset `s` of an object with `has_Inf`. This definition is non-canonical (it uses `default s`); it should be used only as here, as an auxiliary instance in the construction of the `conditionally_complete_linear_order` structure. -/ noncomputable def subset_has_Inf [inhabited s] : has_Inf s := {Inf := λ t, if ht : Inf (coe '' t : set α) ∈ s then ⟨Inf (coe '' t : set α), ht⟩ else default s} local attribute [instance] subset_has_Inf @[simp] lemma subset_Inf_def [inhabited s] : @Inf s _ = λ t, if ht : Inf (coe '' t : set α) ∈ s then ⟨Inf (coe '' t : set α), ht⟩ else default s := rfl lemma subset_Inf_of_within [inhabited s] {t : set s} (h : Inf (coe '' t : set α) ∈ s) : Inf (coe '' t : set α) = (@Inf s _ t : α) := by simp [dif_pos h] end has_Inf variables [conditionally_complete_linear_order α] local attribute [instance] subset_has_Sup local attribute [instance] subset_has_Inf /-- For a nonempty subset of a conditionally complete linear order to be a conditionally complete linear order, it suffices that it contain the `Sup` of all its nonempty bounded-above subsets, and the `Inf` of all its nonempty bounded-below subsets. -/ noncomputable def subset_conditionally_complete_linear_order [inhabited s] (h_Sup : ∀ {t : set s} (ht : t.nonempty) (h_bdd : bdd_above t), Sup (coe '' t : set α) ∈ s) (h_Inf : ∀ {t : set s} (ht : t.nonempty) (h_bdd : bdd_below t), Inf (coe '' t : set α) ∈ s) : conditionally_complete_linear_order s := { le_cSup := begin rintros t c h_bdd hct, -- The following would be a more natural way to finish, but gives a "deep recursion" error: -- simpa [subset_Sup_of_within (h_Sup t)] using (strict_mono_coe s).monotone.le_cSup_image hct h_bdd, have := (strict_mono_coe s).monotone.le_cSup_image hct h_bdd, rwa subset_Sup_of_within s (h_Sup ⟨c, hct⟩ h_bdd) at this, end, cSup_le := begin rintros t B ht hB, have := (strict_mono_coe s).monotone.cSup_image_le ht hB, rwa subset_Sup_of_within s (h_Sup ht ⟨B, hB⟩) at this, end, le_cInf := begin intros t B ht hB, have := (strict_mono_coe s).monotone.le_cInf_image ht hB, rwa subset_Inf_of_within s (h_Inf ht ⟨B, hB⟩) at this, end, cInf_le := begin rintros t c h_bdd hct, have := (strict_mono_coe s).monotone.cInf_image_le hct h_bdd, rwa subset_Inf_of_within s (h_Inf ⟨c, hct⟩ h_bdd) at this, end, ..subset_has_Sup s, ..subset_has_Inf s, ..distrib_lattice.to_lattice s, ..classical.DLO s } section ord_connected /-- The `Sup` function on a nonempty `ord_connected` set `s` in a conditionally complete linear order takes values within `s`, for all nonempty bounded-above subsets of `s`. -/ lemma Sup_within_of_ord_connected {s : set α} [hs : ord_connected s] ⦃t : set s⦄ (ht : t.nonempty) (h_bdd : bdd_above t) : Sup (coe '' t : set α) ∈ s := begin obtain ⟨c, hct⟩ : ∃ c, c ∈ t := ht, obtain ⟨B, hB⟩ : ∃ B, B ∈ upper_bounds t := h_bdd, refine hs c.2 B.2 ⟨_, _⟩, { exact (strict_mono_coe s).monotone.le_cSup_image hct ⟨B, hB⟩ }, { exact (strict_mono_coe s).monotone.cSup_image_le ⟨c, hct⟩ hB }, end /-- The `Inf` function on a nonempty `ord_connected` set `s` in a conditionally complete linear order takes values within `s`, for all nonempty bounded-below subsets of `s`. -/ lemma Inf_within_of_ord_connected {s : set α} [hs : ord_connected s] ⦃t : set s⦄ (ht : t.nonempty) (h_bdd : bdd_below t) : Inf (coe '' t : set α) ∈ s := begin obtain ⟨c, hct⟩ : ∃ c, c ∈ t := ht, obtain ⟨B, hB⟩ : ∃ B, B ∈ lower_bounds t := h_bdd, refine hs B.2 c.2 ⟨_, _⟩, { exact (strict_mono_coe s).monotone.le_cInf_image ⟨c, hct⟩ hB }, { exact (strict_mono_coe s).monotone.cInf_image_le hct ⟨B, hB⟩ }, end /-- A nonempty `ord_connected` set in a conditionally complete linear order is naturally a conditionally complete linear order. -/ noncomputable instance ord_connected_subset_conditionally_complete_linear_order [inhabited s] [ord_connected s] : conditionally_complete_linear_order s := subset_conditionally_complete_linear_order s Sup_within_of_ord_connected Inf_within_of_ord_connected end ord_connected end subtype
eff98e1e8bf5283445d330380dd2548d7f8af6d0
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/category_theory/instances/Top/default.lean
94a3855e2c630b64642e8343beee8ac1ec21541a
[ "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
341
lean
-- Copyright (c) 2019 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison import category_theory.instances.Top.basic import category_theory.instances.Top.limits import category_theory.instances.Top.adjunctions import category_theory.instances.Top.open_nhds
9524ffcc2d54f26bb551c543e85ae71cca3b4add
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch6/ex0302.lean
0d0089faa4d9f7c5a579c2c4e4b5fb5dd2f06e17
[]
no_license
Ailrun/Theorem_Proving_in_Lean
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
refs/heads/master
1,609,838,270,467
1,586,846,743,000
1,586,846,743,000
240,967,761
1
0
null
null
null
null
UTF-8
Lean
false
false
61
lean
def foo.bar : ℕ := 1 open foo #check bar #check foo.bar
1b19fb75ea8029c83167a97ac02df29732b13b78
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/smt_assert_define.lean
819df0f814197bb5f79b0da7db1130352aa7877c
[ "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
934
lean
open smt_tactic constant p : nat → nat → Prop constant f : nat → nat axiom pf (a : nat) : p (f a) (f a) → p a a local attribute [ematch] nat.add_zero lemma ex1 (a b c : nat) : a = b + 0 → a + c = b + c := by using_smt $ do pr ← tactic.to_expr ```(nat.add_zero b), note `h none pr, trace_state, return () lemma ex2(a b c : nat) : a = b → p (f a) (f b) → p a b := by using_smt $ do intros, t ← tactic.to_expr ```(p (f a) (f a)), assert `h t, -- assert automatically closed the new goal trace_state, tactic.trace "-----", pr ← tactic.to_expr ```(pf _ h), note `h2 none pr, trace_state, return () def foo := 0 lemma fooex : foo = 0 := rfl lemma ex3 (a b c : nat) : a = b + foo → a + c = b + c := begin [smt] intros, add_fact fooex, ematch end lemma ex4 (a b c : nat) : a = b → p (f a) (f b) → p a b := begin [smt] intros, have h : p (f a) (f a), add_fact (pf _ h) end
04f9c8badb25fd59bf9f10158bdf5aeaa6eb8888
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/abelian/opposite.lean
e9639b75b3d69d0ef109aeadec077d99726a1eec
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
6,249
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.abelian.basic import category_theory.preadditive.opposite import category_theory.limits.opposites /-! # The opposite of an abelian category is abelian. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ noncomputable theory namespace category_theory open category_theory.limits variables (C : Type*) [category C] [abelian C] local attribute [instance] has_finite_limits_of_has_equalizers_and_finite_products has_finite_colimits_of_has_coequalizers_and_finite_coproducts -- Porting note: -- This should have been a global instance, -- but triggers https://github.com/leanprover/lean4/issues/2055 -- when ported to mathlib4. abelian.has_finite_biproducts instance : abelian Cᵒᵖ := { normal_mono_of_mono := λ X Y f m, by exactI normal_mono_of_normal_epi_unop _ (normal_epi_of_epi f.unop), normal_epi_of_epi := λ X Y f m, by exactI normal_epi_of_normal_mono_unop _ (normal_mono_of_mono f.unop), } section variables {C} {X Y : C} (f : X ⟶ Y) {A B : Cᵒᵖ} (g : A ⟶ B) -- TODO: Generalize (this will work whenever f has a cokernel) -- (The abelian case is probably sufficient for most applications.) /-- The kernel of `f.op` is the opposite of `cokernel f`. -/ @[simps] def kernel_op_unop : (kernel f.op).unop ≅ cokernel f := { hom := (kernel.lift f.op (cokernel.π f).op $ by simp [← op_comp]).unop, inv := cokernel.desc f (kernel.ι f.op).unop $ by { rw [← f.unop_op, ← unop_comp, f.unop_op], simp }, hom_inv_id' := begin rw [← unop_id, ← (cokernel.desc f _ _).unop_op, ← unop_comp], congr' 1, dsimp, ext, simp [← op_comp], end, inv_hom_id' := begin dsimp, ext, simp [← unop_comp], end } -- TODO: Generalize (this will work whenever f has a kernel) -- (The abelian case is probably sufficient for most applications.) /-- The cokernel of `f.op` is the opposite of `kernel f`. -/ @[simps] def cokernel_op_unop : (cokernel f.op).unop ≅ kernel f := { hom := kernel.lift f (cokernel.π f.op).unop $ by { rw [← f.unop_op, ← unop_comp, f.unop_op], simp }, inv := (cokernel.desc f.op (kernel.ι f).op $ by simp [← op_comp]).unop, hom_inv_id' := begin rw [← unop_id, ← (kernel.lift f _ _).unop_op, ← unop_comp], congr' 1, dsimp, ext, simp [← op_comp], end, inv_hom_id' := begin dsimp, ext, simp [← unop_comp], end } /-- The kernel of `g.unop` is the opposite of `cokernel g`. -/ @[simps] def kernel_unop_op : opposite.op (kernel g.unop) ≅ cokernel g := (cokernel_op_unop g.unop).op /-- The cokernel of `g.unop` is the opposite of `kernel g`. -/ @[simps] def cokernel_unop_op : opposite.op (cokernel g.unop) ≅ kernel g := (kernel_op_unop g.unop).op lemma cokernel.π_op : (cokernel.π f.op).unop = (cokernel_op_unop f).hom ≫ kernel.ι f ≫ eq_to_hom (opposite.unop_op _).symm := by simp [cokernel_op_unop] lemma kernel.ι_op : (kernel.ι f.op).unop = eq_to_hom (opposite.unop_op _) ≫ cokernel.π f ≫ (kernel_op_unop f).inv := by simp [kernel_op_unop] /-- The kernel of `f.op` is the opposite of `cokernel f`. -/ @[simps] def kernel_op_op : kernel f.op ≅ opposite.op (cokernel f) := (kernel_op_unop f).op.symm /-- The cokernel of `f.op` is the opposite of `kernel f`. -/ @[simps] def cokernel_op_op : cokernel f.op ≅ opposite.op (kernel f) := (cokernel_op_unop f).op.symm /-- The kernel of `g.unop` is the opposite of `cokernel g`. -/ @[simps] def kernel_unop_unop : kernel g.unop ≅ (cokernel g).unop := (kernel_unop_op g).unop.symm lemma kernel.ι_unop : (kernel.ι g.unop).op = eq_to_hom (opposite.op_unop _) ≫ cokernel.π g ≫ (kernel_unop_op g).inv := by simp lemma cokernel.π_unop : (cokernel.π g.unop).op = (cokernel_unop_op g).hom ≫ kernel.ι g ≫ eq_to_hom (opposite.op_unop _).symm := by simp /-- The cokernel of `g.unop` is the opposite of `kernel g`. -/ @[simps] def cokernel_unop_unop : cokernel g.unop ≅ (kernel g).unop := (cokernel_unop_op g).unop.symm /-- The opposite of the image of `g.unop` is the image of `g.` -/ def image_unop_op : opposite.op (image g.unop) ≅ image g := (abelian.image_iso_image _).op ≪≫ (cokernel_op_op _).symm ≪≫ cokernel_iso_of_eq (cokernel.π_unop _) ≪≫ (cokernel_epi_comp _ _) ≪≫ (cokernel_comp_is_iso _ _) ≪≫ (abelian.coimage_iso_image' _) /-- The opposite of the image of `f` is the image of `f.op`. -/ def image_op_op : opposite.op (image f) ≅ image f.op := image_unop_op f.op /-- The image of `f.op` is the opposite of the image of `f`. -/ def image_op_unop : (image f.op).unop ≅ image f := (image_unop_op f.op).unop /-- The image of `g` is the opposite of the image of `g.unop.` -/ def image_unop_unop : (image g).unop ≅ image g.unop := (image_unop_op g).unop lemma image_ι_op_comp_image_unop_op_hom : (image.ι g.unop).op ≫ (image_unop_op g).hom = factor_thru_image g := begin dunfold image_unop_op, simp only [←category.assoc, ←op_comp, iso.trans_hom, iso.symm_hom, iso.op_hom, cokernel_op_op_inv, cokernel_comp_is_iso_hom, cokernel_epi_comp_hom, cokernel_iso_of_eq_hom_comp_desc_assoc, abelian.coimage_iso_image'_hom, eq_to_hom_refl, is_iso.inv_id, category.id_comp (cokernel.π (kernel.ι g))], simp only [category.assoc, abelian.image_iso_image_hom_comp_image_ι, kernel.lift_ι, quiver.hom.op_unop, cokernel.π_desc], end lemma image_unop_op_hom_comp_image_ι : (image_unop_op g).hom ≫ image.ι g = (factor_thru_image g.unop).op := by simp only [←cancel_epi (image.ι g.unop).op, ←category.assoc, image_ι_op_comp_image_unop_op_hom, ←op_comp, image.fac, quiver.hom.op_unop] lemma factor_thru_image_comp_image_unop_op_inv : factor_thru_image g ≫ (image_unop_op g).inv = (image.ι g.unop).op := by rw [iso.comp_inv_eq, image_ι_op_comp_image_unop_op_hom] lemma image_unop_op_inv_comp_op_factor_thru_image : (image_unop_op g).inv ≫ (factor_thru_image g.unop).op = image.ι g := by rw [iso.inv_comp_eq, image_unop_op_hom_comp_image_ι] end end category_theory
6686b503f77128928bd57de585c5ebe025f55105
94e33a31faa76775069b071adea97e86e218a8ee
/src/analysis/locally_convex/bounded.lean
7b2bd1cb6dd268a87f6ccfab3db3a7e61af5d2ef
[ "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
6,723
lean
/- Copyright (c) 2022 Moritz Doll. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Moritz Doll -/ import analysis.locally_convex.basic import topology.bornology.basic import topology.algebra.uniform_group import analysis.locally_convex.balanced_core_hull /-! # Von Neumann Boundedness This file defines natural or von Neumann bounded sets and proves elementary properties. ## Main declarations * `bornology.is_vonN_bounded`: A set `s` is von Neumann-bounded if every neighborhood of zero absorbs `s`. * `bornology.vonN_bornology`: The bornology made of the von Neumann-bounded sets. ## Main results * `bornology.is_vonN_bounded_of_topological_space_le`: A coarser topology admits more von Neumann-bounded sets. ## References * [Bourbaki, *Topological Vector Spaces*][bourbaki1987] -/ variables {𝕜 E ι : Type*} open filter open_locale topological_space pointwise namespace bornology section semi_normed_ring section has_zero variables (𝕜) variables [semi_normed_ring 𝕜] [has_smul 𝕜 E] [has_zero E] variables [topological_space E] /-- A set `s` is von Neumann bounded if every neighborhood of 0 absorbs `s`. -/ def is_vonN_bounded (s : set E) : Prop := ∀ ⦃V⦄, V ∈ 𝓝 (0 : E) → absorbs 𝕜 V s variables (E) @[simp] lemma is_vonN_bounded_empty : is_vonN_bounded 𝕜 (∅ : set E) := λ _ _, absorbs_empty variables {𝕜 E} lemma is_vonN_bounded_iff (s : set E) : is_vonN_bounded 𝕜 s ↔ ∀ V ∈ 𝓝 (0 : E), absorbs 𝕜 V s := iff.rfl lemma _root_.filter.has_basis.is_vonN_bounded_basis_iff {q : ι → Prop} {s : ι → set E} {A : set E} (h : (𝓝 (0 : E)).has_basis q s) : is_vonN_bounded 𝕜 A ↔ ∀ i (hi : q i), absorbs 𝕜 (s i) A := begin refine ⟨λ hA i hi, hA (h.mem_of_mem hi), λ hA V hV, _⟩, rcases h.mem_iff.mp hV with ⟨i, hi, hV⟩, exact (hA i hi).mono_left hV, end /-- Subsets of bounded sets are bounded. -/ lemma is_vonN_bounded.subset {s₁ s₂ : set E} (h : s₁ ⊆ s₂) (hs₂ : is_vonN_bounded 𝕜 s₂) : is_vonN_bounded 𝕜 s₁ := λ V hV, (hs₂ hV).mono_right h /-- The union of two bounded sets is bounded. -/ lemma is_vonN_bounded.union {s₁ s₂ : set E} (hs₁ : is_vonN_bounded 𝕜 s₁) (hs₂ : is_vonN_bounded 𝕜 s₂) : is_vonN_bounded 𝕜 (s₁ ∪ s₂) := λ V hV, (hs₁ hV).union (hs₂ hV) end has_zero end semi_normed_ring section multiple_topologies variables [semi_normed_ring 𝕜] [add_comm_group E] [module 𝕜 E] /-- If a topology `t'` is coarser than `t`, then any set `s` that is bounded with respect to `t` is bounded with respect to `t'`. -/ lemma is_vonN_bounded.of_topological_space_le {t t' : topological_space E} (h : t ≤ t') {s : set E} (hs : @is_vonN_bounded 𝕜 E _ _ _ t s) : @is_vonN_bounded 𝕜 E _ _ _ t' s := λ V hV, hs $ (le_iff_nhds t t').mp h 0 hV end multiple_topologies section image variables {𝕜₁ 𝕜₂ F : Type*} [normed_division_ring 𝕜₁] [normed_division_ring 𝕜₂] [add_comm_group E] [module 𝕜₁ E] [add_comm_group F] [module 𝕜₂ F] [topological_space E] [topological_space F] /-- A continuous linear image of a bounded set is bounded. -/ lemma is_vonN_bounded.image {σ : 𝕜₁ →+* 𝕜₂} [ring_hom_surjective σ] [ring_hom_isometric σ] {s : set E} (hs : is_vonN_bounded 𝕜₁ s) (f : E →SL[σ] F) : is_vonN_bounded 𝕜₂ (f '' s) := begin let σ' := ring_equiv.of_bijective σ ⟨σ.injective, σ.is_surjective⟩, have σ_iso : isometry σ := add_monoid_hom_class.isometry_of_norm σ (λ x, ring_hom_isometric.is_iso), have σ'_symm_iso : isometry σ'.symm := σ_iso.right_inv σ'.right_inv, have f_tendsto_zero := f.continuous.tendsto 0, rw map_zero at f_tendsto_zero, intros V hV, rcases hs (f_tendsto_zero hV) with ⟨r, hrpos, hr⟩, refine ⟨r, hrpos, λ a ha, _⟩, rw ← σ'.apply_symm_apply a, have hanz : a ≠ 0 := norm_pos_iff.mp (hrpos.trans_le ha), have : σ'.symm a ≠ 0 := (ring_hom.map_ne_zero σ'.symm.to_ring_hom).mpr hanz, change _ ⊆ σ _ • _, rw [set.image_subset_iff, preimage_smul_setₛₗ _ _ _ f this.is_unit], refine hr (σ'.symm a) _, rwa σ'_symm_iso.norm_map_of_map_zero (map_zero _) end end image section normed_field variables [normed_field 𝕜] [add_comm_group E] [module 𝕜 E] variables [topological_space E] [has_continuous_smul 𝕜 E] /-- Singletons are bounded. -/ lemma is_vonN_bounded_singleton (x : E) : is_vonN_bounded 𝕜 ({x} : set E) := λ V hV, (absorbent_nhds_zero hV).absorbs /-- The union of all bounded set is the whole space. -/ lemma is_vonN_bounded_covers : ⋃₀ (set_of (is_vonN_bounded 𝕜)) = (set.univ : set E) := set.eq_univ_iff_forall.mpr (λ x, set.mem_sUnion.mpr ⟨{x}, is_vonN_bounded_singleton _, set.mem_singleton _⟩) variables (𝕜 E) /-- The von Neumann bornology defined by the von Neumann bounded sets. Note that this is not registered as an instance, in order to avoid diamonds with the metric bornology.-/ @[reducible] -- See note [reducible non-instances] def vonN_bornology : bornology E := bornology.of_bounded (set_of (is_vonN_bounded 𝕜)) (is_vonN_bounded_empty 𝕜 E) (λ _ hs _ ht, hs.subset ht) (λ _ hs _, hs.union) is_vonN_bounded_singleton variables {E} @[simp] lemma is_bounded_iff_is_vonN_bounded {s : set E} : @is_bounded _ (vonN_bornology 𝕜 E) s ↔ is_vonN_bounded 𝕜 s := is_bounded_of_bounded_iff _ end normed_field end bornology section uniform_add_group variables [nondiscrete_normed_field 𝕜] [add_comm_group E] [module 𝕜 E] variables [uniform_space E] [uniform_add_group E] [has_continuous_smul 𝕜 E] variables [t3_space E] lemma totally_bounded.is_vonN_bounded {s : set E} (hs : totally_bounded s) : bornology.is_vonN_bounded 𝕜 s := begin rw totally_bounded_iff_subset_finite_Union_nhds_zero at hs, intros U hU, have h : filter.tendsto (λ (x : E × E), x.fst + x.snd) (𝓝 (0,0)) (𝓝 ((0 : E) + (0 : E))) := tendsto_add, rw add_zero at h, have h' := (nhds_basis_closed_balanced 𝕜 E).prod (nhds_basis_closed_balanced 𝕜 E), simp_rw [←nhds_prod_eq, id.def] at h', rcases h.basis_left h' U hU with ⟨x, hx, h''⟩, rcases hs x.snd hx.2.1 with ⟨t, ht, hs⟩, refine absorbs.mono_right _ hs, rw ht.absorbs_Union, have hx_fstsnd : x.fst + x.snd ⊆ U, { intros z hz, rcases set.mem_add.mp hz with ⟨z1, z2, hz1, hz2, hz⟩, have hz' : (z1, z2) ∈ x.fst ×ˢ x.snd := ⟨hz1, hz2⟩, simpa only [hz] using h'' hz' }, refine λ y hy, absorbs.mono_left _ hx_fstsnd, rw [←set.singleton_vadd, vadd_eq_add], exact (absorbent_nhds_zero hx.1.1).absorbs.add hx.2.2.2.absorbs_self, end end uniform_add_group
6770af85f47664981ba0648c89245a8acf68beb0
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/abstract_tac.lean
e27e70436459a679d7b62826bed226f325331dac
[ "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
229
lean
def ex (a b c : nat) : a = b → c = b → a = c ∧ b = c := begin intros, split, abstract { transitivity, trace "hello", trace_state, assumption, symmetry, assumption }, abstract { symmetry, assumption } end #print ex
11fdf91c9fac550d7179d82cc639aaf1cc6a92fb
8b9f17008684d796c8022dab552e42f0cb6fb347
/hott/algebra/category/basic.hlean
85ffbbe85b894ede9aaa06c2c857eb6081e7374a
[ "Apache-2.0" ]
permissive
chubbymaggie/lean
0d06ae25f9dd396306fb02190e89422ea94afd7b
d2c7b5c31928c98f545b16420d37842c43b4ae9a
refs/heads/master
1,611,313,622,901
1,430,266,839,000
1,430,267,083,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,409
hlean
/- Copyright (c) 2014 Jakob von Raumer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: algebra.category.basic Author: Jakob von Raumer -/ import algebra.precategory.iso open iso is_equiv eq is_trunc -- A category is a precategory extended by a witness -- that the function from paths to isomorphisms, -- is an equivalecnce. namespace category definition is_univalent [reducible] {ob : Type} (C : precategory ob) := Π(a b : ob), is_equiv (@iso_of_eq ob C a b) structure category [class] (ob : Type) extends parent : precategory ob := (iso_of_path_equiv : is_univalent parent) attribute category [multiple-instances] abbreviation iso_of_path_equiv := @category.iso_of_path_equiv definition category.mk' [reducible] (ob : Type) (C : precategory ob) (H : Π (a b : ob), is_equiv (@iso_of_eq ob C a b)) : category ob := precategory.rec_on C category.mk H section basic variables {ob : Type} [C : category ob] include C -- Make iso_of_path_equiv a class instance -- TODO: Unsafe class instance? attribute iso_of_path_equiv [instance] definition eq_of_iso [reducible] {a b : ob} : a ≅ b → a = b := iso_of_eq⁻¹ᵉ set_option apply.class_instance false -- disable class instance resolution in the apply tactic definition is_trunc_1_ob : is_trunc 1 ob := begin apply is_trunc_succ_intro, intros [a, b], fapply is_trunc_is_equiv_closed, exact (@eq_of_iso _ _ a b), apply is_equiv_inv, apply is_hset_iso, end end basic -- Bundled version of categories -- we don't use Category.carrier explicitly, but rather use Precategory.carrier (to_Precategory C) structure Category : Type := (carrier : Type) (struct : category carrier) attribute Category.struct [instance] [coercion] -- definition objects [reducible] := Category.objects -- definition category_instance [instance] [coercion] [reducible] := Category.category_instance definition Category.to_Precategory [coercion] [reducible] (C : Category) : Precategory := Precategory.mk (Category.carrier C) C definition category.Mk [reducible] := Category.mk definition category.MK [reducible] (C : Precategory) (H : is_univalent C) : Category := Category.mk C (category.mk' C C H) definition Category.eta (C : Category) : Category.mk C C = C := Category.rec (λob c, idp) C end category
97046a03c4dd6a1e1f6a3c3d80eab4815e74ec69
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/stage0/src/Lean/MetavarContext.lean
3b2d13cb0ee41eb2ca8ea2b7244c64cb9671c5b0
[ "Apache-2.0" ]
permissive
banksonian/lean4
3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc
78da6b3aa2840693eea354a41e89fc5b212a5011
refs/heads/master
1,673,703,624,165
1,605,123,551,000
1,605,123,551,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
51,744
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Util.MonadCache import Lean.LocalContext namespace Lean /- The metavariable context stores metavariable declarations and their assignments. It is used in the elaborator, tactic framework, unifier (aka `isDefEq`), and type class resolution (TC). First, we list all the requirements imposed by these modules. - We may invoke TC while executing `isDefEq`. We need this feature to be able to solve unification problems such as: ``` f ?a (ringAdd ?s) ?x ?y =?= f Int intAdd n m ``` where `(?a : Type) (?s : Ring ?a) (?x ?y : ?a)` During `isDefEq` (i.e., unification), it will need to solve the constrain ``` ringAdd ?s =?= intAdd ``` We say `ringAdd ?s` is stuck because it cannot be reduced until we synthesize the term `?s : Ring ?a` using TC. This can be done since we have assigned `?a := Int` when solving `?a =?= Int`. - TC uses `isDefEq`, and `isDefEq` may create TC problems as shown aaa. Thus, we may have nested TC problems. - `isDefEq` extends the local context when going inside binders. Thus, the local context for nested TC may be an extension of the local context for outer TC. - TC should not assign metavariables created by the elaborator, simp, tactic framework, and outer TC problems. Reason: TC commits to the first solution it finds. Consider the TC problem `Coe Nat ?x`, where `?x` is a metavariable created by the caller. There are many solutions to this problem (e.g., `?x := Int`, `?x := Real`, ...), and it doesn’t make sense to commit to the first one since TC does not know the the constraints the caller may impose on `?x` after the TC problem is solved. Remark: we claim it is not feasible to make the whole system backtrackable, and allow the caller to backtrack back to TC and ask it for another solution if the first one found did not work. We claim it would be too inefficient. - TC metavariables should not leak outside of TC. Reason: we want to get rid of them after we synthesize the instance. - `simp` invokes `isDefEq` for matching the left-hand-side of equations to terms in our goal. Thus, it may invoke TC indirectly. - In Lean3, we didn’t have to create a fresh pattern for trying to match the left-hand-side of equations when executing `simp`. We had a mechanism called tmp metavariables. It avoided this overhead, but it created many problems since `simp` may indirectly call TC which may recursively call TC. Moreover, we want to allow TC to invoke tactics. Thus, when `simp` invokes `isDefEq`, it may indirectly invoke a tactic and `simp` itself. The Lean3 approach assumed that metavariables were short-lived, this is not true in Lean4, and to some extent was also not true in Lean3 since `simp`, in principle, could trigger an arbitrary number of nested TC problems. - Here are some possible call stack traces we could have in Lean3 (and Lean4). ``` Elaborator (-> TC -> isDefEq)+ Elaborator -> isDefEq (-> TC -> isDefEq)* Elaborator -> simp -> isDefEq (-> TC -> isDefEq)* ``` In Lean4, TC may also invoke tactics. - In Lean3 and Lean4, TC metavariables are not really short-lived. We solve an arbitrary number of unification problems, and we may have nested TC invocations. - TC metavariables do not share the same local context even in the same invocation. In the C++ and Lean implementations we use a trick to ensure they do: https://github.com/leanprover/lean/blob/92826917a252a6092cffaf5fc5f1acb1f8cef379/src/library/type_context.cpp#L3583-L3594 - Metavariables may be natural, synthetic or syntheticOpaque. a) Natural metavariables may be assigned by unification (i.e., `isDefEq`). b) Synthetic metavariables may still be assigned by unification, but whenever possible `isDefEq` will avoid the assignment. For example, if we have the unification constaint `?m =?= ?n`, where `?m` is synthetic, but `?n` is not, `isDefEq` solves it by using the assignment `?n := ?m`. We use synthetic metavariables for type class resolution. Any module that creates synthetic metavariables, must also check whether they have been assigned by `isDefEq`, and then still synthesize them, and check whether the sythesized result is compatible with the one assigned by `isDefEq`. c) SyntheticOpaque metavariables are never assigned by `isDefEq`. That is, the constraint `?n =?= Nat.succ Nat.zero` always fail if `?n` is a syntheticOpaque metavariable. This kind of metavariable is created by tactics such as `intro`. Reason: in the tactic framework, subgoals as represented as metavariables, and a subgoal `?n` is considered as solved whenever the metavariable is assigned. This distinction was not precise in Lean3 and produced counterintuitive behavior. For example, the following hack was added in Lean3 to work around one of these issues: https://github.com/leanprover/lean/blob/92826917a252a6092cffaf5fc5f1acb1f8cef379/src/library/type_context.cpp#L2751 - When creating lambda/forall expressions, we need to convert/abstract free variables and convert them to bound variables. Now, suppose we a trying to create a lambda/forall expression by abstracting free variables `xs` and a term `t[?m]` which contains a metavariable `?m`, and the local context of `?m` contains `xs`. The term ``` fun xs => t[?m] ``` will be ill-formed if we later assign a term `s` to `?m`, and `s` contains free variables in `xs`. We address this issue by changing the free variable abstraction procedure. We consider two cases: `?m` is natural, `?m` is synthetic. Assume the type of `?m` is `A[xs]`. Then, in both cases we create an auxiliary metavariable `?n` with type `forall xs => A[xs]`, and local context := local context of `?m` - `xs`. In both cases, we produce the term `fun xs => t[?n xs]` 1- If `?m` is natural or synthetic, then we assign `?m := ?n xs`, and we produce the term `fun xs => t[?n xs]` 2- If `?m` is syntheticOpaque, then we mark `?n` as a syntheticOpaque variable. However, `?n` is managed by the metavariable context itself. We say we have a "delayed assignment" `?n xs := ?m`. That is, after a term `s` is assigned to `?m`, and `s` does not contain metavariables, we replace any occurrence `?n ts` with `s[xs := ts]`. Gruesome details: - When we create the type `forall xs => A` for `?n`, we may encounter the same issue if `A` contains metavariables. So, the process above is recursive. We claim it terminates because we keep creating new metavariables with smaller local contexts. - Suppose, we have `t[?m]` and we want to create a let-expression by abstracting a let-decl free variable `x`, and the local context of `?m` contatins `x`. Similarly to the previous case ``` let x : T := v; t[?m] ``` will be ill-formed if we later assign a term `s` to `?m`, and `s` contains free variable `x`. Again, assume the type of `?m` is `A[x]`. 1- If `?m` is natural or synthetic, then we create `?n : (let x : T := v; A[x])` with and local context := local context of `?m` - `x`, we assign `?m := ?n`, and produce the term `let x : T := v; t[?n]`. That is, we are just making sure `?n` must never be assigned to a term containing `x`. 2- If `?m` is syntheticOpaque, we create a fresh syntheticOpaque `?n` with type `?n : T -> (let x : T := v; A[x])` and local context := local context of `?m` - `x`, create the delayed assignment `?n #[x] := ?m`, and produce the term `let x : T := v; t[?n x]`. Now suppose we assign `s` to `?m`. We do not assign the term `fun (x : T) => s` to `?n`, since `fun (x : T) => s` may not even be type correct. Instead, we just replace applications `?n r` with `s[x/r]`. The term `r` may not necessarily be a bound variable. For example, a tactic may have reduced `let x : T := v; t[?n x]` into `t[?n v]`. We are essentially using the pair "delayed assignment + application" to implement a delayed substitution. - We use TC for implementing coercions. Both Joe Hendrix and Reid Barton reported a nasty limitation. In Lean3, TC will not be used if there are metavariables in the TC problem. For example, the elaborator will not try to synthesize `Coe Nat ?x`. This is good, but this constraint is too strict for problems such as `Coe (Vector Bool ?n) (BV ?n)`. The coercion exists independently of `?n`. Thus, during TC, we want `isDefEq` to throw an exception instead of return `false` whenever it tries to assign a metavariable owned by its caller. The idea is to sign to the caller that it cannot solve the TC problem at this point, and more information is needed. That is, the caller must make progress an assign its metavariables before trying to invoke TC again. In Lean4, we are using a simpler design for the `MetavarContext`. - No distinction betwen temporary and regular metavariables. - Metavariables have a `depth` Nat field. - MetavarContext also has a `depth` field. - We bump the `MetavarContext` depth when we create a nested problem. Example: Elaborator (depth = 0) -> Simplifier matcher (depth = 1) -> TC (level = 2) -> TC (level = 3) -> ... - When `MetavarContext` is at depth N, `isDefEq` does not assign variables from `depth < N`. - Metavariables from depth N+1 must be fully assigned before we return to level N. - New design even allows us to invoke tactics from TC. * Main concern We don't have tmp metavariables anymore in Lean4. Thus, before trying to match the left-hand-side of an equation in `simp`. We first must bump the level of the `MetavarContext`, create fresh metavariables, then create a new pattern by replacing the free variable on the left-hand-side with these metavariables. We are hoping to minimize this overhead by - Using better indexing data structures in `simp`. They should reduce the number of time `simp` must invoke `isDefEq`. - Implementing `isDefEqApprox` which ignores metavariables and returns only `false` or `undef`. It is a quick filter that allows us to fail quickly and avoid the creation of new fresh metavariables, and a new pattern. - Adding built-in support for arithmetic, Logical connectives, etc. Thus, we avoid a bunch of lemmas in the simp set. - Adding support for AC-rewriting. In Lean3, users use AC lemmas as rewriting rules for "sorting" terms. This is inefficient, requires a quadratic number of rewrite steps, and does not preserve the structure of the goal. The temporary metavariables were also used in the "app builder" module used in Lean3. The app builder uses `isDefEq`. So, it could, in principle, invoke an arbitrary number of nested TC problems. However, in Lean3, all app builder uses are controlled. That is, it is mainly used to synthesize implicit arguments using very simple unification and/or non-nested TC. So, if the "app builder" becomes a bottleneck without tmp metavars, we may solve the issue by implementing `isDefEqCheap` that never invokes TC and uses tmp metavars. -/ structure LocalInstance := (className : Name) (fvar : Expr) abbrev LocalInstances := Array LocalInstance def LocalInstance.beq (i₁ i₂ : LocalInstance) : Bool := i₁.fvar == i₂.fvar instance : BEq LocalInstance := ⟨LocalInstance.beq⟩ /-- Remove local instance with the given `fvarId`. Do nothing if `localInsts` does not contain any free variable with id `fvarId`. -/ def LocalInstances.erase (localInsts : LocalInstances) (fvarId : FVarId) : LocalInstances := match localInsts.findIdx? (fun inst => inst.fvar.fvarId! == fvarId) with | some idx => localInsts.eraseIdx idx | _ => localInsts inductive MetavarKind | natural | synthetic | syntheticOpaque def MetavarKind.isSyntheticOpaque : MetavarKind → Bool | MetavarKind.syntheticOpaque => true | _ => false def MetavarKind.isNatural : MetavarKind → Bool | MetavarKind.natural => true | _ => false structure MetavarDecl := (userName : Name := Name.anonymous) (lctx : LocalContext) (type : Expr) (depth : Nat) (localInstances : LocalInstances) (kind : MetavarKind) (numScopeArgs : Nat := 0) -- See comment at `CheckAssignment` `Meta/ExprDefEq.lean` @[export lean_mk_metavar_decl] def mkMetavarDeclEx (userName : Name) (lctx : LocalContext) (type : Expr) (depth : Nat) (localInstances : LocalInstances) (kind : MetavarKind) : MetavarDecl := { userName := userName, lctx := lctx, type := type, depth := depth, localInstances := localInstances, kind := kind } instance : Inhabited MetavarDecl := ⟨{ lctx := arbitrary _, type := arbitrary _, depth := 0, localInstances := #[], kind := MetavarKind.natural }⟩ /-- A delayed assignment for a metavariable `?m`. It represents an assignment of the form `?m := (fun fvars => val)`. The local context `lctx` provides the declarations for `fvars`. Note that `fvars` may not be defined in the local context for `?m`. - TODO: after we delete the old frontend, we can remove the field `lctx`. This field is only used in old C++ implementation. -/ structure DelayedMetavarAssignment := (lctx : LocalContext) (fvars : Array Expr) (val : Expr) open Std (HashMap PersistentHashMap) structure MetavarContext := (depth : Nat := 0) (lDepth : PersistentHashMap MVarId Nat := {}) (decls : PersistentHashMap MVarId MetavarDecl := {}) (lAssignment : PersistentHashMap MVarId Level := {}) (eAssignment : PersistentHashMap MVarId Expr := {}) (dAssignment : PersistentHashMap MVarId DelayedMetavarAssignment := {}) class MonadMCtx (m : Type → Type) := (getMCtx : m MetavarContext) (modifyMCtx : (MetavarContext → MetavarContext) → m Unit) export MonadMCtx (getMCtx modifyMCtx) instance (m n) [MonadMCtx m] [MonadLift m n] : MonadMCtx n := { getMCtx := liftM (getMCtx : m _), modifyMCtx := fun f => liftM (modifyMCtx f : m _) } namespace MetavarContext instance : Inhabited MetavarContext := ⟨{}⟩ @[export lean_mk_metavar_ctx] def mkMetavarContext : Unit → MetavarContext := fun _ => {} /- Low level API for adding/declaring metavariable declarations. It is used to implement actions in the monads `MetaM`, `ElabM` and `TacticM`. It should not be used directly since the argument `(mvarId : MVarId)` is assumed to be "unique". -/ def addExprMVarDecl (mctx : MetavarContext) (mvarId : MVarId) (userName : Name) (lctx : LocalContext) (localInstances : LocalInstances) (type : Expr) (kind : MetavarKind := MetavarKind.natural) (numScopeArgs : Nat := 0) : MetavarContext := { mctx with decls := mctx.decls.insert mvarId { userName := userName, lctx := lctx, localInstances := localInstances, type := type, depth := mctx.depth, kind := kind, numScopeArgs := numScopeArgs } } @[export lean_metavar_ctx_mk_decl] def addExprMVarDeclExp (mctx : MetavarContext) (mvarId : MVarId) (userName : Name) (lctx : LocalContext) (localInstances : LocalInstances) (type : Expr) (kind : MetavarKind) : MetavarContext := addExprMVarDecl mctx mvarId userName lctx localInstances type kind /- Low level API for adding/declaring universe level metavariable declarations. It is used to implement actions in the monads `MetaM`, `ElabM` and `TacticM`. It should not be used directly since the argument `(mvarId : MVarId)` is assumed to be "unique". -/ def addLevelMVarDecl (mctx : MetavarContext) (mvarId : MVarId) : MetavarContext := { mctx with lDepth := mctx.lDepth.insert mvarId mctx.depth } @[export lean_metavar_ctx_find_decl] def findDecl? (mctx : MetavarContext) (mvarId : MVarId) : Option MetavarDecl := mctx.decls.find? mvarId def getDecl (mctx : MetavarContext) (mvarId : MVarId) : MetavarDecl := match mctx.decls.find? mvarId with | some decl => decl | none => panic! "unknown metavariable" def findUserName? (mctx : MetavarContext) (userName : Name) : Option MVarId := let search : Except MVarId Unit := mctx.decls.forM fun mvarId decl => if decl.userName == userName then throw mvarId else pure () match search with | Except.ok _ => none | Except.error mvarId => some mvarId def setMVarKind (mctx : MetavarContext) (mvarId : MVarId) (kind : MetavarKind) : MetavarContext := let decl := mctx.getDecl mvarId { mctx with decls := mctx.decls.insert mvarId { decl with kind := kind } } def setMVarUserName (mctx : MetavarContext) (mvarId : MVarId) (userName : Name) : MetavarContext := let decl := mctx.getDecl mvarId { mctx with decls := mctx.decls.insert mvarId { decl with userName := userName } } def findLevelDepth? (mctx : MetavarContext) (mvarId : MVarId) : Option Nat := mctx.lDepth.find? mvarId def getLevelDepth (mctx : MetavarContext) (mvarId : MVarId) : Nat := match mctx.findLevelDepth? mvarId with | some d => d | none => panic! "unknown metavariable" def isAnonymousMVar (mctx : MetavarContext) (mvarId : MVarId) : Bool := match mctx.findDecl? mvarId with | none => false | some mvarDecl => mvarDecl.userName.isAnonymous def renameMVar (mctx : MetavarContext) (mvarId : MVarId) (newUserName : Name) : MetavarContext := match mctx.findDecl? mvarId with | none => panic! "unknown metavariable" | some mvarDecl => { mctx with decls := mctx.decls.insert mvarId { mvarDecl with userName := newUserName } } @[export lean_metavar_ctx_assign_level] def assignLevel (m : MetavarContext) (mvarId : MVarId) (val : Level) : MetavarContext := { m with lAssignment := m.lAssignment.insert mvarId val } @[export lean_metavar_ctx_assign_expr] def assignExprCore (m : MetavarContext) (mvarId : MVarId) (val : Expr) : MetavarContext := { m with eAssignment := m.eAssignment.insert mvarId val } def assignExpr (m : MetavarContext) (mvarId : MVarId) (val : Expr) : MetavarContext := { m with eAssignment := m.eAssignment.insert mvarId val } @[export lean_metavar_ctx_assign_delayed] def assignDelayed (m : MetavarContext) (mvarId : MVarId) (lctx : LocalContext) (fvars : Array Expr) (val : Expr) : MetavarContext := { m with dAssignment := m.dAssignment.insert mvarId { lctx := lctx, fvars := fvars, val := val } } @[export lean_metavar_ctx_get_level_assignment] def getLevelAssignment? (m : MetavarContext) (mvarId : MVarId) : Option Level := m.lAssignment.find? mvarId @[export lean_metavar_ctx_get_expr_assignment] def getExprAssignment? (m : MetavarContext) (mvarId : MVarId) : Option Expr := m.eAssignment.find? mvarId @[export lean_metavar_ctx_get_delayed_assignment] def getDelayedAssignment? (m : MetavarContext) (mvarId : MVarId) : Option DelayedMetavarAssignment := m.dAssignment.find? mvarId @[export lean_metavar_ctx_is_level_assigned] def isLevelAssigned (m : MetavarContext) (mvarId : MVarId) : Bool := m.lAssignment.contains mvarId @[export lean_metavar_ctx_is_expr_assigned] def isExprAssigned (m : MetavarContext) (mvarId : MVarId) : Bool := m.eAssignment.contains mvarId @[export lean_metavar_ctx_is_delayed_assigned] def isDelayedAssigned (m : MetavarContext) (mvarId : MVarId) : Bool := m.dAssignment.contains mvarId @[export lean_metavar_ctx_erase_delayed] def eraseDelayed (m : MetavarContext) (mvarId : MVarId) : MetavarContext := { m with dAssignment := m.dAssignment.erase mvarId } /- Given a sequence of delayed assignments ``` mvarId₁ := mvarId₂ ...; ... mvarIdₙ := mvarId_root ... -- where `mvarId_root` is not delayed assigned ``` in `mctx`, `getDelayedRoot mctx mvarId₁` return `mvarId_root`. If `mvarId₁` is not delayed assigned then return `mvarId₁` -/ partial def getDelayedRoot (m : MetavarContext) : MVarId → MVarId | mvarId => match getDelayedAssignment? m mvarId with | some d => match d.val.getAppFn with | Expr.mvar mvarId _ => getDelayedRoot m mvarId | _ => mvarId | none => mvarId def isLevelAssignable (mctx : MetavarContext) (mvarId : MVarId) : Bool := match mctx.lDepth.find? mvarId with | some d => d == mctx.depth | _ => panic! "unknown universe metavariable" def isExprAssignable (mctx : MetavarContext) (mvarId : MVarId) : Bool := let decl := mctx.getDecl mvarId decl.depth == mctx.depth def incDepth (mctx : MetavarContext) : MetavarContext := { mctx with depth := mctx.depth + 1 } /-- Return true iff the given level contains an assigned metavariable. -/ def hasAssignedLevelMVar (mctx : MetavarContext) : Level → Bool | Level.succ lvl _ => lvl.hasMVar && hasAssignedLevelMVar mctx lvl | Level.max lvl₁ lvl₂ _ => (lvl₁.hasMVar && hasAssignedLevelMVar mctx lvl₁) || (lvl₂.hasMVar && hasAssignedLevelMVar mctx lvl₂) | Level.imax lvl₁ lvl₂ _ => (lvl₁.hasMVar && hasAssignedLevelMVar mctx lvl₁) || (lvl₂.hasMVar && hasAssignedLevelMVar mctx lvl₂) | Level.mvar mvarId _ => mctx.isLevelAssigned mvarId | Level.zero _ => false | Level.param _ _ => false /-- Return `true` iff expression contains assigned (level/expr) metavariables or delayed assigned mvars -/ def hasAssignedMVar (mctx : MetavarContext) : Expr → Bool | Expr.const _ lvls _ => lvls.any (hasAssignedLevelMVar mctx) | Expr.sort lvl _ => hasAssignedLevelMVar mctx lvl | Expr.app f a _ => (f.hasMVar && hasAssignedMVar mctx f) || (a.hasMVar && hasAssignedMVar mctx a) | Expr.letE _ t v b _ => (t.hasMVar && hasAssignedMVar mctx t) || (v.hasMVar && hasAssignedMVar mctx v) || (b.hasMVar && hasAssignedMVar mctx b) | Expr.forallE _ d b _ => (d.hasMVar && hasAssignedMVar mctx d) || (b.hasMVar && hasAssignedMVar mctx b) | Expr.lam _ d b _ => (d.hasMVar && hasAssignedMVar mctx d) || (b.hasMVar && hasAssignedMVar mctx b) | Expr.fvar _ _ => false | Expr.bvar _ _ => false | Expr.lit _ _ => false | Expr.mdata _ e _ => e.hasMVar && hasAssignedMVar mctx e | Expr.proj _ _ e _ => e.hasMVar && hasAssignedMVar mctx e | Expr.mvar mvarId _ => mctx.isExprAssigned mvarId || mctx.isDelayedAssigned mvarId /-- Return true iff the given level contains a metavariable that can be assigned. -/ def hasAssignableLevelMVar (mctx : MetavarContext) : Level → Bool | Level.succ lvl _ => lvl.hasMVar && hasAssignableLevelMVar mctx lvl | Level.max lvl₁ lvl₂ _ => (lvl₁.hasMVar && hasAssignableLevelMVar mctx lvl₁) || (lvl₂.hasMVar && hasAssignableLevelMVar mctx lvl₂) | Level.imax lvl₁ lvl₂ _ => (lvl₁.hasMVar && hasAssignableLevelMVar mctx lvl₁) || (lvl₂.hasMVar && hasAssignableLevelMVar mctx lvl₂) | Level.mvar mvarId _ => mctx.isLevelAssignable mvarId | Level.zero _ => false | Level.param _ _ => false /-- Return `true` iff expression contains a metavariable that can be assigned. -/ def hasAssignableMVar (mctx : MetavarContext) : Expr → Bool | Expr.const _ lvls _ => lvls.any (hasAssignableLevelMVar mctx) | Expr.sort lvl _ => hasAssignableLevelMVar mctx lvl | Expr.app f a _ => (f.hasMVar && hasAssignableMVar mctx f) || (a.hasMVar && hasAssignableMVar mctx a) | Expr.letE _ t v b _ => (t.hasMVar && hasAssignableMVar mctx t) || (v.hasMVar && hasAssignableMVar mctx v) || (b.hasMVar && hasAssignableMVar mctx b) | Expr.forallE _ d b _ => (d.hasMVar && hasAssignableMVar mctx d) || (b.hasMVar && hasAssignableMVar mctx b) | Expr.lam _ d b _ => (d.hasMVar && hasAssignableMVar mctx d) || (b.hasMVar && hasAssignableMVar mctx b) | Expr.fvar _ _ => false | Expr.bvar _ _ => false | Expr.lit _ _ => false | Expr.mdata _ e _ => e.hasMVar && hasAssignableMVar mctx e | Expr.proj _ _ e _ => e.hasMVar && hasAssignableMVar mctx e | Expr.mvar mvarId _ => mctx.isExprAssignable mvarId partial def instantiateLevelMVars {m} [Monad m] [MonadMCtx m] : Level → m Level | lvl@(Level.succ lvl₁ _) => return Level.updateSucc! lvl (← instantiateLevelMVars lvl₁) | lvl@(Level.max lvl₁ lvl₂ _) => return Level.updateMax! lvl (← instantiateLevelMVars lvl₁) (← instantiateLevelMVars lvl₂) | lvl@(Level.imax lvl₁ lvl₂ _) => return Level.updateIMax! lvl (← instantiateLevelMVars lvl₁) (← instantiateLevelMVars lvl₂) | lvl@(Level.mvar mvarId _) => do match getLevelAssignment? (← getMCtx) mvarId with | some newLvl => if !newLvl.hasMVar then pure newLvl else do let newLvl' ← instantiateLevelMVars newLvl modifyMCtx fun mctx => mctx.assignLevel mvarId newLvl' pure newLvl' | none => pure lvl | lvl => pure lvl /-- instantiateExprMVars main function -/ partial def instantiateExprMVars {m ω} [Monad m] [MonadMCtx m] [STWorld ω m] [MonadLiftT (ST ω) m] (e : Expr) : MonadCacheT Expr Expr m Expr := if !e.hasMVar then pure e else checkCache e fun e => do match e with | Expr.proj _ _ s _ => return e.updateProj! (← instantiateExprMVars s) | Expr.forallE _ d b _ => return e.updateForallE! (← instantiateExprMVars d) (← instantiateExprMVars b) | Expr.lam _ d b _ => return e.updateLambdaE! (← instantiateExprMVars d) (← instantiateExprMVars b) | Expr.letE _ t v b _ => return e.updateLet! (← instantiateExprMVars t) (← instantiateExprMVars v) (← instantiateExprMVars b) | Expr.const _ lvls _ => return e.updateConst! (← lvls.mapM instantiateLevelMVars) | Expr.sort lvl _ => return e.updateSort! (← instantiateLevelMVars lvl) | Expr.mdata _ b _ => return e.updateMData! (← instantiateExprMVars b) | Expr.app _ _ _ => e.withApp fun f args => do let instArgs (f : Expr) : MonadCacheT Expr Expr m Expr := do let args ← args.mapM instantiateExprMVars pure (mkAppN f args) let instApp : MonadCacheT Expr Expr m Expr := do let wasMVar := f.isMVar let f ← instantiateExprMVars f if wasMVar && f.isLambda then /- Some of the arguments in args are irrelevant after we beta reduce. -/ instantiateExprMVars (f.betaRev args.reverse) else instArgs f match f with | Expr.mvar mvarId _ => let mctx ← getMCtx match mctx.getDelayedAssignment? mvarId with | none => instApp | some { fvars := fvars, val := val, .. } => /- Apply "delayed substitution" (i.e., delayed assignment + application). That is, `f` is some metavariable `?m`, that is delayed assigned to `val`. If after instantiating `val`, we obtain `newVal`, and `newVal` does not contain metavariables, we replace the free variables `fvars` in `newVal` with the first `fvars.size` elements of `args`. -/ if fvars.size > args.size then /- We don't have sufficient arguments for instantiating the free variables `fvars`. This can only happy if a tactic or elaboration function is not implemented correctly. We decided to not use `panic!` here and report it as an error in the frontend when we are checking for unassigned metavariables in an elaborated term. -/ instArgs f else let newVal ← instantiateExprMVars val if newVal.hasExprMVar then instArgs f else do let args ← args.mapM instantiateExprMVars /- Example: suppose we have `?m t1 t2 t3` That is, `f := ?m` and `args := #[t1, t2, t3]` Morever, `?m` is delayed assigned `?m #[x, y] := f x y` where, `fvars := #[x, y]` and `newVal := f x y`. After abstracting `newVal`, we have `f (Expr.bvar 0) (Expr.bvar 1)`. After `instantiaterRevRange 0 2 args`, we have `f t1 t2`. After `mkAppRange 2 3`, we have `f t1 t2 t3` -/ let newVal := newVal.abstract fvars let result := newVal.instantiateRevRange 0 fvars.size args let result := mkAppRange result fvars.size args.size args pure $ result | _ => instApp | e@(Expr.mvar mvarId _) => checkCache e fun e => do let mctx ← getMCtx match mctx.getExprAssignment? mvarId with | some newE => do let newE' ← instantiateExprMVars newE modifyMCtx fun mctx => mctx.assignExpr mvarId newE' pure newE' | none => pure e | e => pure e instance {ω} : MonadMCtx (StateRefT MetavarContext (ST ω)) := { getMCtx := get, modifyMCtx := modify } def instantiateMVars (mctx : MetavarContext) (e : Expr) : Expr × MetavarContext := if !e.hasMVar then (e, mctx) else let instantiate {ω} (e : Expr) : (MonadCacheT Expr Expr $ StateRefT MetavarContext $ ST ω) Expr := instantiateExprMVars e runST fun _ => instantiate e $.run $.run mctx def instantiateLCtxMVars (mctx : MetavarContext) (lctx : LocalContext) : LocalContext × MetavarContext := lctx.foldl (fun (result : LocalContext × MetavarContext) ldecl => let (lctx, mctx) := result; match ldecl with | LocalDecl.cdecl _ fvarId userName type bi => let (type, mctx) := mctx.instantiateMVars type (lctx.mkLocalDecl fvarId userName type bi, mctx) | LocalDecl.ldecl _ fvarId userName type value nonDep => let (type, mctx) := mctx.instantiateMVars type let (value, mctx) := mctx.instantiateMVars value (lctx.mkLetDecl fvarId userName type value nonDep, mctx)) ({}, mctx) def instantiateMVarDeclMVars (mctx : MetavarContext) (mvarId : MVarId) : MetavarContext := let mvarDecl := mctx.getDecl mvarId let (lctx, mctx) := mctx.instantiateLCtxMVars mvarDecl.lctx let (type, mctx) := mctx.instantiateMVars mvarDecl.type { mctx with decls := mctx.decls.insert mvarId { mvarDecl with lctx := lctx, type := type } } namespace DependsOn private abbrev M := StateM ExprSet private def shouldVisit (e : Expr) : M Bool := if !e.hasMVar && !e.hasFVar then pure false else do let s ← get if s.contains e then pure false else do modify fun s => s.insert e pure true @[specialize] private partial def dep (mctx : MetavarContext) (p : FVarId → Bool) (e : Expr) : M Bool := let rec visit (e : Expr) : M Bool := do if !(← shouldVisit e) then pure false else visitMain e, visitMain : Expr → M Bool | Expr.proj _ _ s _ => visit s | Expr.forallE _ d b _ => visit d <||> visit b | Expr.lam _ d b _ => visit d <||> visit b | Expr.letE _ t v b _ => visit t <||> visit v <||> visit b | Expr.mdata _ b _ => visit b | Expr.app f a _ => visit a <||> if f.isApp then visitMain f else visit f | Expr.mvar mvarId _ => match mctx.getExprAssignment? mvarId with | some a => visit a | none => let lctx := (mctx.getDecl mvarId).lctx pure $ lctx.any $ fun decl => p decl.fvarId | Expr.fvar fvarId _ => pure $ p fvarId | e => pure false visit e @[inline] partial def main (mctx : MetavarContext) (p : FVarId → Bool) (e : Expr) : M Bool := if !e.hasFVar && !e.hasMVar then pure false else dep mctx p e end DependsOn /-- Return `true` iff `e` depends on a free variable `x` s.t. `p x` is `true`. For each metavariable `?m` occurring in `x` 1- If `?m := t`, then we visit `t` looking for `x` 2- If `?m` is unassigned, then we consider the worst case and check whether `x` is in the local context of `?m`. This case is a "may dependency". That is, we may assign a term `t` to `?m` s.t. `t` contains `x`. -/ @[inline] def findExprDependsOn (mctx : MetavarContext) (e : Expr) (p : FVarId → Bool) : Bool := (DependsOn.main mctx p e).run' {} /-- Similar to `findExprDependsOn`, but checks the expressions in the given local declaration depends on a free variable `x` s.t. `p x` is `true`. -/ @[inline] def findLocalDeclDependsOn (mctx : MetavarContext) (localDecl : LocalDecl) (p : FVarId → Bool) : Bool := match localDecl with | LocalDecl.cdecl _ _ _ type _ => findExprDependsOn mctx type p | LocalDecl.ldecl _ _ _ type value _ => (DependsOn.main mctx p type <||> DependsOn.main mctx p value).run' {} def exprDependsOn (mctx : MetavarContext) (e : Expr) (fvarId : FVarId) : Bool := findExprDependsOn mctx e $ fun fvarId' => fvarId == fvarId' def localDeclDependsOn (mctx : MetavarContext) (localDecl : LocalDecl) (fvarId : FVarId) : Bool := findLocalDeclDependsOn mctx localDecl $ fun fvarId' => fvarId == fvarId' namespace MkBinding inductive Exception | revertFailure (mctx : MetavarContext) (lctx : LocalContext) (toRevert : Array Expr) (decl : LocalDecl) protected def Exception.toString : Exception → String | Exception.revertFailure _ lctx toRevert decl => "failed to revert " ++ toString (toRevert.map (fun x => "'" ++ toString (lctx.getFVar! x).userName ++ "'")) ++ ", '" ++ toString decl.userName ++ "' depends on them, and it is an auxiliary declaration created by the elaborator" ++ " (possible solution: use tactic 'clear' to remove '" ++ toString decl.userName ++ "' from local context)" instance : ToString Exception := ⟨Exception.toString⟩ /-- `MkBinding` and `elimMVarDepsAux` are mutually recursive, but `cache` is only used at `elimMVarDepsAux`. We use a single state object for convenience. We have a `NameGenerator` because we need to generate fresh auxiliary metavariables. -/ structure State := (mctx : MetavarContext) (ngen : NameGenerator) (cache : HashMap Expr Expr := {}) -- abbrev MCore := EStateM Exception State abbrev M := ReaderT Bool (EStateM Exception State) def preserveOrder : M Bool := read instance : MonadHashMapCacheAdapter Expr Expr M := { getCache := do let s ← get; pure s.cache, modifyCache := fun f => modify fun s => { s with cache := f s.cache } } /-- Return the local declaration of the free variable `x` in `xs` with the smallest index -/ private def getLocalDeclWithSmallestIdx (lctx : LocalContext) (xs : Array Expr) : LocalDecl := do let mut d : LocalDecl := lctx.getFVar! xs[0] for i in [1:xs.size] do let curr := lctx.getFVar! xs[i] if curr.index < d.index then d := curr return d /-- Given `toRevert` an array of free variables s.t. `lctx` contains their declarations, return a new array of free variables that contains `toRevert` and all free variables in `lctx` that may depend on `toRevert`. Remark: the result is sorted by `LocalDecl` indices. Remark: We used to throw an `Exception.revertFailure` exception when an auxiliary declaration had to be reversed. Recall that auxiliary declarations are created when compiling (mutually) recursive definitions. The `revertFailure` due to auxiliary declaration dependency was originally introduced in Lean3 to address issue https://github.com/leanprover/lean/issues/1258. In Lean4, this solution is not satisfactory because all definitions/theorems are potentially recursive. So, even an simple (incomplete) definition such as ``` variables {α : Type} in def f (a : α) : List α := _ ``` would trigger the `Exception.revertFailure` exception. In the definition above, the elaborator creates the auxiliary definition `f : {α : Type} → List α`. The `_` is elaborated as a new fresh variable `?m` that contains `α : Type`, `a : α`, and `f : α → List α` in its context, When we try to create the lambda `fun {α : Type} (a : α) => ?m`, we first need to create an auxiliary `?n` which do not contain `α` and `a` in its context. That is, we create the metavariable `?n : {α : Type} → (a : α) → (f : α → List α) → List α`, add the delayed assignment `?n #[α, a, f] := ?m α a f`, and create the lambda `fun {α : Type} (a : α) => ?n α a f`. See `elimMVarDeps` for more information. If we kept using the Lean3 approach, we would get the `Exception.revertFailure` exception because we are reverting the auxiliary definition `f`. Note that https://github.com/leanprover/lean/issues/1258 is not an issue in Lean4 because we have changed how we compile recursive definitions. -/ private def collectDeps (mctx : MetavarContext) (lctx : LocalContext) (toRevert : Array Expr) (preserveOrder : Bool) : Except Exception (Array Expr) := do if toRevert.size == 0 then pure toRevert else if preserveOrder then -- Make sure none of `toRevert` is an AuxDecl -- Make sure toRevert[j] does not depend on toRevert[i] for j > i toRevert.size.forM fun i => do let fvar := toRevert[i] let decl := lctx.getFVar! fvar i.forM fun j => do let prevFVar := toRevert[j] let prevDecl := lctx.getFVar! prevFVar if localDeclDependsOn mctx prevDecl fvar.fvarId! then throw (Exception.revertFailure mctx lctx toRevert prevDecl) let newToRevert := if preserveOrder then toRevert else Array.mkEmpty toRevert.size let firstDeclToVisit := getLocalDeclWithSmallestIdx lctx toRevert let initSize := newToRevert.size lctx.foldlM (init := newToRevert) (start := firstDeclToVisit.index) fun (newToRevert : Array Expr) decl => if initSize.any $ fun i => decl.fvarId == (newToRevert.get! i).fvarId! then pure newToRevert else if toRevert.any (fun x => decl.fvarId == x.fvarId!) then pure (newToRevert.push decl.toExpr) else if findLocalDeclDependsOn mctx decl (fun fvarId => newToRevert.any $ fun x => x.fvarId! == fvarId) then pure (newToRevert.push decl.toExpr) else pure newToRevert /-- Create a new `LocalContext` by removing the free variables in `toRevert` from `lctx`. We use this function when we create auxiliary metavariables at `elimMVarDepsAux`. -/ private def reduceLocalContext (lctx : LocalContext) (toRevert : Array Expr) : LocalContext := toRevert.foldr (fun x lctx => lctx.erase x.fvarId!) lctx @[inline] private def getMCtx : M MetavarContext := do let s ← get; pure s.mctx /-- Return free variables in `xs` that are in the local context `lctx` -/ private def getInScope (lctx : LocalContext) (xs : Array Expr) : Array Expr := xs.foldl (fun scope x => if lctx.contains x.fvarId! then scope.push x else scope) #[] /-- Execute `x` with an empty cache, and then restore the original cache. -/ @[inline] private def withFreshCache {α} (x : M α) : M α := do let cache ← modifyGet $ fun s => (s.cache, { s with cache := {} }) let a ← x modify fun s => { s with cache := cache } pure a /-- Create an application `mvar ys` where `ys` are the free variables. See "Gruesome details" in the beginning of the file for understanding how let-decl free variables are handled. -/ private def mkMVarApp (lctx : LocalContext) (mvar : Expr) (xs : Array Expr) (kind : MetavarKind) : Expr := xs.foldl (fun e x => match kind with | MetavarKind.syntheticOpaque => mkApp e x | _ => if (lctx.getFVar! x).isLet then e else mkApp e x) mvar /-- Return true iff some `e` in `es` depends on `fvarId` -/ private def anyDependsOn (mctx : MetavarContext) (es : Array Expr) (fvarId : FVarId) : Bool := es.any fun e => exprDependsOn mctx e fvarId private partial def elimMVarDepsAux (xs : Array Expr) (e : Expr) : M Expr := let rec visit (e : Expr) : M Expr := if !e.hasMVar then pure e else checkCache e elim, elim (e : Expr) : M Expr := do match e with | Expr.proj _ _ s _ => return e.updateProj! (← visit s) | Expr.forallE _ d b _ => return e.updateForallE! (← visit d) (← visit b) | Expr.lam _ d b _ => return e.updateLambdaE! (← visit d) (← visit b) | Expr.letE _ t v b _ => return e.updateLet! (← visit t) (← visit v) (← visit b) | Expr.mdata _ b _ => return e.updateMData! (← visit b) | Expr.app _ _ _ => e.withApp fun f args => elimApp f args | Expr.mvar mvarId _ => elimApp e #[] | e => return e, abstractRangeAux (xs : Array Expr) (i : Nat) (e : Expr) : M Expr := do let e ← elim e pure (e.abstractRange i xs), mkAuxMVarType (lctx : LocalContext) (xs : Array Expr) (kind : MetavarKind) (e : Expr) : M Expr := do let e ← abstractRangeAux xs xs.size e xs.size.foldRevM (fun i e => let x := xs[i] match lctx.getFVar! x with | LocalDecl.cdecl _ _ n type bi => do let type := type.headBeta let type ← abstractRangeAux xs i type pure $ Lean.mkForall n bi type e | LocalDecl.ldecl _ _ n type value nonDep => do let type := type.headBeta let type ← abstractRangeAux xs i type let value ← abstractRangeAux xs i value let e := mkLet n type value e nonDep match kind with | MetavarKind.syntheticOpaque => -- See "Gruesome details" section in the beginning of the file let e := e.liftLooseBVars 0 1 pure $ mkForall n BinderInfo.default type e | _ => pure e) e, elimApp (f : Expr) (args : Array Expr) : M Expr := do match f with | Expr.mvar mvarId _ => let processDefault (newF : Expr) : M Expr := do if newF.isLambda then let args ← args.mapM visit elim $ newF.betaRev args.reverse else if newF == f then let args ← args.mapM visit pure $ mkAppN newF args else elimApp newF args let mctx ← getMCtx match mctx.getExprAssignment? mvarId with | some val => processDefault val | _ => let mvarDecl := mctx.getDecl mvarId let mvarLCtx := mvarDecl.lctx let toRevert := getInScope mvarLCtx xs if toRevert.size == 0 then processDefault f else let newMVarKind := if !mctx.isExprAssignable mvarId then MetavarKind.syntheticOpaque else mvarDecl.kind /- If `mvarId` is the lhs of a delayed assignment `?m #[x_1, ... x_n] := val`, then `nestedFVars` is `#[x_1, ..., x_n]`. In this case, we produce a new `syntheticOpaque` metavariable `?n` and a delayed assignment ``` ?n #[y_1, ..., y_m, x_1, ... x_n] := ?m x_1 ... x_n ``` where `#[y_1, ..., y_m]` is `toRevert` after `collectDeps`. Remark: `newMVarKind != MetavarKind.syntheticOpaque ==> nestedFVars == #[]` -/ let cont (nestedFVars : Array Expr) : M Expr := do let args ← args.mapM visit let preserve ← preserveOrder match collectDeps mctx mvarLCtx toRevert preserve with | Except.error ex => throw ex | Except.ok toRevert => let newMVarLCtx := reduceLocalContext mvarLCtx toRevert let newLocalInsts := mvarDecl.localInstances.filter fun inst => toRevert.all $ fun x => inst.fvar != x let newMVarType ← mkAuxMVarType mvarLCtx toRevert newMVarKind mvarDecl.type let newMVarId ← get >>= fun s => pure s.ngen.curr let newMVar := mkMVar newMVarId let result := mkMVarApp mvarLCtx newMVar toRevert newMVarKind let numScopeArgs := mvarDecl.numScopeArgs + result.getAppNumArgs modify fun s => { s with mctx := s.mctx.addExprMVarDecl newMVarId Name.anonymous newMVarLCtx newLocalInsts newMVarType newMVarKind numScopeArgs, ngen := s.ngen.next } match newMVarKind with | MetavarKind.syntheticOpaque => modify fun s => { s with mctx := assignDelayed s.mctx newMVarId mvarLCtx (toRevert ++ nestedFVars) (mkAppN f nestedFVars) } | _ => modify fun s => { s with mctx := assignExpr s.mctx mvarId result } pure (mkAppN result args) if !mvarDecl.kind.isSyntheticOpaque then cont #[] else match mctx.getDelayedAssignment? mvarId with | none => cont #[] | some { fvars := fvars, .. } => cont fvars | _ => let f ← visit f let args ← args.mapM visit pure (mkAppN f args) elim e partial def elimMVarDeps (xs : Array Expr) (e : Expr) : M Expr := if !e.hasMVar then pure e else withFreshCache $ elimMVarDepsAux xs e /-- Similar to `Expr.abstractRange`, but handles metavariables correctly. It uses `elimMVarDeps` to ensure `e` and the type of the free variables `xs` do not contain a metavariable `?m` s.t. local context of `?m` contains a free variable in `xs`. `elimMVarDeps` is defined later in this file. -/ @[inline] private def abstractRange (xs : Array Expr) (i : Nat) (e : Expr) : M Expr := do let e ← elimMVarDeps xs e pure (e.abstractRange i xs) /-- Similar to `LocalContext.mkBinding`, but handles metavariables correctly. If `usedOnly == false` then `forall` and `lambda` are created only for used variables. -/ @[specialize] def mkBinding (isLambda : Bool) (lctx : LocalContext) (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) : M (Expr × Nat) := do let e ← abstractRange xs xs.size e xs.size.foldRevM (fun i (p : Expr × Nat) => do let (e, num) := p; let x := xs[i] match lctx.getFVar! x with | LocalDecl.cdecl _ _ n type bi => if !usedOnly || e.hasLooseBVar 0 then let type := type.headBeta; let type ← abstractRange xs i type if isLambda then pure (Lean.mkLambda n bi type e, num + 1) else pure (Lean.mkForall n bi type e, num + 1) else pure (e.lowerLooseBVars 1 1, num) | LocalDecl.ldecl _ _ n type value nonDep => if e.hasLooseBVar 0 then let type ← abstractRange xs i type let value ← abstractRange xs i value pure (mkLet n type value e nonDep, num + 1) else pure (e.lowerLooseBVars 1 1, num)) (e, 0) end MkBinding abbrev MkBindingM := ReaderT LocalContext MkBinding.MCore def elimMVarDeps (xs : Array Expr) (e : Expr) (preserveOrder : Bool) : MkBindingM Expr := fun _ => MkBinding.elimMVarDeps xs e preserveOrder def mkBinding (isLambda : Bool) (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) : MkBindingM (Expr × Nat) := fun lctx => MkBinding.mkBinding isLambda lctx xs e usedOnly false @[inline] def mkLambda (xs : Array Expr) (e : Expr) : MkBindingM Expr := do let (e, _) ← mkBinding true xs e pure e @[inline] def mkForall (xs : Array Expr) (e : Expr) : MkBindingM Expr := do let (e, _) ← mkBinding false xs e pure e @[inline] def mkForallUsedOnly (xs : Array Expr) (e : Expr) : MkBindingM (Expr × Nat) := do mkBinding false xs e true /-- `isWellFormed mctx lctx e` return true if - All locals in `e` are declared in `lctx` - All metavariables `?m` in `e` have a local context which is a subprefix of `lctx` or are assigned, and the assignment is well-formed. -/ partial def isWellFormed (mctx : MetavarContext) (lctx : LocalContext) : Expr → Bool | Expr.mdata _ e _ => isWellFormed mctx lctx e | Expr.proj _ _ e _ => isWellFormed mctx lctx e | e@(Expr.app f a _) => (!e.hasExprMVar && !e.hasFVar) || (isWellFormed mctx lctx f && isWellFormed mctx lctx a) | e@(Expr.lam _ d b _) => (!e.hasExprMVar && !e.hasFVar) || (isWellFormed mctx lctx d && isWellFormed mctx lctx b) | e@(Expr.forallE _ d b _) => (!e.hasExprMVar && !e.hasFVar) || (isWellFormed mctx lctx d && isWellFormed mctx lctx b) | e@(Expr.letE _ t v b _) => (!e.hasExprMVar && !e.hasFVar) || (isWellFormed mctx lctx t && isWellFormed mctx lctx v && isWellFormed mctx lctx b) | Expr.const _ _ _ => true | Expr.bvar _ _ => true | Expr.sort _ _ => true | Expr.lit _ _ => true | Expr.mvar mvarId _ => let mvarDecl := mctx.getDecl mvarId; if mvarDecl.lctx.isSubPrefixOf lctx then true else match mctx.getExprAssignment? mvarId with | none => false | some v => isWellFormed mctx lctx v | Expr.fvar fvarId _ => lctx.contains fvarId namespace LevelMVarToParam structure Context := (paramNamePrefix : Name) (alreadyUsedPred : Name → Bool) structure State := (mctx : MetavarContext) (paramNames : Array Name := #[]) (nextParamIdx : Nat) abbrev M := ReaderT Context $ StateM State partial def mkParamName : M Name := do let ctx ← read let s ← get let newParamName := ctx.paramNamePrefix.appendIndexAfter s.nextParamIdx if ctx.alreadyUsedPred newParamName then modify fun s => { s with nextParamIdx := s.nextParamIdx + 1 } mkParamName else do modify fun s => { s with nextParamIdx := s.nextParamIdx + 1, paramNames := s.paramNames.push newParamName } pure newParamName partial def visitLevel (u : Level) : M Level := do match u with | Level.succ v _ => return u.updateSucc! (← visitLevel v) | Level.max v₁ v₂ _ => return u.updateMax! (← visitLevel v₁) (← visitLevel v₂) | Level.imax v₁ v₂ _ => return u.updateIMax! (← visitLevel v₁) (← visitLevel v₂) | Level.zero _ => pure u | Level.param _ _ => pure u | Level.mvar mvarId _ => let s ← get match s.mctx.getLevelAssignment? mvarId with | some v => visitLevel v | none => let p ← mkParamName let p := mkLevelParam p modify fun s => { s with mctx := s.mctx.assignLevel mvarId p } pure p partial def main (e : Expr) : M Expr := do if !e.hasMVar then pure e else match e with | Expr.proj _ _ s _ => return e.updateProj! (← main s) | Expr.forallE _ d b _ => return e.updateForallE! (← main d) (← main b) | Expr.lam _ d b _ => return e.updateLambdaE! (← main d) (← main b) | Expr.letE _ t v b _ => return e.updateLet! (← main t) (← main v) (← main b) | Expr.app f a _ => return e.updateApp! (← main f) (← main a) | Expr.mdata _ b _ => return e.updateMData! (← main b) | Expr.const _ us _ => return e.updateConst! (← us.mapM visitLevel) | Expr.sort u _ => return e.updateSort! (← visitLevel u) | Expr.mvar mvarId _ => let s ← get match s.mctx.getExprAssignment? mvarId with | some v => main v | none => pure e | e => pure e end LevelMVarToParam structure UnivMVarParamResult := (mctx : MetavarContext) (newParamNames : Array Name) (nextParamIdx : Nat) (expr : Expr) def levelMVarToParam (mctx : MetavarContext) (alreadyUsedPred : Name → Bool) (e : Expr) (paramNamePrefix : Name := `u) (nextParamIdx : Nat := 1) : UnivMVarParamResult := let (e, s) := LevelMVarToParam.main e { paramNamePrefix := paramNamePrefix, alreadyUsedPred := alreadyUsedPred } { mctx := mctx, nextParamIdx := nextParamIdx } { mctx := s.mctx, newParamNames := s.paramNames, nextParamIdx := s.nextParamIdx, expr := e } def getExprAssignmentDomain (mctx : MetavarContext) : Array MVarId := mctx.eAssignment.foldl (fun a mvarId _ => Array.push a mvarId) #[] end MetavarContext end Lean
3632e9cdfc0874a02948b18025e190086479fefd
9dc8cecdf3c4634764a18254e94d43da07142918
/test/rcases.lean
30b131d1ec3931aac30614d0c94adad91dbf26bc
[ "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
9,069
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import tactic.rcases instance {α} : has_inter (set α) := ⟨λ s t, {a | a ∈ s ∧ a ∈ t}⟩ universe u variables {α β γ : Type u} example (x : α × β × γ) : true := begin rcases x with ⟨a, b, c⟩, { guard_hyp a : α, guard_hyp b : β, guard_hyp c : γ, trivial } end example (x : α × β × γ) : true := begin rcases x with ⟨a, ⟨-, c⟩⟩, { guard_hyp a : α, success_if_fail { guard_hyp x_snd_fst : β }, guard_hyp c : γ, trivial } end example (x : (α × β) × γ) : true := begin rcases x with ⟨⟨a:α, b⟩, c⟩, { guard_hyp a : α, guard_hyp b : β, guard_hyp c : γ, trivial } end example : inhabited α × option β ⊕ γ → true := begin rintro (⟨⟨a⟩, _ | b⟩ | c), { guard_hyp a : α, trivial }, { guard_hyp a : α, guard_hyp b : β, trivial }, { guard_hyp c : γ, trivial } end example : cond ff ℕ ℤ → cond tt ℤ ℕ → (ℕ ⊕ unit) → true := begin rintro (x y : ℤ) (z | u), { guard_hyp x : ℤ, guard_hyp y : ℤ, guard_hyp z : ℕ, trivial }, { guard_hyp x : ℤ, guard_hyp y : ℤ, guard_hyp u : unit, trivial } end example (x y : ℕ) (h : x = y) : true := begin rcases x with _|⟨⟩|z, { guard_hyp h : nat.zero = y, trivial }, { guard_hyp h : nat.succ nat.zero = y, trivial }, { guard_hyp z : ℕ, guard_hyp h : z.succ.succ = y, trivial }, end -- from equiv.sum_empty example (s : α ⊕ empty) : true := begin rcases s with _ | ⟨⟨⟩⟩, { guard_hyp s : α, trivial } end example : true := begin obtain ⟨n : ℕ, h : n = n, -⟩ : ∃ n : ℕ, n = n ∧ true, { existsi 0, simp }, guard_hyp n : ℕ, guard_hyp h : n = n, success_if_fail {assumption}, trivial end example : true := begin obtain : ∃ n : ℕ, n = n ∧ true, { existsi 0, simp }, trivial end example : true := begin obtain (h : true) | ⟨⟨⟩⟩ : true ∨ false, { left, trivial }, guard_hyp h : true, trivial end example : true := begin obtain h | ⟨⟨⟩⟩ : true ∨ false := or.inl trivial, guard_hyp h : true, trivial end example : true := begin obtain ⟨h, h2⟩ := and.intro trivial trivial, guard_hyp h : true, guard_hyp h2 : true, trivial end example : true := begin success_if_fail {obtain ⟨h, h2⟩}, trivial end example (x y : α × β) : true := begin rcases ⟨x, y⟩ with ⟨⟨a, b⟩, c, d⟩, { guard_hyp a : α, guard_hyp b : β, guard_hyp c : α, guard_hyp d : β, trivial } end example (x y : α ⊕ β) : true := begin obtain ⟨a|b, c|d⟩ := ⟨x, y⟩, { guard_hyp a : α, guard_hyp c : α, trivial }, { guard_hyp a : α, guard_hyp d : β, trivial }, { guard_hyp b : β, guard_hyp c : α, trivial }, { guard_hyp b : β, guard_hyp d : β, trivial }, end example {i j : ℕ} : (Σ' x, i ≤ x ∧ x ≤ j) → i ≤ j := begin intro h, rcases h' : h with ⟨x,h₀,h₁⟩, guard_hyp h' : h = ⟨x,h₀,h₁⟩, apply le_trans h₀ h₁, end protected def set.foo {α β} (s : set α) (t : set β) : set (α × β) := ∅ example {α} (V : set α) (w : true → ∃ p, p ∈ (V.foo V) ∩ (V.foo V)) : true := begin obtain ⟨a, h⟩ : ∃ p, p ∈ (V.foo V) ∩ (V.foo V) := w trivial, trivial, end example (n : ℕ) : true := begin obtain one_lt_n | n_le_one : 1 < n + 1 ∨ n + 1 ≤ 1 := nat.lt_or_ge 1 (n + 1), trivial, trivial, end example (n : ℕ) : true := begin obtain one_lt_n | (n_le_one : n + 1 ≤ 1) := nat.lt_or_ge 1 (n + 1), trivial, trivial, end example (h : ∃ x : ℕ, x = x ∧ 1 = 1) : true := begin rcases h with ⟨-, _⟩, (do lc ← tactic.local_context, guard lc.empty), trivial end example (h : ∃ x : ℕ, x = x ∧ 1 = 1) : true := begin rcases h with ⟨-, _, h⟩, (do lc ← tactic.local_context, guard (lc.length = 1)), guard_hyp h : 1 = 1, trivial end example (h : true ∨ true ∨ true) : true := begin rcases h with -|-|-, iterate 3 { (do lc ← tactic.local_context, guard lc.empty), trivial }, end example : bool → false → true | ff := by rintro ⟨⟩ | tt := by rintro ⟨⟩ example : true := begin obtain h : true, { trivial }, exact h end example {a b} (h : a ∧ b) : a ∧ b := begin rcases h with t, exact t end open tactic meta def test_rcases_hint (s : string) (num_goals : ℕ) (depth := 5) : tactic unit := do change `(true), h ← get_local `h, pat ← rcases_hint ```(h) depth, p ← pp pat, guard (p.to_string = s) <|> fail format!"got '{p.to_string}', expected: '{s}'", gs ← get_goals, guard (gs.length = num_goals) <|> fail format!"there are {gs.length} goals remaining", all_goals triv $> () example {α} (h : ∃ x : α, x = x) := by test_rcases_hint "⟨h_w, ⟨⟩⟩" 1 example (h : true ∨ true ∨ true) := by test_rcases_hint "⟨⟨⟩⟩ | ⟨⟨⟩⟩ | ⟨⟨⟩⟩" 3 example (h : ℕ) := by test_rcases_hint "_ | _ | h" 3 2 example {p} (h : (p ∧ p) ∨ (p ∧ p)) := by test_rcases_hint "⟨h_left, h_right⟩ | ⟨h_left, h_right⟩" 2 example {p} (h : (p ∧ p) ∨ (p ∧ (p ∨ p))) := by test_rcases_hint "⟨h_left, h_right⟩ | ⟨h_left, h_right | h_right⟩" 3 example {p} (h : p ∧ (p ∨ p)) := by test_rcases_hint "⟨h_left, h_right | h_right⟩" 2 example (h : 0 < 2) := by test_rcases_hint "_ | ⟨_, _ | ⟨_, ⟨⟩⟩⟩" 1 example (h : 3 < 2) := by test_rcases_hint "_ | ⟨_, _ | ⟨_, ⟨⟩⟩⟩" 0 example (h : 3 < 0) := by test_rcases_hint "⟨⟩" 0 example (h : false) := by test_rcases_hint "⟨⟩" 0 example (h : true) := by test_rcases_hint "⟨⟩" 1 example {α} (h : list α) := by test_rcases_hint "_ | ⟨h_hd, _ | ⟨h_tl_hd, h_tl_tl⟩⟩" 3 2 example {α} (h : (α ⊕ α) × α) := by test_rcases_hint "⟨h_fst | h_fst, h_snd⟩" 2 2 inductive foo (α : Type) : ℕ → Type | zero : foo 0 | one (m) : α → foo m example {α} (h : foo α 0) : true := by test_rcases_hint "_ | ⟨_, h_ᾰ⟩" 2 example {α} (h : foo α 1) : true := by test_rcases_hint "_ | ⟨_, h_ᾰ⟩" 1 example {α n} (h : foo α n) : true := by test_rcases_hint "_ | ⟨n, h_ᾰ⟩" 2 1 example {α} (V : set α) (h : ∃ p, p ∈ (V.foo V) ∩ (V.foo V)) := by test_rcases_hint "⟨⟨h_w_fst, h_w_snd⟩, ⟨⟩⟩" 0 section rsuffices /-- These next few are duplicated from `rcases/obtain` tests, with the goal order swapped. -/ example : true := begin rsuffices ⟨n : ℕ, h : n = n, -⟩ : ∃ n : ℕ, n = n ∧ true, { guard_hyp n : ℕ, guard_hyp h : n = n, success_if_fail {assumption}, trivial }, { existsi 0, simp }, end example : true := begin rsuffices : ∃ n : ℕ, n = n ∧ true, { trivial }, { existsi 0, simp }, end example : true := begin rsuffices (h : true) | ⟨⟨⟩⟩ : true ∨ false, { guard_hyp h : true, trivial }, { left, trivial }, end example : true := begin success_if_fail {rsuffices ⟨h, h2⟩}, trivial end example (x y : α × β) : true := begin rsuffices ⟨⟨a, b⟩, c, d⟩ : (α × β) × (α × β), { guard_hyp a : α, guard_hyp b : β, guard_hyp c : α, guard_hyp d : β, trivial }, { exact ⟨x, y⟩ } end -- This test demonstrates why `swap` is not used in the implementation of `rsuffices`: -- it would make the _second_ goal the one requiring ⟨x, y⟩, not the last one. example (x y : α ⊕ β) : true := begin rsuffices ⟨a|b, c|d⟩ : (α ⊕ β) × (α ⊕ β), { guard_hyp a : α, guard_hyp c : α, trivial }, { guard_hyp a : α, guard_hyp d : β, trivial }, { guard_hyp b : β, guard_hyp c : α, trivial }, { guard_hyp b : β, guard_hyp d : β, trivial }, exact ⟨x, y⟩, end example {α} (V : set α) (w : true → ∃ p, p ∈ (V.foo V) ∩ (V.foo V)) : true := begin rsuffices ⟨a, h⟩ : ∃ p, p ∈ (V.foo V) ∩ (V.foo V), { trivial }, { exact w trivial }, end -- Now some tests that ensure that things stay in the correct order. -- This test demonstrates why `focus1` is required in the definition of `rsuffices`; otherwise -- the `∃ ...` goal would get put _after_ the `true` goal. example : nonempty ℕ ∧ true := begin split, rsuffices ⟨n : ℕ, hn⟩ : ∃ n, _, { exact ⟨n⟩ }, { exact true }, { exact ⟨0, trivial⟩ }, { trivial }, end section instances example (h : Π {α}, inhabited α) : inhabited (α ⊕ β) := begin rsufficesI (ha | hb) : inhabited α ⊕ inhabited β, { exact ⟨sum.inl default⟩ }, { exact ⟨sum.inr default⟩ }, { exact sum.inl h } end include β -- this test demonstrates that the `resetI` also applies onto the goal. example (h : Π {α}, inhabited α) : inhabited α := begin have : inhabited β := h, rsufficesI t : β, { exact h }, { exact default } end example (h : Π {α}, inhabited α) : β := begin rsufficesI ht : inhabited β, { guard_hyp ht : inhabited β, exact default }, { exact h } end end instances end rsuffices
0083ad97d02e237b6748d60ff16b3e1a50c362d0
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/ring_theory/ideal/over.lean
a0e87d32d8116c7b580abec865a7f625f61eaa51
[ "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
17,339
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import ring_theory.algebraic import ring_theory.localization /-! # Ideals over/under ideals This file concerns ideals lying over other ideals. Let `f : R →+* S` be a ring homomorphism (typically a ring extension), `I` an ideal of `R` and `J` an ideal of `S`. We say `J` lies over `I` (and `I` under `J`) if `I` is the `f`-preimage of `J`. This is expressed here by writing `I = J.comap f`. ## Implementation notes The proofs of the `comap_ne_bot` and `comap_lt_comap` families use an approach specific for their situation: we construct an element in `I.comap f` from the coefficients of a minimal polynomial. Once mathlib has more material on the localization at a prime ideal, the results can be proven using more general going-up/going-down theory. -/ variables {R : Type*} [comm_ring R] namespace ideal open polynomial open submodule section comm_ring variables {S : Type*} [comm_ring S] {f : R →+* S} {I J : ideal S} lemma coeff_zero_mem_comap_of_root_mem_of_eval_mem {r : S} (hr : r ∈ I) {p : polynomial R} (hp : p.eval₂ f r ∈ I) : p.coeff 0 ∈ I.comap f := begin rw [←p.div_X_mul_X_add, eval₂_add, eval₂_C, eval₂_mul, eval₂_X] at hp, refine mem_comap.mpr ((I.add_mem_iff_right _).mp hp), exact I.mul_mem_left _ hr end lemma coeff_zero_mem_comap_of_root_mem {r : S} (hr : r ∈ I) {p : polynomial R} (hp : p.eval₂ f r = 0) : p.coeff 0 ∈ I.comap f := coeff_zero_mem_comap_of_root_mem_of_eval_mem hr (hp.symm ▸ I.zero_mem) lemma exists_coeff_ne_zero_mem_comap_of_non_zero_divisor_root_mem {r : S} (r_non_zero_divisor : ∀ {x}, x * r = 0 → x = 0) (hr : r ∈ I) {p : polynomial R} : ∀ (p_ne_zero : p ≠ 0) (hp : p.eval₂ f r = 0), ∃ i, p.coeff i ≠ 0 ∧ p.coeff i ∈ I.comap f := begin refine p.rec_on_horner _ _ _, { intro h, contradiction }, { intros p a coeff_eq_zero a_ne_zero ih p_ne_zero hp, refine ⟨0, _, coeff_zero_mem_comap_of_root_mem hr hp⟩, simp [coeff_eq_zero, a_ne_zero] }, { intros p p_nonzero ih mul_nonzero hp, rw [eval₂_mul, eval₂_X] at hp, obtain ⟨i, hi, mem⟩ := ih p_nonzero (r_non_zero_divisor hp), refine ⟨i + 1, _, _⟩; simp [hi, mem] } end /-- Let `P` be an ideal in `R[x]`. The map `R[x]/P → (R / (P ∩ R))[x] / (P / (P ∩ R))` is injective. -/ lemma injective_quotient_le_comap_map (P : ideal (polynomial R)) : function.injective ((map (map_ring_hom (quotient.mk (P.comap C))) P).quotient_map (map_ring_hom (quotient.mk (P.comap C))) le_comap_map) := begin refine quotient_map_injective' (le_of_eq _), rw comap_map_of_surjective (map_ring_hom (quotient.mk (P.comap C))) (map_surjective _ quotient.mk_surjective), refine le_antisymm (sup_le le_rfl _) (le_sup_of_le_left le_rfl), refine λ p hp, polynomial_mem_ideal_of_coeff_mem_ideal P p (λ n, quotient.eq_zero_iff_mem.mp _), simpa only [coeff_map, coe_map_ring_hom] using ext_iff.mp (ideal.mem_bot.mp (mem_comap.mp hp)) n, end /-- The identity in this lemma asserts that the "obvious" square ``` R → (R / (P ∩ R)) ↓ ↓ R[x] / P → (R / (P ∩ R))[x] / (P / (P ∩ R)) ``` commutes. It is used, for instance, in the proof of `quotient_mk_comp_C_is_integral_of_jacobson`, in the file `ring_theory/jacobson`. -/ lemma quotient_mk_maps_eq (P : ideal (polynomial R)) : ((quotient.mk (map (map_ring_hom (quotient.mk (P.comap C))) P)).comp C).comp (quotient.mk (P.comap C)) = ((map (map_ring_hom (quotient.mk (P.comap C))) P).quotient_map (map_ring_hom (quotient.mk (P.comap C))) le_comap_map).comp ((quotient.mk P).comp C) := begin refine ring_hom.ext (λ x, _), repeat { rw [ring_hom.coe_comp, function.comp_app] }, rw [quotient_map_mk, coe_map_ring_hom, map_C], end /-- This technical lemma asserts the existence of a polynomial `p` in an ideal `P ⊂ R[x]` that is non-zero in the quotient `R / (P ∩ R) [x]`. The assumptions are equivalent to `P ≠ 0` and `P ∩ R = (0)`. -/ lemma exists_nonzero_mem_of_ne_bot {P : ideal (polynomial R)} (Pb : P ≠ ⊥) (hP : ∀ (x : R), C x ∈ P → x = 0) : ∃ p : polynomial R, p ∈ P ∧ (polynomial.map (quotient.mk (P.comap C)) p) ≠ 0 := begin obtain ⟨m, hm⟩ := submodule.nonzero_mem_of_bot_lt (bot_lt_iff_ne_bot.mpr Pb), refine ⟨m, submodule.coe_mem m, λ pp0, hm (submodule.coe_eq_zero.mp _)⟩, refine (ring_hom.injective_iff (polynomial.map_ring_hom (quotient.mk (P.comap C)))).mp _ _ pp0, refine map_injective _ ((quotient.mk (P.comap C)).injective_iff_ker_eq_bot.mpr _), rw [mk_ker], exact (submodule.eq_bot_iff _).mpr (λ x hx, hP x (mem_comap.mp hx)), end variables {p : ideal R} {P : ideal S} /-- If there is an injective map `R/p → S/P` such that following diagram commutes: ``` R → S ↓ ↓ R/p → S/P ``` then `P` lies over `p`. -/ lemma comap_eq_of_scalar_tower_quotient [algebra R S] [algebra (R ⧸ p) (S ⧸ P)] [is_scalar_tower R (R ⧸ p) (S ⧸ P)] (h : function.injective (algebra_map (R ⧸ p) (S ⧸ P))) : comap (algebra_map R S) P = p := begin ext x, split; rw [mem_comap, ← quotient.eq_zero_iff_mem, ← quotient.eq_zero_iff_mem, quotient.mk_algebra_map, is_scalar_tower.algebra_map_apply _ (R ⧸ p), quotient.algebra_map_eq], { intro hx, exact (algebra_map (R ⧸ p) (S ⧸ P)).injective_iff.mp h _ hx }, { intro hx, rw [hx, ring_hom.map_zero] }, end /-- If `P` lies over `p`, then `R / p` has a canonical map to `S / P`. -/ def quotient.algebra_quotient_of_le_comap (h : p ≤ comap f P) : algebra (R ⧸ p) (S ⧸ P) := ring_hom.to_algebra $ quotient_map _ f h /-- `R / p` has a canonical map to `S / pS`. -/ instance quotient.algebra_quotient_map_quotient : algebra (R ⧸ p) (S ⧸ map f p) := quotient.algebra_quotient_of_le_comap le_comap_map @[simp] lemma quotient.algebra_map_quotient_map_quotient (x : R) : algebra_map (R ⧸ p) (S ⧸ map f p) (quotient.mk p x) = quotient.mk _ (f x) := rfl @[simp] lemma quotient.mk_smul_mk_quotient_map_quotient (x : R) (y : S) : quotient.mk p x • quotient.mk (map f p) y = quotient.mk _ (f x * y) := rfl instance quotient.tower_quotient_map_quotient [algebra R S] : is_scalar_tower R (R ⧸ p) (S ⧸ map (algebra_map R S) p) := is_scalar_tower.of_algebra_map_eq $ λ x, by rw [quotient.algebra_map_eq, quotient.algebra_map_quotient_map_quotient, quotient.mk_algebra_map] end comm_ring section is_domain variables {S : Type*} [comm_ring S] {f : R →+* S} {I J : ideal S} lemma exists_coeff_ne_zero_mem_comap_of_root_mem [is_domain S] {r : S} (r_ne_zero : r ≠ 0) (hr : r ∈ I) {p : polynomial R} : ∀ (p_ne_zero : p ≠ 0) (hp : p.eval₂ f r = 0), ∃ i, p.coeff i ≠ 0 ∧ p.coeff i ∈ I.comap f := exists_coeff_ne_zero_mem_comap_of_non_zero_divisor_root_mem (λ _ h, or.resolve_right (mul_eq_zero.mp h) r_ne_zero) hr lemma exists_coeff_mem_comap_sdiff_comap_of_root_mem_sdiff [is_prime I] (hIJ : I ≤ J) {r : S} (hr : r ∈ (J : set S) \ I) {p : polynomial R} (p_ne_zero : p.map (quotient.mk (I.comap f)) ≠ 0) (hpI : p.eval₂ f r ∈ I) : ∃ i, p.coeff i ∈ (J.comap f : set R) \ (I.comap f) := begin obtain ⟨hrJ, hrI⟩ := hr, have rbar_ne_zero : quotient.mk I r ≠ 0 := mt (quotient.mk_eq_zero I).mp hrI, have rbar_mem_J : quotient.mk I r ∈ J.map (quotient.mk I) := mem_map_of_mem _ hrJ, have quotient_f : ∀ x ∈ I.comap f, (quotient.mk I).comp f x = 0, { simp [quotient.eq_zero_iff_mem] }, have rbar_root : (p.map (quotient.mk (I.comap f))).eval₂ (quotient.lift (I.comap f) _ quotient_f) (quotient.mk I r) = 0, { convert quotient.eq_zero_iff_mem.mpr hpI, exact trans (eval₂_map _ _ _) (hom_eval₂ p f (quotient.mk I) r).symm }, obtain ⟨i, ne_zero, mem⟩ := exists_coeff_ne_zero_mem_comap_of_root_mem rbar_ne_zero rbar_mem_J p_ne_zero rbar_root, rw coeff_map at ne_zero mem, refine ⟨i, (mem_quotient_iff_mem hIJ).mp _, mt _ ne_zero⟩, { simpa using mem }, simp [quotient.eq_zero_iff_mem], end lemma comap_lt_comap_of_root_mem_sdiff [I.is_prime] (hIJ : I ≤ J) {r : S} (hr : r ∈ (J : set S) \ I) {p : polynomial R} (p_ne_zero : p.map (quotient.mk (I.comap f)) ≠ 0) (hp : p.eval₂ f r ∈ I) : I.comap f < J.comap f := let ⟨i, hJ, hI⟩ := exists_coeff_mem_comap_sdiff_comap_of_root_mem_sdiff hIJ hr p_ne_zero hp in set_like.lt_iff_le_and_exists.mpr ⟨comap_mono hIJ, p.coeff i, hJ, hI⟩ lemma mem_of_one_mem (h : (1 : S) ∈ I) (x) : x ∈ I := (I.eq_top_iff_one.mpr h).symm ▸ mem_top lemma comap_lt_comap_of_integral_mem_sdiff [algebra R S] [hI : I.is_prime] (hIJ : I ≤ J) {x : S} (mem : x ∈ (J : set S) \ I) (integral : is_integral R x) : I.comap (algebra_map R S) < J.comap (algebra_map _ _) := begin obtain ⟨p, p_monic, hpx⟩ := integral, refine comap_lt_comap_of_root_mem_sdiff hIJ mem _ _, swap, { apply map_monic_ne_zero p_monic, apply quotient.nontrivial, apply mt comap_eq_top_iff.mp, apply hI.1 }, convert I.zero_mem end lemma comap_ne_bot_of_root_mem [is_domain S] {r : S} (r_ne_zero : r ≠ 0) (hr : r ∈ I) {p : polynomial R} (p_ne_zero : p ≠ 0) (hp : p.eval₂ f r = 0) : I.comap f ≠ ⊥ := λ h, let ⟨i, hi, mem⟩ := exists_coeff_ne_zero_mem_comap_of_root_mem r_ne_zero hr p_ne_zero hp in absurd (mem_bot.mp (eq_bot_iff.mp h mem)) hi lemma is_maximal_of_is_integral_of_is_maximal_comap [algebra R S] (hRS : algebra.is_integral R S) (I : ideal S) [I.is_prime] (hI : is_maximal (I.comap (algebra_map R S))) : is_maximal I := ⟨⟨mt comap_eq_top_iff.mpr hI.1.1, λ J I_lt_J, let ⟨I_le_J, x, hxJ, hxI⟩ := set_like.lt_iff_le_and_exists.mp I_lt_J in comap_eq_top_iff.1 $ hI.1.2 _ (comap_lt_comap_of_integral_mem_sdiff I_le_J ⟨hxJ, hxI⟩ (hRS x))⟩⟩ lemma is_maximal_of_is_integral_of_is_maximal_comap' (f : R →+* S) (hf : f.is_integral) (I : ideal S) [hI' : I.is_prime] (hI : is_maximal (I.comap f)) : is_maximal I := @is_maximal_of_is_integral_of_is_maximal_comap R _ S _ f.to_algebra hf I hI' hI variables [algebra R S] lemma comap_ne_bot_of_algebraic_mem [is_domain S] {x : S} (x_ne_zero : x ≠ 0) (x_mem : x ∈ I) (hx : is_algebraic R x) : I.comap (algebra_map R S) ≠ ⊥ := let ⟨p, p_ne_zero, hp⟩ := hx in comap_ne_bot_of_root_mem x_ne_zero x_mem p_ne_zero hp lemma comap_ne_bot_of_integral_mem [nontrivial R] [is_domain S] {x : S} (x_ne_zero : x ≠ 0) (x_mem : x ∈ I) (hx : is_integral R x) : I.comap (algebra_map R S) ≠ ⊥ := comap_ne_bot_of_algebraic_mem x_ne_zero x_mem (hx.is_algebraic R) lemma eq_bot_of_comap_eq_bot [nontrivial R] [is_domain S] (hRS : algebra.is_integral R S) (hI : I.comap (algebra_map R S) = ⊥) : I = ⊥ := begin refine eq_bot_iff.2 (λ x hx, _), by_cases hx0 : x = 0, { exact hx0.symm ▸ ideal.zero_mem ⊥ }, { exact absurd hI (comap_ne_bot_of_integral_mem hx0 hx (hRS x)) } end lemma is_maximal_comap_of_is_integral_of_is_maximal (hRS : algebra.is_integral R S) (I : ideal S) [hI : I.is_maximal] : is_maximal (I.comap (algebra_map R S)) := begin refine quotient.maximal_of_is_field _ _, haveI : is_prime (I.comap (algebra_map R S)) := comap_is_prime _ _, exact is_field_of_is_integral_of_is_field (is_integral_quotient_of_is_integral hRS) algebra_map_quotient_injective (by rwa ← quotient.maximal_ideal_iff_is_field_quotient), end lemma is_maximal_comap_of_is_integral_of_is_maximal' {R S : Type*} [comm_ring R] [comm_ring S] (f : R →+* S) (hf : f.is_integral) (I : ideal S) (hI : I.is_maximal) : is_maximal (I.comap f) := @is_maximal_comap_of_is_integral_of_is_maximal R _ S _ f.to_algebra hf I hI section is_integral_closure variables (S) {A : Type*} [comm_ring A] variables [algebra R A] [algebra A S] [is_scalar_tower R A S] [is_integral_closure A R S] lemma is_integral_closure.comap_lt_comap {I J : ideal A} [I.is_prime] (I_lt_J : I < J) : I.comap (algebra_map R A) < J.comap (algebra_map _ _) := let ⟨I_le_J, x, hxJ, hxI⟩ := set_like.lt_iff_le_and_exists.mp I_lt_J in comap_lt_comap_of_integral_mem_sdiff I_le_J ⟨hxJ, hxI⟩ (is_integral_closure.is_integral R S x) lemma is_integral_closure.is_maximal_of_is_maximal_comap (I : ideal A) [I.is_prime] (hI : is_maximal (I.comap (algebra_map R A))) : is_maximal I := is_maximal_of_is_integral_of_is_maximal_comap (λ x, is_integral_closure.is_integral R S x) I hI variables [is_domain A] lemma is_integral_closure.comap_ne_bot [nontrivial R] {I : ideal A} (I_ne_bot : I ≠ ⊥) : I.comap (algebra_map R A) ≠ ⊥ := let ⟨x, x_mem, x_ne_zero⟩ := I.ne_bot_iff.mp I_ne_bot in comap_ne_bot_of_integral_mem x_ne_zero x_mem (is_integral_closure.is_integral R S x) lemma is_integral_closure.eq_bot_of_comap_eq_bot [nontrivial R] {I : ideal A} : I.comap (algebra_map R A) = ⊥ → I = ⊥ := imp_of_not_imp_not _ _ (is_integral_closure.comap_ne_bot S) end is_integral_closure lemma integral_closure.comap_lt_comap {I J : ideal (integral_closure R S)} [I.is_prime] (I_lt_J : I < J) : I.comap (algebra_map R (integral_closure R S)) < J.comap (algebra_map _ _) := is_integral_closure.comap_lt_comap S I_lt_J lemma integral_closure.is_maximal_of_is_maximal_comap (I : ideal (integral_closure R S)) [I.is_prime] (hI : is_maximal (I.comap (algebra_map R (integral_closure R S)))) : is_maximal I := is_integral_closure.is_maximal_of_is_maximal_comap S I hI section variables [is_domain S] lemma integral_closure.comap_ne_bot [nontrivial R] {I : ideal (integral_closure R S)} (I_ne_bot : I ≠ ⊥) : I.comap (algebra_map R (integral_closure R S)) ≠ ⊥ := is_integral_closure.comap_ne_bot S I_ne_bot lemma integral_closure.eq_bot_of_comap_eq_bot [nontrivial R] {I : ideal (integral_closure R S)} : I.comap (algebra_map R (integral_closure R S)) = ⊥ → I = ⊥ := is_integral_closure.eq_bot_of_comap_eq_bot S /-- `comap (algebra_map R S)` is a surjection from the prime spec of `R` to prime spec of `S`. `hP : (algebra_map R S).ker ≤ P` is a slight generalization of the extension being injective -/ lemma exists_ideal_over_prime_of_is_integral' (H : algebra.is_integral R S) (P : ideal R) [is_prime P] (hP : (algebra_map R S).ker ≤ P) : ∃ (Q : ideal S), is_prime Q ∧ Q.comap (algebra_map R S) = P := begin have hP0 : (0 : S) ∉ algebra.algebra_map_submonoid S P.prime_compl, { rintro ⟨x, ⟨hx, x0⟩⟩, exact absurd (hP x0) hx }, let Rₚ := localization P.prime_compl, let Sₚ := localization (algebra.algebra_map_submonoid S P.prime_compl), letI : is_domain (localization (algebra.algebra_map_submonoid S P.prime_compl)) := is_localization.is_domain_localization (le_non_zero_divisors_of_no_zero_divisors hP0), obtain ⟨Qₚ : ideal Sₚ, Qₚ_maximal⟩ := exists_maximal Sₚ, haveI Qₚ_max : is_maximal (comap _ Qₚ) := @is_maximal_comap_of_is_integral_of_is_maximal Rₚ _ Sₚ _ (localization_algebra P.prime_compl S) (is_integral_localization H) _ Qₚ_maximal, refine ⟨comap (algebra_map S Sₚ) Qₚ, ⟨comap_is_prime _ Qₚ, _⟩⟩, convert localization.at_prime.comap_maximal_ideal, rw [comap_comap, ← local_ring.eq_maximal_ideal Qₚ_max, ← is_localization.map_comp _], refl end end /-- More general going-up theorem than `exists_ideal_over_prime_of_is_integral'`. TODO: Version of going-up theorem with arbitrary length chains (by induction on this)? Not sure how best to write an ascending chain in Lean -/ theorem exists_ideal_over_prime_of_is_integral (H : algebra.is_integral R S) (P : ideal R) [is_prime P] (I : ideal S) [is_prime I] (hIP : I.comap (algebra_map R S) ≤ P) : ∃ Q ≥ I, is_prime Q ∧ Q.comap (algebra_map R S) = P := begin obtain ⟨Q' : ideal (S ⧸ I), ⟨Q'_prime, hQ'⟩⟩ := @exists_ideal_over_prime_of_is_integral' (R ⧸ I.comap (algebra_map R S)) _ (S ⧸ I) _ ideal.quotient_algebra _ (is_integral_quotient_of_is_integral H) (map (quotient.mk (I.comap (algebra_map R S))) P) (map_is_prime_of_surjective quotient.mk_surjective (by simp [hIP])) (le_trans (le_of_eq ((ring_hom.injective_iff_ker_eq_bot _).1 algebra_map_quotient_injective)) bot_le), haveI := Q'_prime, refine ⟨Q'.comap _, le_trans (le_of_eq mk_ker.symm) (ker_le_comap _), ⟨comap_is_prime _ Q', _⟩⟩, rw comap_comap, refine trans _ (trans (congr_arg (comap (quotient.mk (comap (algebra_map R S) I))) hQ') _), { simpa [comap_comap] }, { refine trans (comap_map_of_surjective _ quotient.mk_surjective _) (sup_eq_left.2 _), simpa [← ring_hom.ker_eq_comap_bot] using hIP}, end /-- `comap (algebra_map R S)` is a surjection from the max spec of `S` to max spec of `R`. `hP : (algebra_map R S).ker ≤ P` is a slight generalization of the extension being injective -/ lemma exists_ideal_over_maximal_of_is_integral [is_domain S] (H : algebra.is_integral R S) (P : ideal R) [P_max : is_maximal P] (hP : (algebra_map R S).ker ≤ P) : ∃ (Q : ideal S), is_maximal Q ∧ Q.comap (algebra_map R S) = P := begin obtain ⟨Q, ⟨Q_prime, hQ⟩⟩ := exists_ideal_over_prime_of_is_integral' H P hP, haveI : Q.is_prime := Q_prime, exact ⟨Q, is_maximal_of_is_integral_of_is_maximal_comap H _ (hQ.symm ▸ P_max), hQ⟩, end end is_domain end ideal
9ae495438aa407cf95a14a45b30f735406d56cbf
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/mv_polynomial/cardinal.lean
9ae2103150290c71b1d9ceaaab23f2b62b5d848a
[ "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
2,142
lean
/- Copyright (c) 2021 Chris Hughes, Junyan Xu. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Junyan Xu -/ import data.mv_polynomial.equiv import set_theory.cardinal.ordinal /-! # Cardinality of Multivariate Polynomial Ring The main result in this file is `mv_polynomial.cardinal_mk_le_max`, which says that the cardinality of `mv_polynomial σ R` is bounded above by the maximum of `#R`, `#σ` and `ℵ₀`. -/ universes u v open cardinal open_locale cardinal namespace mv_polynomial section two_universes variables {σ : Type u} {R : Type v} [comm_semiring R] @[simp] lemma cardinal_mk_eq_max_lift [nonempty σ] [nontrivial R] : #(mv_polynomial σ R) = max (max (cardinal.lift.{u} $ #R) $ cardinal.lift.{v} $ #σ) ℵ₀ := begin haveI : infinite (σ →₀ ℕ) := infinite_iff.2 ((le_max_right _ _).trans (mk_finsupp_nat σ).ge), refine (mk_finsupp_lift_of_infinite _ R).trans _, rw [mk_finsupp_nat, max_assoc, lift_max, lift_aleph_0, max_comm], end @[simp] lemma cardinal_mk_eq_lift [is_empty σ] : #(mv_polynomial σ R) = cardinal.lift.{u} (#R) := ((is_empty_ring_equiv R σ).to_equiv.trans equiv.ulift.{u}.symm).cardinal_eq lemma cardinal_lift_mk_le_max {σ : Type u} {R : Type v} [comm_semiring R] : #(mv_polynomial σ R) ≤ max (max (cardinal.lift.{u} $ #R) $ cardinal.lift.{v} $ #σ) ℵ₀ := begin casesI subsingleton_or_nontrivial R, { exact (mk_eq_one _).trans_le (le_max_of_le_right one_le_aleph_0) }, casesI is_empty_or_nonempty σ, { exact cardinal_mk_eq_lift.trans_le (le_max_of_le_left $ le_max_left _ _) }, { exact cardinal_mk_eq_max_lift.le }, end end two_universes variables {σ R : Type u} [comm_semiring R] lemma cardinal_mk_eq_max [nonempty σ] [nontrivial R] : #(mv_polynomial σ R) = max (max (#R) (#σ)) ℵ₀ := by simp /-- The cardinality of the multivariate polynomial ring, `mv_polynomial σ R` is at most the maximum of `#R`, `#σ` and `ℵ₀` -/ lemma cardinal_mk_le_max : #(mv_polynomial σ R) ≤ max (max (#R) (#σ)) ℵ₀ := cardinal_lift_mk_le_max.trans $ by rw [lift_id, lift_id] end mv_polynomial
638053129e5e4c56cb63ae45379af06e8ab2b2d7
acc85b4be2c618b11fc7cb3005521ae6858a8d07
/logic/function.lean
e782dc9fd404e72399049d96115a7f1927551294
[ "Apache-2.0" ]
permissive
linpingchuan/mathlib
d49990b236574df2a45d9919ba43c923f693d341
5ad8020f67eb13896a41cc7691d072c9331b1f76
refs/heads/master
1,626,019,377,808
1,508,048,784,000
1,508,048,784,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,512
lean
/- Copyright (c) 2016 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro Miscellaneous function constructions and lemmas. -/ import logic.basic universes u v variables {α : Type u} {β : Type v} {f : α → β} namespace function @[simp] theorem injective.eq_iff (I : injective f) {a b : α} : f a = f b ↔ a = b := ⟨@I _ _, congr_arg f⟩ local attribute [instance] classical.decidable_inhabited classical.prop_decidable noncomputable def partial_inv (f : α → β) (b : β) : option α := if h : ∃ a, f a = b then some (classical.some h) else none theorem partial_inv_eq {f : α → β} (I : injective f) (a : α) : (partial_inv f (f a)) = some a := have h : ∃ a', f a' = f a, from ⟨_, rfl⟩, (dif_pos h).trans (congr_arg _ (I $ classical.some_spec h)) theorem partial_inv_eq_of_eq {f : α → β} (I : injective f) {b : β} {a : α} (h : partial_inv f b = some a) : f a = b := by by_cases (∃ a, f a = b) with h'; simp [partial_inv, h'] at h; injection h with h; subst h; apply classical.some_spec h' variables {s : set α} {a : α} {b : β} section inv_fun variable [inhabited α] noncomputable def inv_fun_on (f : α → β) (s : set α) (b : β) : α := if h : ∃a, a ∈ s ∧ f a = b then classical.some h else default α theorem inv_fun_on_pos (h : ∃a∈s, f a = b) : inv_fun_on f s b ∈ s ∧ f (inv_fun_on f s b) = b := by rw [bex_def] at h; rw [inv_fun_on, dif_pos h]; exact classical.some_spec h theorem inv_fun_on_mem (h : ∃a∈s, f a = b) : inv_fun_on f s b ∈ s := (inv_fun_on_pos h).left theorem inv_fun_on_eq (h : ∃a∈s, f a = b) : f (inv_fun_on f s b) = b := (inv_fun_on_pos h).right theorem inv_fun_on_eq' (h : ∀x∈s, ∀y∈s, f x = f y → x = y) (ha : a ∈ s) : inv_fun_on f s (f a) = a := have ∃a'∈s, f a' = f a, from ⟨a, ha, rfl⟩, h _ (inv_fun_on_mem this) _ ha (inv_fun_on_eq this) theorem inv_fun_on_neg (h : ¬ ∃a∈s, f a = b) : inv_fun_on f s b = default α := by rw [bex_def] at h; rw [inv_fun_on, dif_neg h] noncomputable def inv_fun (f : α → β) : β → α := inv_fun_on f set.univ theorem inv_fun_eq (h : ∃a, f a = b) : f (inv_fun f b) = b := inv_fun_on_eq $ let ⟨a, ha⟩ := h in ⟨a, trivial, ha⟩ theorem inv_fun_eq_of_injective_of_right_inverse {g : β → α} (hf : injective f) (hg : right_inverse g f) : inv_fun f = g := funext $ assume b, hf begin rw [hg b], exact inv_fun_eq ⟨g b, hg b⟩ end lemma right_inverse_inv_fun (hf : surjective f) : right_inverse (inv_fun f) f := assume b, inv_fun_eq $ hf b lemma left_inverse_inv_fun (hf : injective f) : left_inverse (inv_fun f) f := assume b, have f (inv_fun f (f b)) = f b, from inv_fun_eq ⟨b, rfl⟩, hf this lemma injective.has_left_inverse (hf : injective f) : has_left_inverse f := ⟨inv_fun f, left_inverse_inv_fun hf⟩ end inv_fun section surj_inv noncomputable def surj_inv {f : α → β} (h : surjective f) (b : β) : α := classical.some (h b) lemma surj_inv_eq (h : surjective f) : f (surj_inv h b) = b := classical.some_spec (h b) lemma right_inverse_surj_inv (hf : surjective f) : right_inverse (surj_inv hf) f := assume b, surj_inv_eq hf lemma surjective.has_right_inverse (hf : surjective f) : has_right_inverse f := ⟨_, right_inverse_surj_inv hf⟩ lemma injective_surj_inv (h : surjective f) : injective (surj_inv h) := injective_of_has_left_inverse ⟨f, right_inverse_surj_inv h⟩ end surj_inv end function
1d98e30514d7e293f575a5ff8eec8bca37423c34
f3a5af2927397cf346ec0e24312bfff077f00425
/src/game/world10/level9.lean
7643b61ea226766226d4e47bb6135c0e0a3e1b8b
[ "Apache-2.0" ]
permissive
ImperialCollegeLondon/natural_number_game
05c39e1586408cfb563d1a12e1085a90726ab655
f29b6c2884299fc63fdfc81ae5d7daaa3219f9fd
refs/heads/master
1,688,570,964,990
1,636,908,242,000
1,636,908,242,000
195,403,790
277
84
Apache-2.0
1,694,547,955,000
1,562,328,792,000
Lean
UTF-8
Lean
false
false
631
lean
import game.world10.level8 -- hide namespace mynat -- hide /- # Inequality world. ## Level 9: `le_total` -/ /- Lemma For all naturals $a$ and $b$, either $a\le b$ or $b\le a$. -/ theorem le_total (a b : mynat) : a ≤ b ∨ b ≤ a := begin [nat_num_game] revert a, induction b with d hd, intro a, right, exact zero_le a, intro a, cases a with a, left, exact zero_le _, cases hd a, left, exact succ_le_succ a d h, right, exact succ_le_succ d a h, end -- Another collectible: the naturals are a linear order. instance : linear_order mynat := by structure_helper end mynat -- hide
b3b06e50ffc0430694968b93fbba735b6e065971
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/src/Std/Data/PersistentHashMap.lean
85bbbb98d98b73f1f6c19b368d6ebc25597011f4
[ "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
13,369
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 -/ namespace Std universe u v w w' namespace PersistentHashMap inductive Entry (α : Type u) (β : Type v) (σ : Type w) where | entry (key : α) (val : β) : Entry α β σ | ref (node : σ) : Entry α β σ | null : Entry α β σ instance {α β σ} : Inhabited (Entry α β σ) := ⟨Entry.null⟩ inductive Node (α : Type u) (β : Type v) : Type (max u v) where | entries (es : Array (Entry α β (Node α β))) : Node α β | collision (ks : Array α) (vs : Array β) (h : ks.size = vs.size) : Node α β instance {α β} : Inhabited (Node α β) := ⟨Node.entries #[]⟩ abbrev shift : USize := 5 abbrev branching : USize := USize.ofNat (2 ^ shift.toNat) abbrev maxDepth : USize := 7 abbrev maxCollisions : Nat := 4 def mkEmptyEntriesArray {α β} : Array (Entry α β (Node α β)) := (Array.mkArray PersistentHashMap.branching.toNat PersistentHashMap.Entry.null) end PersistentHashMap structure PersistentHashMap (α : Type u) (β : Type v) [BEq α] [Hashable α] where root : PersistentHashMap.Node α β := PersistentHashMap.Node.entries PersistentHashMap.mkEmptyEntriesArray size : Nat := 0 abbrev PHashMap (α : Type u) (β : Type v) [BEq α] [Hashable α] := PersistentHashMap α β namespace PersistentHashMap variable {α : Type u} {β : Type v} def empty [BEq α] [Hashable α] : PersistentHashMap α β := {} def isEmpty [BEq α] [Hashable α] (m : PersistentHashMap α β) : Bool := m.size == 0 instance [BEq α] [Hashable α] : Inhabited (PersistentHashMap α β) := ⟨{}⟩ def mkEmptyEntries {α β} : Node α β := Node.entries mkEmptyEntriesArray abbrev mul2Shift (i : USize) (shift : USize) : USize := i.shiftLeft shift abbrev div2Shift (i : USize) (shift : USize) : USize := i.shiftRight shift abbrev mod2Shift (i : USize) (shift : USize) : USize := USize.land i ((USize.shiftLeft 1 shift) - 1) inductive IsCollisionNode : Node α β → Prop where | mk (keys : Array α) (vals : Array β) (h : keys.size = vals.size) : IsCollisionNode (Node.collision keys vals h) abbrev CollisionNode (α β) := { n : Node α β // IsCollisionNode n } inductive IsEntriesNode : Node α β → Prop where | mk (entries : Array (Entry α β (Node α β))) : IsEntriesNode (Node.entries entries) abbrev EntriesNode (α β) := { n : Node α β // IsEntriesNode n } private theorem size_set {ks : Array α} {vs : Array β} (h : ks.size = vs.size) (i : Fin ks.size) (j : Fin vs.size) (k : α) (v : β) : (ks.set i k).size = (vs.set j v).size := by simp [h] private theorem size_push {ks : Array α} {vs : Array β} (h : ks.size = vs.size) (k : α) (v : β) : (ks.push k).size = (vs.push v).size := by simp [h] partial def insertAtCollisionNodeAux [BEq α] : CollisionNode α β → Nat → α → β → CollisionNode α β | n@⟨Node.collision keys vals heq, _⟩, i, k, v => if h : i < keys.size then let idx : Fin keys.size := ⟨i, h⟩; let k' := keys.get idx; if k == k' then let j : Fin vals.size := ⟨i, by rw [←heq]; assumption⟩ ⟨Node.collision (keys.set idx k) (vals.set j v) (size_set heq idx j k v), IsCollisionNode.mk _ _ _⟩ else insertAtCollisionNodeAux n (i+1) k v else ⟨Node.collision (keys.push k) (vals.push v) (size_push heq k v), IsCollisionNode.mk _ _ _⟩ | ⟨Node.entries _, h⟩, _, _, _ => False.elim (nomatch h) def insertAtCollisionNode [BEq α] : CollisionNode α β → α → β → CollisionNode α β := fun n k v => insertAtCollisionNodeAux n 0 k v def getCollisionNodeSize : CollisionNode α β → Nat | ⟨Node.collision keys _ _, _⟩ => keys.size | ⟨Node.entries _, h⟩ => False.elim (nomatch h) def mkCollisionNode (k₁ : α) (v₁ : β) (k₂ : α) (v₂ : β) : Node α β := let ks : Array α := Array.mkEmpty maxCollisions let ks := (ks.push k₁).push k₂ let vs : Array β := Array.mkEmpty maxCollisions let vs := (vs.push v₁).push v₂ Node.collision ks vs rfl partial def insertAux [BEq α] [Hashable α] : Node α β → USize → USize → α → β → Node α β | Node.collision keys vals heq, _, depth, k, v => let newNode := insertAtCollisionNode ⟨Node.collision keys vals heq, IsCollisionNode.mk _ _ _⟩ k v if depth >= maxDepth || getCollisionNodeSize newNode < maxCollisions then newNode.val else match newNode with | ⟨Node.entries _, h⟩ => False.elim (nomatch h) | ⟨Node.collision keys vals heq, _⟩ => let rec traverse (i : Nat) (entries : Node α β) : Node α β := if h : i < keys.size then let k := keys.get ⟨i, h⟩ let v := vals.get ⟨i, heq ▸ h⟩ let h := hash k |>.toUSize let h := div2Shift h (shift * (depth - 1)) traverse (i+1) (insertAux entries h depth k v) else entries traverse 0 mkEmptyEntries | Node.entries entries, h, depth, k, v => let j := (mod2Shift h shift).toNat Node.entries $ entries.modify j fun entry => match entry with | Entry.null => Entry.entry k v | Entry.ref node => Entry.ref $ insertAux node (div2Shift h shift) (depth+1) k v | Entry.entry k' v' => if k == k' then Entry.entry k v else Entry.ref $ mkCollisionNode k' v' k v def insert [BEq α] [Hashable α] : PersistentHashMap α β → α → β → PersistentHashMap α β | { root := n, size := sz }, k, v => { root := insertAux n (hash k |>.toUSize) 1 k v, size := sz + 1 } partial def findAtAux [BEq α] (keys : Array α) (vals : Array β) (heq : keys.size = vals.size) (i : Nat) (k : α) : Option β := if h : i < keys.size then let k' := keys.get ⟨i, h⟩ if k == k' then some (vals.get ⟨i, by rw [←heq]; assumption⟩) else findAtAux keys vals heq (i+1) k else none partial def findAux [BEq α] : Node α β → USize → α → Option β | Node.entries entries, h, k => let j := (mod2Shift h shift).toNat match entries.get! j with | Entry.null => none | Entry.ref node => findAux node (div2Shift h shift) k | Entry.entry k' v => if k == k' then some v else none | Node.collision keys vals heq, _, k => findAtAux keys vals heq 0 k def find? [BEq α] [Hashable α] : PersistentHashMap α β → α → Option β | { root := n, .. }, k => findAux n (hash k |>.toUSize) k @[inline] def getOp [BEq α] [Hashable α] (self : PersistentHashMap α β) (idx : α) : Option β := self.find? idx @[inline] def findD [BEq α] [Hashable α] (m : PersistentHashMap α β) (a : α) (b₀ : β) : β := (m.find? a).getD b₀ @[inline] def find! [BEq α] [Hashable α] [Inhabited β] (m : PersistentHashMap α β) (a : α) : β := match m.find? a with | some b => b | none => panic! "key is not in the map" partial def findEntryAtAux [BEq α] (keys : Array α) (vals : Array β) (heq : keys.size = vals.size) (i : Nat) (k : α) : Option (α × β) := if h : i < keys.size then let k' := keys.get ⟨i, h⟩ if k == k' then some (k', vals.get ⟨i, by rw [←heq]; assumption⟩) else findEntryAtAux keys vals heq (i+1) k else none partial def findEntryAux [BEq α] : Node α β → USize → α → Option (α × β) | Node.entries entries, h, k => let j := (mod2Shift h shift).toNat match entries.get! j with | Entry.null => none | Entry.ref node => findEntryAux node (div2Shift h shift) k | Entry.entry k' v => if k == k' then some (k', v) else none | Node.collision keys vals heq, _, k => findEntryAtAux keys vals heq 0 k def findEntry? [BEq α] [Hashable α] : PersistentHashMap α β → α → Option (α × β) | { root := n, .. }, k => findEntryAux n (hash k |>.toUSize) k partial def containsAtAux [BEq α] (keys : Array α) (vals : Array β) (heq : keys.size = vals.size) (i : Nat) (k : α) : Bool := if h : i < keys.size then let k' := keys.get ⟨i, h⟩ if k == k' then true else containsAtAux keys vals heq (i+1) k else false partial def containsAux [BEq α] : Node α β → USize → α → Bool | Node.entries entries, h, k => let j := (mod2Shift h shift).toNat match entries.get! j with | Entry.null => false | Entry.ref node => containsAux node (div2Shift h shift) k | Entry.entry k' v => k == k' | Node.collision keys vals heq, _, k => containsAtAux keys vals heq 0 k def contains [BEq α] [Hashable α] : PersistentHashMap α β → α → Bool | { root := n, .. }, k => containsAux n (hash k |>.toUSize) k partial def isUnaryEntries (a : Array (Entry α β (Node α β))) (i : Nat) (acc : Option (α × β)) : Option (α × β) := if h : i < a.size then match a.get ⟨i, h⟩ with | Entry.null => isUnaryEntries a (i+1) acc | Entry.ref _ => none | Entry.entry k v => match acc with | none => isUnaryEntries a (i+1) (some (k, v)) | some _ => none else acc def isUnaryNode : Node α β → Option (α × β) | Node.entries entries => isUnaryEntries entries 0 none | Node.collision keys vals heq => if h : 1 = keys.size then have : 0 < keys.size := by rw [←h]; decide some (keys.get ⟨0, this⟩, vals.get ⟨0, by rw [←heq]; assumption⟩) else none partial def eraseAux [BEq α] : Node α β → USize → α → Node α β × Bool | n@(Node.collision keys vals heq), _, k => match keys.indexOf? k with | some idx => let ⟨keys', keq⟩ := keys.eraseIdx' idx let ⟨vals', veq⟩ := vals.eraseIdx' (Eq.ndrec idx heq) have : keys.size - 1 = vals.size - 1 := by rw [heq] (Node.collision keys' vals' (keq.trans (this.trans veq.symm)), true) | none => (n, false) | n@(Node.entries entries), h, k => let j := (mod2Shift h shift).toNat let entry := entries.get! j match entry with | Entry.null => (n, false) | Entry.entry k' v => if k == k' then (Node.entries (entries.set! j Entry.null), true) else (n, false) | Entry.ref node => let entries := entries.set! j Entry.null let (newNode, deleted) := eraseAux node (div2Shift h shift) k if !deleted then (n, false) else match isUnaryNode newNode with | none => (Node.entries (entries.set! j (Entry.ref newNode)), true) | some (k, v) => (Node.entries (entries.set! j (Entry.entry k v)), true) def erase [BEq α] [Hashable α] : PersistentHashMap α β → α → PersistentHashMap α β | { root := n, size := sz }, k => let h := hash k |>.toUSize let (n, del) := eraseAux n h k { root := n, size := if del then sz - 1 else sz } section variable {m : Type w → Type w'} [Monad m] variable {σ : Type w} @[specialize] partial def foldlMAux (f : σ → α → β → m σ) : Node α β → σ → m σ | Node.collision keys vals heq, acc => let rec traverse (i : Nat) (acc : σ) : m σ := do if h : i < keys.size then let k := keys.get ⟨i, h⟩ let v := vals.get ⟨i, heq ▸ h⟩ traverse (i+1) (← f acc k v) else pure acc traverse 0 acc | Node.entries entries, acc => entries.foldlM (fun acc entry => match entry with | Entry.null => pure acc | Entry.entry k v => f acc k v | Entry.ref node => foldlMAux f node acc) acc @[specialize] def foldlM [BEq α] [Hashable α] (map : PersistentHashMap α β) (f : σ → α → β → m σ) (init : σ) : m σ := foldlMAux f map.root init @[specialize] def forM [BEq α] [Hashable α] (map : PersistentHashMap α β) (f : α → β → m PUnit) : m PUnit := map.foldlM (fun _ => f) ⟨⟩ @[specialize] def foldl [BEq α] [Hashable α] (map : PersistentHashMap α β) (f : σ → α → β → σ) (init : σ) : σ := Id.run $ map.foldlM f init end def toList [BEq α] [Hashable α] (m : PersistentHashMap α β) : List (α × β) := m.foldl (init := []) fun ps k v => (k, v) :: ps structure Stats where numNodes : Nat := 0 numNull : Nat := 0 numCollisions : Nat := 0 maxDepth : Nat := 0 partial def collectStats : Node α β → Stats → Nat → Stats | Node.collision keys _ _, stats, depth => { stats with numNodes := stats.numNodes + 1, numCollisions := stats.numCollisions + keys.size - 1, maxDepth := Nat.max stats.maxDepth depth } | Node.entries entries, stats, depth => let stats := { stats with numNodes := stats.numNodes + 1, maxDepth := Nat.max stats.maxDepth depth } entries.foldl (fun stats entry => match entry with | Entry.null => { stats with numNull := stats.numNull + 1 } | Entry.ref node => collectStats node stats (depth + 1) | Entry.entry _ _ => stats) stats def stats [BEq α] [Hashable α] (m : PersistentHashMap α β) : Stats := collectStats m.root {} 1 def Stats.toString (s : Stats) : String := s!"\{ nodes := {s.numNodes}, null := {s.numNull}, collisions := {s.numCollisions}, depth := {s.maxDepth}}" instance : ToString Stats := ⟨Stats.toString⟩ end PersistentHashMap end Std
e79e4501db137876880e774623e8b63c868d960e
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/order/lattice_intervals.lean
cae0393181ef7dfd4b492d8dfbfdcae914b0b76e
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,806
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import order.bounded_lattice import data.set.intervals.basic /-! # Intervals in Lattices In this file, we provide instances of lattice structures on intervals within lattices. Some of them depend on the order of the endpoints of the interval, and thus are not made global instances. These are probably not all of the lattice instances that could be placed on these intervals, but more can be added easily along the same lines when needed. ## Main definitions In the following, `*` can represent either `c`, `o`, or `i`. * `set.Ic*.semilattice_inf_bot` * `set.Ii*.semillatice_inf` * `set.I*c.semilattice_sup_top` * `set.I*c.semillatice_inf` * `set.Iic.bounded_lattice`, within a `bounded_lattice` * `set.Ici.bounded_lattice`, within a `bounded_lattice` -/ variable {α : Type*} namespace set namespace Ico variables {a b : α} instance [semilattice_inf α] : semilattice_inf (Ico a b) := subtype.semilattice_inf (λ x y hx hy, ⟨le_inf hx.1 hy.1, lt_of_le_of_lt inf_le_left hx.2⟩) /-- `Ico a b` has a bottom element whenever `a < b`. -/ def order_bot [partial_order α] (h : a < b) : order_bot (Ico a b) := { bot := ⟨a, ⟨le_refl a, h⟩⟩, bot_le := λ x, x.prop.1, .. (subtype.partial_order _) } /-- `Ico a b` is a `semilattice_inf_bot` whenever `a < b`. -/ def semilattice_inf_bot [semilattice_inf α] (h : a < b) : semilattice_inf_bot (Ico a b) := { .. (Ico.semilattice_inf), .. (Ico.order_bot h) } end Ico namespace Iio instance [semilattice_inf α] {a : α} : semilattice_inf (Iio a) := subtype.semilattice_inf (λ x y hx hy, lt_of_le_of_lt inf_le_left hx) end Iio namespace Ioc variables {a b : α} instance [semilattice_sup α] : semilattice_sup (Ioc a b) := subtype.semilattice_sup (λ x y hx hy, ⟨lt_of_lt_of_le hx.1 le_sup_left, sup_le hx.2 hy.2⟩) /-- `Ioc a b` has a top element whenever `a < b`. -/ def order_top [partial_order α] (h : a < b) : order_top (Ioc a b) := { top := ⟨b, ⟨h, le_refl b⟩⟩, le_top := λ x, x.prop.2, .. (subtype.partial_order _) } /-- `Ioc a b` is a `semilattice_sup_top` whenever `a < b`. -/ def semilattice_sup_top [semilattice_sup α] (h : a < b) : semilattice_sup_top (Ioc a b) := { .. (Ioc.semilattice_sup), .. (Ioc.order_top h) } end Ioc namespace Iio instance [semilattice_sup α] {a : α} : semilattice_sup (Ioi a) := subtype.semilattice_sup (λ x y hx hy, lt_of_lt_of_le hx le_sup_left) end Iio namespace Iic variables {a : α} instance [semilattice_inf α] : semilattice_inf (Iic a) := subtype.semilattice_inf (λ x y hx hy, le_trans inf_le_left hx) instance [semilattice_sup α] : semilattice_sup (Iic a) := subtype.semilattice_sup (λ x y hx hy, sup_le hx hy) instance [lattice α] : lattice (Iic a) := { .. (Iic.semilattice_inf), .. (Iic.semilattice_sup) } instance [partial_order α] : order_top (Iic a) := { top := ⟨a, le_refl a⟩, le_top := λ x, x.prop, .. (subtype.partial_order _) } @[simp] lemma coe_top [partial_order α] {a : α} : ↑(⊤ : Iic a) = a := rfl instance [semilattice_inf α] : semilattice_inf_top (Iic a) := { .. (Iic.semilattice_inf), .. (Iic.order_top) } instance [semilattice_sup α] : semilattice_sup_top (Iic a) := { .. (Iic.semilattice_sup), .. (Iic.order_top) } instance [preorder α] [order_bot α] : order_bot (Iic a) := { bot := ⟨⊥, bot_le⟩, bot_le := λ ⟨_,_⟩, subtype.mk_le_mk.2 bot_le } @[simp] lemma coe_bot [preorder α] [order_bot α] {a : α} : ↑(⊥ : Iic a) = (⊥ : α) := rfl instance [partial_order α] [no_bot_order α] {a : α} : no_bot_order (Iic a) := ⟨λ x, let ⟨y, hy⟩ := no_bot x.1 in ⟨⟨y, le_trans hy.le x.2⟩, hy⟩ ⟩ instance [semilattice_inf_bot α] : semilattice_inf_bot (Iic a) := { .. (Iic.semilattice_inf), .. (Iic.order_bot) } instance [semilattice_sup_bot α] : semilattice_sup_bot (Iic a) := { .. (Iic.semilattice_sup), .. (Iic.order_bot) } instance [bounded_lattice α] : bounded_lattice (Iic a) := { .. (Iic.order_top), .. (Iic.order_bot), .. (Iic.lattice) } end Iic namespace Ici variables {a : α} instance [semilattice_inf α] : semilattice_inf (Ici a) := subtype.semilattice_inf (λ x y hx hy, le_inf hx hy) instance [semilattice_sup α] : semilattice_sup (Ici a) := subtype.semilattice_sup (λ x y hx hy, le_trans hx le_sup_left) instance [lattice α] : lattice (Ici a) := { .. (Ici.semilattice_inf), .. (Ici.semilattice_sup) } instance [preorder α] : order_bot (Ici a) := { bot := ⟨a, le_refl a⟩, bot_le := λ x, x.prop } @[simp] lemma coe_bot [partial_order α] {a : α} : ↑(⊥ : Ici a) = a := rfl instance [semilattice_inf α] : semilattice_inf_bot (Ici a) := { .. (Ici.semilattice_inf), .. (Ici.order_bot) } instance [semilattice_sup α] : semilattice_sup_bot (Ici a) := { .. (Ici.semilattice_sup), .. (Ici.order_bot) } instance [preorder α] [order_top α] : order_top (Ici a) := { top := ⟨⊤, le_top⟩, le_top := λ ⟨_,_⟩, subtype.mk_le_mk.2 le_top } @[simp] lemma coe_top [preorder α] [order_top α] {a : α} : ↑(⊤ : Ici a) = (⊤ : α) := rfl instance [partial_order α] [no_top_order α] {a : α} : no_top_order (Ici a) := ⟨λ x, let ⟨y, hy⟩ := no_top x.1 in ⟨⟨y, le_trans x.2 hy.le⟩, hy⟩ ⟩ instance [semilattice_sup_top α] : semilattice_sup_top (Ici a) := { .. (Ici.semilattice_sup), .. (Ici.order_top) } instance [semilattice_inf_top α] : semilattice_inf_top (Ici a) := { .. (Ici.semilattice_inf), .. (Ici.order_top) } instance [bounded_lattice α] : bounded_lattice (Ici a) := { .. (Ici.order_top), .. (Ici.order_bot), .. (Ici.lattice) } end Ici namespace Icc instance [semilattice_inf α] {a b : α} : semilattice_inf (Icc a b) := subtype.semilattice_inf (λ x y hx hy, ⟨le_inf hx.1 hy.1, le_trans inf_le_left hx.2⟩) instance [semilattice_sup α] {a b : α} : semilattice_sup (Icc a b) := subtype.semilattice_sup (λ x y hx hy, ⟨le_trans hx.1 le_sup_left, sup_le hx.2 hy.2⟩) instance [lattice α] {a b : α} : lattice (Icc a b) := { .. (Icc.semilattice_inf), .. (Icc.semilattice_sup) } /-- `Icc a b` has a bottom element whenever `a ≤ b`. -/ def order_bot [partial_order α] {a b : α} (h : a ≤ b) : order_bot (Icc a b) := { bot := ⟨a, ⟨le_refl a, h⟩⟩, bot_le := λ x, x.prop.1, .. (subtype.partial_order _) } /-- `Icc a b` has a top element whenever `a ≤ b`. -/ def order_top [partial_order α] {a b : α} (h : a ≤ b) : order_top (Icc a b) := { top := ⟨b, ⟨h, le_refl b⟩⟩, le_top := λ x, x.prop.2, .. (subtype.partial_order _) } /-- `Icc a b` is a `semilattice_inf_bot` whenever `a ≤ b`. -/ def semilattice_inf_bot [semilattice_inf α] {a b : α} (h : a ≤ b) : semilattice_inf_bot (Icc a b) := { .. (Icc.order_bot h), .. (Icc.semilattice_inf) } /-- `Icc a b` is a `semilattice_inf_top` whenever `a ≤ b`. -/ def semilattice_inf_top [semilattice_inf α] {a b : α} (h : a ≤ b) : semilattice_inf_top (Icc a b) := { .. (Icc.order_top h), .. (Icc.semilattice_inf) } /-- `Icc a b` is a `semilattice_sup_bot` whenever `a ≤ b`. -/ def semilattice_sup_bot [semilattice_sup α] {a b : α} (h : a ≤ b) : semilattice_sup_bot (Icc a b) := { .. (Icc.order_bot h), .. (Icc.semilattice_sup) } /-- `Icc a b` is a `semilattice_sup_top` whenever `a ≤ b`. -/ def semilattice_sup_top [semilattice_sup α] {a b : α} (h : a ≤ b) : semilattice_sup_top (Icc a b) := { .. (Icc.order_top h), .. (Icc.semilattice_sup) } /-- `Icc a b` is a `bounded_lattice` whenever `a ≤ b`. -/ def bounded_lattice [lattice α] {a b : α} (h : a ≤ b) : bounded_lattice (Icc a b) := { .. (Icc.semilattice_inf_bot h), .. (Icc.semilattice_sup_top h) } end Icc end set
6a3f2e9ea77ed2aa04b090969e99a24cbe5cae65
63abd62053d479eae5abf4951554e1064a4c45b4
/src/topology/category/Compactum.lean
3b07c3437be69a3f341a55f297b1bda9538e9e59
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
17,246
lean
/- Copyright (c) 2020 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz -/ import category_theory.monad.types import category_theory.monad.limits import category_theory.equivalence import topology.category.CompHaus import data.set.constructions /-! # Compacta and Compact Hausdorff Spaces Recall that, given a monad `M` on `Type*`, an *algebra* for `M` consists of the following data: - A type `X : Type*` - A "structure" map `M X → X`. This data must also satisfy a distributivity and unit axiom, and algebras for `M` form a category in an evident way. See the file `category_theory.monad.algebra` for a general version, as well as the following link. https://ncatlab.org/nlab/show/monad This file proves the equivalence between the category of *compact Hausdorff topological spaces* and the category of algebras for the *ultrafilter monad*. ## Notation: Here are the main objects introduced in this file. - `Compactum` is the type of compacta, which we define as algebras for the ultrafilter monad. - `Compactum_to_CompHaus` is the functor `Compactum ⥤ CompHaus`. Here `CompHaus` is the usual category of compact Hausdorff spaces. - `Compactum_to_CompHaus.is_equivalence` is a term of type `is_equivalence Compactum_to_CompHaus`. The proof of this equivalence is a bit technical. But the idea is quite simply that the structure map `ultrafilter X → X` for an algebra `X` of the ultrafilter monad should be considered as the map sending an ultrafilter to its limit in `X`. The topology on `X` is then defined by mimicking the characterization of open sets in terms of ultrafilters. Any `X : Compactum` is endowed with a coercion to `Type*`, as well as the following instances: - `topological_space X`. - `compact_space X`. - `t2_space X`. Any morphism `f : X ⟶ Y` of is endowed with a coercion to a function `X → Y`, which is shown to be continuous in `continuous_of_hom`. The function `Compactum.of_topological_space` can be used to construct a `Compactum` from a topological space which satisfies `compact_space` and `t2_space`. We also add wrappers around structures which already exist. Here are the main ones, all in the `Compactum` namespace: - `forget : Compactum ⥤ Type*` is the forgetful functor, which induces a `concrete_category` instance for `Compactum`. - `free : Type* ⥤ Compactum` is the left adjoint to `forget`, and the adjunction is in `adj`. - `str : ultrafilter X → X` is the structure map for `X : Compactum`. The notation `X.str` is preferred. - `join : ultrafilter (ultrafilter X) → ultrafilter X` is the monadic join for `X : Compactum`. Again, the notation `X.join` is preferred. - `incl : X → ultrafilter X` is the unit for `X : Compactum`. The notation `X.incl` is preferred. ## References - E. Manes, Algebraic Theories, Graduate Texts in Mathematics 26, Springer-Verlag, 1976. - https://ncatlab.org/nlab/show/ultrafilter -/ open category_theory filter topological_space category_theory.limits has_finite_inter open_locale classical local notation `β` := of_type_functor ultrafilter /-- The type `Compactum` of Compacta, defined as algebras for the ultrafilter monad. -/ @[derive [category, inhabited]] def Compactum := monad.algebra β namespace Compactum /-- The forgetful functor to Type* -/ @[derive [creates_limits,faithful]] def forget : Compactum ⥤ Type* := monad.forget _ /-- The "free" Compactum functor. -/ def free : Type* ⥤ Compactum := monad.free _ /-- The adjunction between `free` and `forget`. -/ def adj : free ⊣ forget := monad.adj _ -- Basic instances instance : concrete_category Compactum := { forget := forget } instance : has_coe_to_sort Compactum := ⟨Type*,forget.obj⟩ instance {X Y : Compactum} : has_coe_to_fun (X ⟶ Y) := ⟨λ f, X → Y, λ f, f.f⟩ instance : has_limits Compactum := has_limits_of_has_limits_creates_limits forget /-- The structure map for a compactum, essentially sending an ultrafilter to its limit. -/ def str (X : Compactum) : ultrafilter X → X := X.a /-- The monadic join. -/ def join (X : Compactum) : ultrafilter (ultrafilter X) → ultrafilter X := (μ_ β).app _ /-- The inclusion of `X` into `ultrafilter X`. -/ def incl (X : Compactum) : X → ultrafilter X := (η_ β).app _ @[simp] lemma str_incl (X : Compactum) (x : X) : X.str (X.incl x) = x := begin change ((η_ β).app _ ≫ X.a) _ = _, rw monad.algebra.unit, refl, end @[simp] lemma str_hom_commute (X Y : Compactum) (f : X ⟶ Y) (xs : ultrafilter X) : f (X.str xs) = Y.str (ultrafilter.map f xs) := begin change (X.a ≫ f.f) _ = _, rw ←f.h, refl, end @[simp] lemma join_distrib (X : Compactum) (uux : ultrafilter (ultrafilter X)) : X.str (X.join uux) = X.str (ultrafilter.map X.str uux) := begin change ((μ_ β).app _ ≫ X.a) _ = _, rw monad.algebra.assoc, refl, end instance {X : Compactum} : topological_space X := { is_open := { U | ∀ (F : ultrafilter X), X.str F ∈ U → U ∈ F.1 }, is_open_univ := λ _ _, filter.univ_sets _, is_open_inter := λ S T h3 h4 h5 h6, filter.inter_sets _ (h3 _ h6.1) (h4 _ h6.2), is_open_sUnion := λ S h1 F ⟨T,hT,h2⟩, filter.sets_of_superset _ (h1 T hT _ h2) (set.subset_sUnion_of_mem hT) } theorem is_closed_iff {X : Compactum} (S : set X) : is_closed S ↔ (∀ F : ultrafilter X, S ∈ F.1 → X.str F ∈ S) := begin split, { intros cond F h, by_contradiction c, specialize cond F c, cases F with F hF, rw ultrafilter_iff_compl_mem_iff_not_mem at hF, rw hF at cond, contradiction }, { intros h1 F h2, specialize h1 F, cases mem_or_compl_mem_of_ultrafilter F.2 S; finish } end instance {X : Compactum} : compact_space X := begin constructor, rw compact_iff_ultrafilter_le_nhds, intros F hF h, refine ⟨X.str ⟨F,hF⟩, by tauto, _⟩, rw le_nhds_iff, intros S h1 h2, exact h2 ⟨F,hF⟩ h1, end /-- A local definition used only in the proofs. -/ private def basic {X : Compactum} (A : set X) : set (ultrafilter X) := {F | A ∈ F.1} /-- A local definition used only in the proofs. -/ private def cl {X : Compactum} (A : set X) : set X := X.str '' (basic A) private lemma basic_inter {X : Compactum} (A B : set X) : basic (A ∩ B) = basic A ∩ basic B := begin ext G, split, { intro hG, refine ⟨_, _⟩; apply filter.sets_of_superset _ hG; intros x hx; finish }, { rintros ⟨h1,h2⟩, exact G.val.inter_sets h1 h2 } end private lemma subset_cl {X : Compactum} (A : set X) : A ⊆ cl A := λ a ha, ⟨X.incl a, ha,by simp⟩ private theorem cl_cl {X : Compactum} (A : set X) : cl (cl A) ⊆ cl A := begin rintros _ ⟨F,hF,rfl⟩, -- Notation to be used in this proof. let fsu := finset (set (ultrafilter X)), let ssu := set (set (ultrafilter X)), let ι : fsu → ssu := coe, let C0 : ssu := {Z | ∃ B ∈ F.1, X.str ⁻¹' B = Z}, let AA := {G : ultrafilter X | A ∈ G.1}, let C1 := insert AA C0, let C2 := finite_inter_closure C1, -- C0 is closed under intersections. have claim1 : ∀ B C ∈ C0, B ∩ C ∈ C0, { rintros B C ⟨Q,hQ,rfl⟩ ⟨R,hR,rfl⟩, use Q ∩ R, simp only [and_true, eq_self_iff_true, set.preimage_inter, subtype.val_eq_coe], exact inter_sets _ hQ hR }, -- All sets in C0 are nonempty. have claim2 : ∀ B ∈ C0, set.nonempty B, { rintros B ⟨Q,hQ,rfl⟩, obtain ⟨q⟩ := nonempty_of_mem_ultrafilter F.2 hQ, use X.incl q, simpa, }, -- The intersection of AA with every set in C0 is nonempty. have claim3 : ∀ B ∈ C0, (AA ∩ B).nonempty, { rintros B ⟨Q,hQ,rfl⟩, have : (Q ∩ cl A).nonempty, { apply nonempty_of_mem_ultrafilter F.2, exact F.1.inter_sets hQ hF }, rcases this with ⟨q,hq1,P,hq2,hq3⟩, refine ⟨P,hq2,_⟩, rw ←hq3 at hq1, simpa }, -- Suffices to show that the intersection of any finite subcollection of C1 is nonempty. suffices : ∀ (T : fsu), ι T ⊆ C1 → (⋂₀ ι T).nonempty, { obtain ⟨G,h1,hG⟩ := exists_ultrafilter_of_finite_inter_nonempty _ this, let GG : ultrafilter (ultrafilter X) := ⟨G, hG⟩, use X.join GG, have : ultrafilter.map X.str GG = F, { suffices : (ultrafilter.map X.str GG).1 ≤ F.1, { ext1, exact is_ultrafilter.unique F.2 (ultrafilter.map X.str GG).2.1 this }, intros S hS, refine h1 (or.inr ⟨S, by simpa⟩) }, rw [join_distrib, this], exact ⟨h1 (or.inl rfl), rfl⟩ }, -- C2 is closed under finite intersections (by construction!). have claim4 := finite_inter_closure_has_finite_inter C1, -- C0 is closed under finite intersections by claim1. have claim5 : has_finite_inter C0 := ⟨⟨set.univ, filter.univ_sets _, by simp⟩, claim1⟩, -- Every element of C2 is nonempty. have claim6 : ∀ P ∈ C2, (P : set (ultrafilter X)).nonempty, { suffices : ∀ P ∈ C2, P ∈ C0 ∨ ∃ Q ∈ C0, P = AA ∩ Q, { intros P hP, cases this P hP, { exact claim2 _ h }, { rcases h with ⟨Q, hQ, rfl⟩, exact claim3 _ hQ } }, intros P hP, exact claim5.finite_inter_closure_insert _ hP }, intros T hT, -- Suffices to show that the intersection of the T's is contained in C2. suffices : ⋂₀ ι T ∈ C2, by exact claim6 _ this, -- Finish apply claim4.finite_inter_mem, intros t ht, exact finite_inter_closure.basic (@hT t ht), end lemma is_closed_cl {X : Compactum} (A : set X) : is_closed (cl A) := begin rw is_closed_iff, intros F hF, exact cl_cl _ ⟨F, hF, rfl⟩, end lemma str_eq_of_le_nhds {X : Compactum} (F : ultrafilter X) (x : X) : F.1 ≤ nhds x → X.str F = x := begin -- Notation to be used in this proof. let fsu := finset (set (ultrafilter X)), let ssu := set (set (ultrafilter X)), let ι : fsu → ssu := coe, let T0 : ssu := { S | ∃ A ∈ F.1, S = basic A }, let AA := (X.str ⁻¹' {x}), let T1 := insert AA T0, let T2 := finite_inter_closure T1, intro cond, -- If F contains a closed set A, then x is contained in A. have claim1 : ∀ (A : set X), is_closed A → A ∈ F.1 → x ∈ A, { intros A hA h, by_contradiction H, rw le_nhds_iff at cond, specialize cond Aᶜ H hA, rw ultrafilter_iff_compl_mem_iff_not_mem.mp F.2 at cond, contradiction }, -- If A ∈ F, then x ∈ cl A. have claim2 : ∀ (A : set X), A ∈ F.1 → x ∈ cl A, { intros A hA, exact claim1 (cl A) (is_closed_cl A) (F.val.sets_of_superset hA (subset_cl A)) }, -- T0 is closed under intersections. have claim3 : ∀ (S1 S2 ∈ T0), S1 ∩ S2 ∈ T0, { rintros S1 S2 ⟨S1, hS1, rfl⟩ ⟨S2, hS2, rfl⟩, exact ⟨S1 ∩ S2, F.1.inter_sets hS1 hS2, by simp [basic_inter]⟩ }, -- For every S ∈ T0, the intersection AA ∩ S is nonempty. have claim4 : ∀ (S ∈ T0), (AA ∩ S).nonempty, { rintros S ⟨S, hS, rfl⟩, rcases claim2 _ hS with ⟨G, hG, hG2⟩, exact ⟨G, hG2, hG⟩ }, -- Every element of T0 is nonempty. have claim5 : ∀ (S ∈ T0), set.nonempty S, { rintros S ⟨S, hS, rfl⟩, exact ⟨F, hS⟩ }, -- Every element of T2 is nonempty. have claim6 : ∀ (S ∈ T2), set.nonempty S, { suffices : ∀ S ∈ T2, S ∈ T0 ∨ ∃ Q ∈ T0, S = AA ∩ Q, { intros S hS, cases this _ hS with h h, { exact claim5 S h }, { rcases h with ⟨Q, hQ, rfl⟩, exact claim4 Q hQ } }, intros S hS, apply finite_inter_closure_insert, { split, { use set.univ, refine ⟨filter.univ_sets _, _⟩, ext, refine ⟨_, by tauto⟩, { intro, apply filter.univ_sets, } }, { exact claim3} }, { exact hS} }, -- It suffices to show that the intersection of any finite subset of T1 is nonempty. suffices : ∀ (F : fsu), ↑F ⊆ T1 → (⋂₀ ι F).nonempty, { obtain ⟨G,h1,hG⟩ := exists_ultrafilter_of_finite_inter_nonempty _ this, let GG : ultrafilter (ultrafilter X) := ⟨G, hG⟩, have c1 : X.join GG = F, { suffices : (X.join GG).1 ≤ F.1, { ext1, exact is_ultrafilter.unique F.2 (join X GG).2.1 this}, intros P hP, exact h1 (or.inr ⟨P, hP, rfl⟩) }, have c2 : ultrafilter.map X.str GG = X.incl x, { suffices : (ultrafilter.map X.str GG).1 ≤ (X.incl x).1, { ext1, exact is_ultrafilter.unique (incl X x).2 (ultrafilter.map (str X) GG).2.1 this }, intros P hP, apply filter.sets_of_superset _ (h1 (or.inl rfl)), rintros x ⟨rfl⟩, exact hP }, simp [←c1, c2] }, -- Finish... intros T hT, refine claim6 _ (finite_inter_mem (finite_inter_closure_has_finite_inter _) _ _), intros t ht, exact finite_inter_closure.basic (@hT t ht) end lemma le_nhds_of_str_eq {X : Compactum} (F : ultrafilter X) (x : X) : X.str F = x → F.1 ≤ nhds x := λ h, le_nhds_iff.mpr (λ s hx hs, hs _ $ by rwa h) -- All the hard work above boils down to this t2_space instance. instance {X : Compactum} : t2_space X := begin rw t2_iff_ultrafilter, intros _ _ _ hF hx hy, replace hx := str_eq_of_le_nhds ⟨_, hF⟩ _ hx, replace hy := str_eq_of_le_nhds ⟨_, hF⟩ _ hy, cc, end /-- The structure map of a compactum actually computes limits. -/ lemma Lim_eq_str {X : Compactum} (F : ultrafilter X) : F.Lim = X.str F := begin erw [is_ultrafilter.Lim_eq_iff_le_nhds, le_nhds_iff], tauto, end lemma cl_eq_closure {X : Compactum} (A : set X) : cl A = closure A := begin ext, rw mem_closure_iff_ultrafilter, split, { rintro ⟨F, h1, h2⟩, exact ⟨F, h1, le_nhds_of_str_eq _ _ h2⟩ }, { rintro ⟨F, h1, h2⟩, exact ⟨F, h1, str_eq_of_le_nhds _ _ h2⟩ } end /-- Any morphism of compacta is continuous. -/ lemma continuous_of_hom {X Y : Compactum} (f : X ⟶ Y) : continuous f := begin rw continuous_iff_ultrafilter, intros x _ h1 h2, change (ultrafilter.map f ⟨_, h1⟩).1 ≤ _, apply le_nhds_of_str_eq, rw [← str_hom_commute, str_eq_of_le_nhds ⟨_, h1⟩ x h2], end /-- Given any compact Hausdorff space, we construct a Compactum. -/ noncomputable def of_topological_space (X : Type*) [topological_space X] [compact_space X] [t2_space X] : Compactum := { A := X, a := ultrafilter.Lim, unit' := by {ext x, exact Lim_eq (by finish [le_nhds_iff]) }, assoc' := begin ext FF, change ultrafilter (ultrafilter X) at FF, set x := (ultrafilter.map ultrafilter.Lim FF).Lim with c1, have c2 : ∀ (U : set X) (F : ultrafilter X), F.Lim ∈ U → is_open U → U ∈ F.1, { intros U F h1 hU, exact c1 ▸ is_open_iff_ultrafilter.mp hU _ h1 _ F.2 (is_ultrafilter.le_nhds_Lim _) }, have c3 : (ultrafilter.map ultrafilter.Lim FF).1 ≤ nhds x, { rw le_nhds_iff, intros U hx hU, refine c2 _ _ (by rwa ← c1) hU }, have c4 : ∀ (U : set X), x ∈ U → is_open U → { G : ultrafilter X | U ∈ G.1 } ∈ FF.1, { intros U hx hU, suffices : ultrafilter.Lim ⁻¹' U ∈ FF.1, { apply filter.sets_of_superset _ this, intros P hP, exact c2 U P hP hU}, exact @c3 U (mem_nhds_sets hU hx) }, apply Lim_eq, rw le_nhds_iff, exact c4, end } /-- Any continuous map between Compacta is a morphism of compacta. -/ def hom_of_continuous {X Y : Compactum} (f : X → Y) (cont : continuous f) : X ⟶ Y := { f := f, h' := begin rw continuous_iff_ultrafilter at cont, ext (F : ultrafilter X), specialize cont (X.str F) F.1 F.2 (le_nhds_of_str_eq F (X.str F) rfl), have := str_eq_of_le_nhds (ultrafilter.map f F) _ cont, simpa only [←this, types_comp_apply, of_type_functor_map], end } end Compactum /-- The functor functor from Compactum to CompHaus. -/ def Compactum_to_CompHaus : Compactum ⥤ CompHaus := { obj := λ X, { to_Top := { α := X } }, map := λ X Y f, { to_fun := f, continuous_to_fun := Compactum.continuous_of_hom _ }} namespace Compactum_to_CompHaus /-- The functor Compactum_to_CompHaus is full. -/ def full : full Compactum_to_CompHaus := { preimage := λ X Y f, Compactum.hom_of_continuous f.1 f.2 } /-- The functor Compactum_to_CompHaus is faithful. -/ lemma faithful : faithful Compactum_to_CompHaus := {} /-- This definition is used to prove essential surjectivity of Compactum_to_CompHaus. -/ noncomputable def iso_of_topological_space {D : CompHaus} : Compactum_to_CompHaus.obj (Compactum.of_topological_space D) ≅ D := { hom := { to_fun := id, continuous_to_fun := λ _ h, by {rw is_open_iff_ultrafilter' at h, exact h} }, inv := { to_fun := id, continuous_to_fun := λ _ h1, by {rw is_open_iff_ultrafilter', intros _ h2, exact h1 _ h2} } } /-- The functor Compactum_to_CompHaus is essentially surjective. -/ noncomputable def ess_surj : ess_surj Compactum_to_CompHaus := { obj_preimage := λ X, Compactum.of_topological_space X, iso' := λ _, iso_of_topological_space } /-- The functor Compactum_to_CompHaus is an equivalence of categories. -/ noncomputable def is_equivalence : is_equivalence Compactum_to_CompHaus := begin apply equivalence.equivalence_of_fully_faithfully_ess_surj _, exact Compactum_to_CompHaus.full, exact Compactum_to_CompHaus.faithful, exact Compactum_to_CompHaus.ess_surj, end end Compactum_to_CompHaus
f235874eed1375ef30e150838913231833a4ba30
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/geometry/manifold/local_invariant_properties.lean
ff005836cf718e000381be7c033cfe272e44f0bc
[]
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
27,351
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.geometry.manifold.smooth_manifold_with_corners import Mathlib.PostPort universes u_1 u_3 l u_2 u_4 namespace Mathlib /-! # Local properties invariant under a groupoid We study properties of a triple `(g, s, x)` where `g` is a function between two spaces `H` and `H'`, `s` is a subset of `H` and `x` is a point of `H`. Our goal is to register how such a property should behave to make sense in charted spaces modelled on `H` and `H'`. The main examples we have in mind are the properties "`g` is differentiable at `x` within `s`", or "`g` is smooth at `x` within `s`". We want to develop general results that, when applied in these specific situations, say that the notion of smooth function in a manifold behaves well under restriction, intersection, is local, and so on. ## Main definitions * `local_invariant_prop G G' P` says that a property `P` of a triple `(g, s, x)` is local, and invariant under composition by elements of the groupoids `G` and `G'` of `H` and `H'` respectively. * `charted_space.lift_prop_within_at` (resp. `lift_prop_at`, `lift_prop_on` and `lift_prop`): given a property `P` of `(g, s, x)` where `g : H → H'`, define the corresponding property for functions `M → M'` where `M` and `M'` are charted spaces modelled respectively on `H` and `H'`. We define these properties within a set at a point, or at a point, or on a set, or in the whole space. This lifting process (obtained by restricting to suitable chart domains) can always be done, but it only behaves well under locality and invariance assumptions. Given `hG : local_invariant_prop G G' P`, we deduce many properties of the lifted property on the charted spaces. For instance, `hG.lift_prop_within_at_inter` says that `P g s x` is equivalent to `P g (s ∩ t) x` whenever `t` is a neighborhood of `x`. ## Implementation notes We do not use dot notation for properties of the lifted property. For instance, we have `hG.lift_prop_within_at_congr` saying that if `lift_prop_within_at P g s x` holds, and `g` and `g'` coincide on `s`, then `lift_prop_within_at P g' s x` holds. We can't call it `lift_prop_within_at.congr` as it is in the namespace associated to `local_invariant_prop`, not in the one for `lift_prop_within_at`. -/ namespace structure_groupoid /-- Structure recording good behavior of a property of a triple `(f, s, x)` where `f` is a function, `s` a set and `x` a point. Good behavior here means locality and invariance under given groupoids (both in the source and in the target). Given such a good behavior, the lift of this property to charted spaces admitting these groupoids will inherit the good behavior. -/ structure local_invariant_prop {H : Type u_1} [topological_space H] {H' : Type u_3} [topological_space H'] (G : structure_groupoid H) (G' : structure_groupoid H') (P : (H → H') → set H → H → Prop) where is_local : ∀ {s : set H} {x : H} {u : set H} {f : H → H'}, is_open u → x ∈ u → (P f s x ↔ P f (s ∩ u) x) right_invariance : ∀ {s : set H} {x : H} {f : H → H'} {e : local_homeomorph H H}, e ∈ G → x ∈ local_equiv.source (local_homeomorph.to_local_equiv e) → P f s x → P (f ∘ ⇑(local_homeomorph.symm e)) (local_equiv.target (local_homeomorph.to_local_equiv e) ∩ ⇑(local_homeomorph.symm e) ⁻¹' s) (coe_fn e x) congr : ∀ {s : set H} {x : H} {f g : H → H'}, (∀ (y : H), y ∈ s → f y = g y) → f x = g x → P f s x → P g s x left_invariance : ∀ {s : set H} {x : H} {f : H → H'} {e' : local_homeomorph H' H'}, e' ∈ G' → s ⊆ f ⁻¹' local_equiv.source (local_homeomorph.to_local_equiv e') → f x ∈ local_equiv.source (local_homeomorph.to_local_equiv e') → P f s x → P (⇑e' ∘ f) s x end structure_groupoid /-- Given a property of germs of functions and sets in the model space, then one defines a corresponding property in a charted space, by requiring that it holds at the preferred chart at this point. (When the property is local and invariant, it will in fact hold using any chart, see `lift_prop_within_at_indep_chart`). We require continuity in the lifted property, as otherwise one single chart might fail to capture the behavior of the function. -/ def charted_space.lift_prop_within_at {H : Type u_1} {M : Type u_2} [topological_space H] [topological_space M] [charted_space H M] {H' : Type u_3} {M' : Type u_4} [topological_space H'] [topological_space M'] [charted_space H' M'] (P : (H → H') → set H → H → Prop) (f : M → M') (s : set M) (x : M) := continuous_within_at f s x ∧ P (⇑(charted_space.chart_at H' (f x)) ∘ f ∘ ⇑(local_homeomorph.symm (charted_space.chart_at H x))) (local_equiv.target (local_homeomorph.to_local_equiv (charted_space.chart_at H x)) ∩ ⇑(local_homeomorph.symm (charted_space.chart_at H x)) ⁻¹' (s ∩ f ⁻¹' local_equiv.source (local_homeomorph.to_local_equiv (charted_space.chart_at H' (f x))))) (coe_fn (charted_space.chart_at H x) x) /-- Given a property of germs of functions and sets in the model space, then one defines a corresponding property of functions on sets in a charted space, by requiring that it holds around each point of the set, in the preferred charts. -/ def charted_space.lift_prop_on {H : Type u_1} {M : Type u_2} [topological_space H] [topological_space M] [charted_space H M] {H' : Type u_3} {M' : Type u_4} [topological_space H'] [topological_space M'] [charted_space H' M'] (P : (H → H') → set H → H → Prop) (f : M → M') (s : set M) := ∀ (x : M), x ∈ s → charted_space.lift_prop_within_at P f s x /-- Given a property of germs of functions and sets in the model space, then one defines a corresponding property of a function at a point in a charted space, by requiring that it holds in the preferred chart. -/ def charted_space.lift_prop_at {H : Type u_1} {M : Type u_2} [topological_space H] [topological_space M] [charted_space H M] {H' : Type u_3} {M' : Type u_4} [topological_space H'] [topological_space M'] [charted_space H' M'] (P : (H → H') → set H → H → Prop) (f : M → M') (x : M) := charted_space.lift_prop_within_at P f set.univ x /-- Given a property of germs of functions and sets in the model space, then one defines a corresponding property of a function in a charted space, by requiring that it holds in the preferred chart around every point. -/ def charted_space.lift_prop {H : Type u_1} {M : Type u_2} [topological_space H] [topological_space M] [charted_space H M] {H' : Type u_3} {M' : Type u_4} [topological_space H'] [topological_space M'] [charted_space H' M'] (P : (H → H') → set H → H → Prop) (f : M → M') := ∀ (x : M), charted_space.lift_prop_at P f x namespace structure_groupoid theorem lift_prop_within_at_univ {H : Type u_1} {M : Type u_2} [topological_space H] [topological_space M] [charted_space H M] {H' : Type u_3} {M' : Type u_4} [topological_space H'] [topological_space M'] [charted_space H' M'] {P : (H → H') → set H → H → Prop} {g : M → M'} {x : M} : charted_space.lift_prop_within_at P g set.univ x ↔ charted_space.lift_prop_at P g x := iff.rfl theorem lift_prop_on_univ {H : Type u_1} {M : Type u_2} [topological_space H] [topological_space M] [charted_space H M] {H' : Type u_3} {M' : Type u_4} [topological_space H'] [topological_space M'] [charted_space H' M'] {P : (H → H') → set H → H → Prop} {g : M → M'} : charted_space.lift_prop_on P g set.univ ↔ charted_space.lift_prop P g := sorry namespace local_invariant_prop /-- If a property of a germ of function `g` on a pointed set `(s, x)` is invariant under the structure groupoid (by composition in the source space and in the target space), then expressing it in charted spaces does not depend on the element of the maximal atlas one uses both in the source and in the target manifolds, provided they are defined around `x` and `g x` respectively, and provided `g` is continuous within `s` at `x` (otherwise, the local behavior of `g` at `x` can not be captured with a chart in the target). -/ theorem lift_prop_within_at_indep_chart_aux {H : Type u_1} {M : Type u_2} [topological_space H] [topological_space M] [charted_space H M] {H' : Type u_3} {M' : Type u_4} [topological_space H'] [topological_space M'] [charted_space H' M'] {G : structure_groupoid H} {G' : structure_groupoid H'} {e : local_homeomorph M H} {e' : local_homeomorph M H} {f : local_homeomorph M' H'} {f' : local_homeomorph M' H'} {P : (H → H') → set H → H → Prop} {g : M → M'} {s : set M} {x : M} (hG : local_invariant_prop G G' P) (he : e ∈ maximal_atlas M G) (xe : x ∈ local_equiv.source (local_homeomorph.to_local_equiv e)) (he' : e' ∈ maximal_atlas M G) (xe' : x ∈ local_equiv.source (local_homeomorph.to_local_equiv e')) (hf : f ∈ maximal_atlas M' G') (xf : g x ∈ local_equiv.source (local_homeomorph.to_local_equiv f)) (hf' : f' ∈ maximal_atlas M' G') (xf' : g x ∈ local_equiv.source (local_homeomorph.to_local_equiv f')) (hgs : continuous_within_at g s x) (h : P (⇑f ∘ g ∘ ⇑(local_homeomorph.symm e)) (local_equiv.target (local_homeomorph.to_local_equiv e) ∩ ⇑(local_homeomorph.symm e) ⁻¹' (s ∩ g ⁻¹' local_equiv.source (local_homeomorph.to_local_equiv f))) (coe_fn e x)) : P (⇑f' ∘ g ∘ ⇑(local_homeomorph.symm e')) (local_equiv.target (local_homeomorph.to_local_equiv e') ∩ ⇑(local_homeomorph.symm e') ⁻¹' (s ∩ g ⁻¹' local_equiv.source (local_homeomorph.to_local_equiv f'))) (coe_fn e' x) := sorry theorem lift_prop_within_at_indep_chart {H : Type u_1} {M : Type u_2} [topological_space H] [topological_space M] [charted_space H M] {H' : Type u_3} {M' : Type u_4} [topological_space H'] [topological_space M'] [charted_space H' M'] {G : structure_groupoid H} {G' : structure_groupoid H'} {e : local_homeomorph M H} {f : local_homeomorph M' H'} {P : (H → H') → set H → H → Prop} {g : M → M'} {s : set M} {x : M} (hG : local_invariant_prop G G' P) [has_groupoid M G] [has_groupoid M' G'] (he : e ∈ maximal_atlas M G) (xe : x ∈ local_equiv.source (local_homeomorph.to_local_equiv e)) (hf : f ∈ maximal_atlas M' G') (xf : g x ∈ local_equiv.source (local_homeomorph.to_local_equiv f)) : charted_space.lift_prop_within_at P g s x ↔ continuous_within_at g s x ∧ P (⇑f ∘ g ∘ ⇑(local_homeomorph.symm e)) (local_equiv.target (local_homeomorph.to_local_equiv e) ∩ ⇑(local_homeomorph.symm e) ⁻¹' (s ∩ g ⁻¹' local_equiv.source (local_homeomorph.to_local_equiv f))) (coe_fn e x) := sorry theorem lift_prop_on_indep_chart {H : Type u_1} {M : Type u_2} [topological_space H] [topological_space M] [charted_space H M] {H' : Type u_3} {M' : Type u_4} [topological_space H'] [topological_space M'] [charted_space H' M'] {G : structure_groupoid H} {G' : structure_groupoid H'} {e : local_homeomorph M H} {f : local_homeomorph M' H'} {P : (H → H') → set H → H → Prop} {g : M → M'} {s : set M} (hG : local_invariant_prop G G' P) [has_groupoid M G] [has_groupoid M' G'] (he : e ∈ maximal_atlas M G) (hf : f ∈ maximal_atlas M' G') (h : charted_space.lift_prop_on P g s) (y : H) : y ∈ local_equiv.target (local_homeomorph.to_local_equiv e) ∩ ⇑(local_homeomorph.symm e) ⁻¹' (s ∩ g ⁻¹' local_equiv.source (local_homeomorph.to_local_equiv f)) → P (⇑f ∘ g ∘ ⇑(local_homeomorph.symm e)) (local_equiv.target (local_homeomorph.to_local_equiv e) ∩ ⇑(local_homeomorph.symm e) ⁻¹' (s ∩ g ⁻¹' local_equiv.source (local_homeomorph.to_local_equiv f))) y := sorry theorem lift_prop_within_at_inter' {H : Type u_1} {M : Type u_2} [topological_space H] [topological_space M] [charted_space H M] {H' : Type u_3} {M' : Type u_4} [topological_space H'] [topological_space M'] [charted_space H' M'] {G : structure_groupoid H} {G' : structure_groupoid H'} {P : (H → H') → set H → H → Prop} {g : M → M'} {s : set M} {t : set M} {x : M} (hG : local_invariant_prop G G' P) (ht : t ∈ nhds_within x s) : charted_space.lift_prop_within_at P g (s ∩ t) x ↔ charted_space.lift_prop_within_at P g s x := sorry theorem lift_prop_within_at_inter {H : Type u_1} {M : Type u_2} [topological_space H] [topological_space M] [charted_space H M] {H' : Type u_3} {M' : Type u_4} [topological_space H'] [topological_space M'] [charted_space H' M'] {G : structure_groupoid H} {G' : structure_groupoid H'} {P : (H → H') → set H → H → Prop} {g : M → M'} {s : set M} {t : set M} {x : M} (hG : local_invariant_prop G G' P) (ht : t ∈ nhds x) : charted_space.lift_prop_within_at P g (s ∩ t) x ↔ charted_space.lift_prop_within_at P g s x := lift_prop_within_at_inter' hG (mem_nhds_within_of_mem_nhds ht) theorem lift_prop_at_of_lift_prop_within_at {H : Type u_1} {M : Type u_2} [topological_space H] [topological_space M] [charted_space H M] {H' : Type u_3} {M' : Type u_4} [topological_space H'] [topological_space M'] [charted_space H' M'] {G : structure_groupoid H} {G' : structure_groupoid H'} {P : (H → H') → set H → H → Prop} {g : M → M'} {s : set M} {x : M} (hG : local_invariant_prop G G' P) (h : charted_space.lift_prop_within_at P g s x) (hs : s ∈ nhds x) : charted_space.lift_prop_at P g x := sorry theorem lift_prop_within_at_of_lift_prop_at_of_mem_nhds {H : Type u_1} {M : Type u_2} [topological_space H] [topological_space M] [charted_space H M] {H' : Type u_3} {M' : Type u_4} [topological_space H'] [topological_space M'] [charted_space H' M'] {G : structure_groupoid H} {G' : structure_groupoid H'} {P : (H → H') → set H → H → Prop} {g : M → M'} {s : set M} {x : M} (hG : local_invariant_prop G G' P) (h : charted_space.lift_prop_at P g x) (hs : s ∈ nhds x) : charted_space.lift_prop_within_at P g s x := sorry theorem lift_prop_on_of_locally_lift_prop_on {H : Type u_1} {M : Type u_2} [topological_space H] [topological_space M] [charted_space H M] {H' : Type u_3} {M' : Type u_4} [topological_space H'] [topological_space M'] [charted_space H' M'] {G : structure_groupoid H} {G' : structure_groupoid H'} {P : (H → H') → set H → H → Prop} {g : M → M'} {s : set M} (hG : local_invariant_prop G G' P) (h : ∀ (x : M), x ∈ s → ∃ (u : set M), is_open u ∧ x ∈ u ∧ charted_space.lift_prop_on P g (s ∩ u)) : charted_space.lift_prop_on P g s := sorry theorem lift_prop_of_locally_lift_prop_on {H : Type u_1} {M : Type u_2} [topological_space H] [topological_space M] [charted_space H M] {H' : Type u_3} {M' : Type u_4} [topological_space H'] [topological_space M'] [charted_space H' M'] {G : structure_groupoid H} {G' : structure_groupoid H'} {P : (H → H') → set H → H → Prop} {g : M → M'} (hG : local_invariant_prop G G' P) (h : ∀ (x : M), ∃ (u : set M), is_open u ∧ x ∈ u ∧ charted_space.lift_prop_on P g u) : charted_space.lift_prop P g := sorry theorem lift_prop_within_at_congr {H : Type u_1} {M : Type u_2} [topological_space H] [topological_space M] [charted_space H M] {H' : Type u_3} {M' : Type u_4} [topological_space H'] [topological_space M'] [charted_space H' M'] {G : structure_groupoid H} {G' : structure_groupoid H'} {P : (H → H') → set H → H → Prop} {g : M → M'} {g' : M → M'} {s : set M} {x : M} (hG : local_invariant_prop G G' P) (h : charted_space.lift_prop_within_at P g s x) (h₁ : ∀ (y : M), y ∈ s → g' y = g y) (hx : g' x = g x) : charted_space.lift_prop_within_at P g' s x := sorry theorem lift_prop_within_at_congr_iff {H : Type u_1} {M : Type u_2} [topological_space H] [topological_space M] [charted_space H M] {H' : Type u_3} {M' : Type u_4} [topological_space H'] [topological_space M'] [charted_space H' M'] {G : structure_groupoid H} {G' : structure_groupoid H'} {P : (H → H') → set H → H → Prop} {g : M → M'} {g' : M → M'} {s : set M} {x : M} (hG : local_invariant_prop G G' P) (h₁ : ∀ (y : M), y ∈ s → g' y = g y) (hx : g' x = g x) : charted_space.lift_prop_within_at P g' s x ↔ charted_space.lift_prop_within_at P g s x := sorry theorem lift_prop_within_at_congr_of_eventually_eq {H : Type u_1} {M : Type u_2} [topological_space H] [topological_space M] [charted_space H M] {H' : Type u_3} {M' : Type u_4} [topological_space H'] [topological_space M'] [charted_space H' M'] {G : structure_groupoid H} {G' : structure_groupoid H'} {P : (H → H') → set H → H → Prop} {g : M → M'} {g' : M → M'} {s : set M} {x : M} (hG : local_invariant_prop G G' P) (h : charted_space.lift_prop_within_at P g s x) (h₁ : filter.eventually_eq (nhds_within x s) g' g) (hx : g' x = g x) : charted_space.lift_prop_within_at P g' s x := sorry theorem lift_prop_within_at_congr_iff_of_eventually_eq {H : Type u_1} {M : Type u_2} [topological_space H] [topological_space M] [charted_space H M] {H' : Type u_3} {M' : Type u_4} [topological_space H'] [topological_space M'] [charted_space H' M'] {G : structure_groupoid H} {G' : structure_groupoid H'} {P : (H → H') → set H → H → Prop} {g : M → M'} {g' : M → M'} {s : set M} {x : M} (hG : local_invariant_prop G G' P) (h₁ : filter.eventually_eq (nhds_within x s) g' g) (hx : g' x = g x) : charted_space.lift_prop_within_at P g' s x ↔ charted_space.lift_prop_within_at P g s x := sorry theorem lift_prop_at_congr_of_eventually_eq {H : Type u_1} {M : Type u_2} [topological_space H] [topological_space M] [charted_space H M] {H' : Type u_3} {M' : Type u_4} [topological_space H'] [topological_space M'] [charted_space H' M'] {G : structure_groupoid H} {G' : structure_groupoid H'} {P : (H → H') → set H → H → Prop} {g : M → M'} {g' : M → M'} {x : M} (hG : local_invariant_prop G G' P) (h : charted_space.lift_prop_at P g x) (h₁ : filter.eventually_eq (nhds x) g' g) : charted_space.lift_prop_at P g' x := sorry theorem lift_prop_at_congr_iff_of_eventually_eq {H : Type u_1} {M : Type u_2} [topological_space H] [topological_space M] [charted_space H M] {H' : Type u_3} {M' : Type u_4} [topological_space H'] [topological_space M'] [charted_space H' M'] {G : structure_groupoid H} {G' : structure_groupoid H'} {P : (H → H') → set H → H → Prop} {g : M → M'} {g' : M → M'} {x : M} (hG : local_invariant_prop G G' P) (h₁ : filter.eventually_eq (nhds x) g' g) : charted_space.lift_prop_at P g' x ↔ charted_space.lift_prop_at P g x := sorry theorem lift_prop_on_congr {H : Type u_1} {M : Type u_2} [topological_space H] [topological_space M] [charted_space H M] {H' : Type u_3} {M' : Type u_4} [topological_space H'] [topological_space M'] [charted_space H' M'] {G : structure_groupoid H} {G' : structure_groupoid H'} {P : (H → H') → set H → H → Prop} {g : M → M'} {g' : M → M'} {s : set M} (hG : local_invariant_prop G G' P) (h : charted_space.lift_prop_on P g s) (h₁ : ∀ (y : M), y ∈ s → g' y = g y) : charted_space.lift_prop_on P g' s := fun (x : M) (hx : x ∈ s) => lift_prop_within_at_congr hG (h x hx) h₁ (h₁ x hx) theorem lift_prop_on_congr_iff {H : Type u_1} {M : Type u_2} [topological_space H] [topological_space M] [charted_space H M] {H' : Type u_3} {M' : Type u_4} [topological_space H'] [topological_space M'] [charted_space H' M'] {G : structure_groupoid H} {G' : structure_groupoid H'} {P : (H → H') → set H → H → Prop} {g : M → M'} {g' : M → M'} {s : set M} (hG : local_invariant_prop G G' P) (h₁ : ∀ (y : M), y ∈ s → g' y = g y) : charted_space.lift_prop_on P g' s ↔ charted_space.lift_prop_on P g s := sorry theorem lift_prop_within_at_mono {H : Type u_1} {M : Type u_2} [topological_space H] [topological_space M] [charted_space H M] {H' : Type u_3} {M' : Type u_4} [topological_space H'] [topological_space M'] [charted_space H' M'] {P : (H → H') → set H → H → Prop} {g : M → M'} {s : set M} {t : set M} {x : M} (mono : ∀ {s : set H} {x : H} {t : set H} {f : H → H'}, t ⊆ s → P f s x → P f t x) (h : charted_space.lift_prop_within_at P g t x) (hst : s ⊆ t) : charted_space.lift_prop_within_at P g s x := sorry theorem lift_prop_within_at_of_lift_prop_at {H : Type u_1} {M : Type u_2} [topological_space H] [topological_space M] [charted_space H M] {H' : Type u_3} {M' : Type u_4} [topological_space H'] [topological_space M'] [charted_space H' M'] {P : (H → H') → set H → H → Prop} {g : M → M'} {s : set M} {x : M} (mono : ∀ {s : set H} {x : H} {t : set H} {f : H → H'}, t ⊆ s → P f s x → P f t x) (h : charted_space.lift_prop_at P g x) : charted_space.lift_prop_within_at P g s x := lift_prop_within_at_mono mono (eq.mp (Eq._oldrec (Eq.refl (charted_space.lift_prop_at P g x)) (Eq.symm (propext lift_prop_within_at_univ))) h) (set.subset_univ s) theorem lift_prop_on_mono {H : Type u_1} {M : Type u_2} [topological_space H] [topological_space M] [charted_space H M] {H' : Type u_3} {M' : Type u_4} [topological_space H'] [topological_space M'] [charted_space H' M'] {P : (H → H') → set H → H → Prop} {g : M → M'} {s : set M} {t : set M} (mono : ∀ {s : set H} {x : H} {t : set H} {f : H → H'}, t ⊆ s → P f s x → P f t x) (h : charted_space.lift_prop_on P g t) (hst : s ⊆ t) : charted_space.lift_prop_on P g s := fun (x : M) (hx : x ∈ s) => lift_prop_within_at_mono mono (h x (hst hx)) hst theorem lift_prop_on_of_lift_prop {H : Type u_1} {M : Type u_2} [topological_space H] [topological_space M] [charted_space H M] {H' : Type u_3} {M' : Type u_4} [topological_space H'] [topological_space M'] [charted_space H' M'] {P : (H → H') → set H → H → Prop} {g : M → M'} {s : set M} (mono : ∀ {s : set H} {x : H} {t : set H} {f : H → H'}, t ⊆ s → P f s x → P f t x) (h : charted_space.lift_prop P g) : charted_space.lift_prop_on P g s := lift_prop_on_mono mono (eq.mp (Eq._oldrec (Eq.refl (charted_space.lift_prop P g)) (Eq.symm (propext lift_prop_on_univ))) h) (set.subset_univ s) theorem lift_prop_at_of_mem_maximal_atlas {H : Type u_1} {M : Type u_2} [topological_space H] [topological_space M] [charted_space H M] {G : structure_groupoid H} {e : local_homeomorph M H} {x : M} {Q : (H → H) → set H → H → Prop} [has_groupoid M G] (hG : local_invariant_prop G G Q) (hQ : ∀ (y : H), Q id set.univ y) (he : e ∈ maximal_atlas M G) (hx : x ∈ local_equiv.source (local_homeomorph.to_local_equiv e)) : charted_space.lift_prop_at Q (⇑e) x := sorry theorem lift_prop_on_of_mem_maximal_atlas {H : Type u_1} {M : Type u_2} [topological_space H] [topological_space M] [charted_space H M] {G : structure_groupoid H} {e : local_homeomorph M H} {Q : (H → H) → set H → H → Prop} [has_groupoid M G] (hG : local_invariant_prop G G Q) (hQ : ∀ (y : H), Q id set.univ y) (he : e ∈ maximal_atlas M G) : charted_space.lift_prop_on Q (⇑e) (local_equiv.source (local_homeomorph.to_local_equiv e)) := sorry theorem lift_prop_at_symm_of_mem_maximal_atlas {H : Type u_1} {M : Type u_2} [topological_space H] [topological_space M] [charted_space H M] {G : structure_groupoid H} {e : local_homeomorph M H} {Q : (H → H) → set H → H → Prop} [has_groupoid M G] {x : H} (hG : local_invariant_prop G G Q) (hQ : ∀ (y : H), Q id set.univ y) (he : e ∈ maximal_atlas M G) (hx : x ∈ local_equiv.target (local_homeomorph.to_local_equiv e)) : charted_space.lift_prop_at Q (⇑(local_homeomorph.symm e)) x := sorry theorem lift_prop_on_symm_of_mem_maximal_atlas {H : Type u_1} {M : Type u_2} [topological_space H] [topological_space M] [charted_space H M] {G : structure_groupoid H} {e : local_homeomorph M H} {Q : (H → H) → set H → H → Prop} [has_groupoid M G] (hG : local_invariant_prop G G Q) (hQ : ∀ (y : H), Q id set.univ y) (he : e ∈ maximal_atlas M G) : charted_space.lift_prop_on Q (⇑(local_homeomorph.symm e)) (local_equiv.target (local_homeomorph.to_local_equiv e)) := sorry theorem lift_prop_at_chart {H : Type u_1} {M : Type u_2} [topological_space H] [topological_space M] [charted_space H M] {G : structure_groupoid H} {x : M} {Q : (H → H) → set H → H → Prop} [has_groupoid M G] (hG : local_invariant_prop G G Q) (hQ : ∀ (y : H), Q id set.univ y) : charted_space.lift_prop_at Q (⇑(charted_space.chart_at H x)) x := lift_prop_at_of_mem_maximal_atlas hG hQ (chart_mem_maximal_atlas G x) (charted_space.mem_chart_source H x) theorem lift_prop_on_chart {H : Type u_1} {M : Type u_2} [topological_space H] [topological_space M] [charted_space H M] {G : structure_groupoid H} {x : M} {Q : (H → H) → set H → H → Prop} [has_groupoid M G] (hG : local_invariant_prop G G Q) (hQ : ∀ (y : H), Q id set.univ y) : charted_space.lift_prop_on Q (⇑(charted_space.chart_at H x)) (local_equiv.source (local_homeomorph.to_local_equiv (charted_space.chart_at H x))) := lift_prop_on_of_mem_maximal_atlas hG hQ (chart_mem_maximal_atlas G x) theorem lift_prop_at_chart_symm {H : Type u_1} {M : Type u_2} [topological_space H] [topological_space M] [charted_space H M] {G : structure_groupoid H} {x : M} {Q : (H → H) → set H → H → Prop} [has_groupoid M G] (hG : local_invariant_prop G G Q) (hQ : ∀ (y : H), Q id set.univ y) : charted_space.lift_prop_at Q (⇑(local_homeomorph.symm (charted_space.chart_at H x))) (coe_fn (charted_space.chart_at H x) x) := sorry theorem lift_prop_on_chart_symm {H : Type u_1} {M : Type u_2} [topological_space H] [topological_space M] [charted_space H M] {G : structure_groupoid H} {x : M} {Q : (H → H) → set H → H → Prop} [has_groupoid M G] (hG : local_invariant_prop G G Q) (hQ : ∀ (y : H), Q id set.univ y) : charted_space.lift_prop_on Q (⇑(local_homeomorph.symm (charted_space.chart_at H x))) (local_equiv.target (local_homeomorph.to_local_equiv (charted_space.chart_at H x))) := lift_prop_on_symm_of_mem_maximal_atlas hG hQ (chart_mem_maximal_atlas G x) theorem lift_prop_id {H : Type u_1} {M : Type u_2} [topological_space H] [topological_space M] [charted_space H M] {G : structure_groupoid H} {Q : (H → H) → set H → H → Prop} (hG : local_invariant_prop G G Q) (hQ : ∀ (y : H), Q id set.univ y) : charted_space.lift_prop Q id := sorry end local_invariant_prop /-- A function from a model space `H` to itself is a local structomorphism, with respect to a structure groupoid `G` for `H`, relative to a set `s` in `H`, if for all points `x` in the set, the function agrees with a `G`-structomorphism on `s` in a neighbourhood of `x`. -/ def is_local_structomorph_within_at {H : Type u_1} [topological_space H] (G : structure_groupoid H) (f : H → H) (s : set H) (x : H) := x ∈ s → ∃ (e : local_homeomorph H H), e ∈ G ∧ set.eq_on f (local_equiv.to_fun (local_homeomorph.to_local_equiv e)) (s ∩ local_equiv.source (local_homeomorph.to_local_equiv e)) ∧ x ∈ local_equiv.source (local_homeomorph.to_local_equiv e) /-- For a groupoid `G` which is `closed_under_restriction`, being a local structomorphism is a local invariant property. -/ theorem is_local_structomorph_within_at_local_invariant_prop {H : Type u_1} [topological_space H] (G : structure_groupoid H) [closed_under_restriction G] : local_invariant_prop G G (is_local_structomorph_within_at G) := sorry
64edd0d0e4270080d16f05b795dd5f4eaffe5719
9dc8cecdf3c4634764a18254e94d43da07142918
/src/analysis/complex/abs_max.lean
9c42071ab16b7b661e86b00fbc8de3897fe53184
[ "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
22,019
lean
/- Copyright (c) 2022 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import analysis.complex.cauchy_integral import analysis.convex.integral import analysis.normed_space.completion import analysis.normed_space.extr import topology.algebra.order.extr_closure /-! # Maximum modulus principle In this file we prove several versions of the maximum modulus principle. There are several statements that can be called "the maximum modulus principle" for maps between normed complex spaces. They differ by assumptions on the domain (any space, a nontrivial space, a finite dimensional space), assumptions on the codomain (any space, a strictly convex space), and by conclusion (either equality of norms or of the values of the function). ## Main results ### Theorems for any codomain Consider a function `f : E → F` that is complex differentiable on a set `s`, is continuous on its closure, and `∥f x∥` has a maximum on `s` at `c`. We prove the following theorems. - `complex.norm_eq_on_closed_ball_of_is_max_on`: if `s = metric.ball c r`, then `∥f x∥ = ∥f c∥` for any `x` from the corresponding closed ball; - `complex.norm_eq_norm_of_is_max_on_of_ball_subset`: if `metric.ball c (dist w c) ⊆ s`, then `∥f w∥ = ∥f c∥`; - `complex.norm_eq_on_of_is_preconnected_of_is_max_on`: if `U` is an open (pre)connected set, `f` is complex differentiable on `U`, and `∥f x∥` has a maximum on `U` at `c ∈ U`, then `∥f x∥ = ∥f c∥` for all `x ∈ U`; - `complex.norm_eq_on_closure_of_is_preconnected_of_is_max_on`: if `s` is open and (pre)connected and `c ∈ s`, then `∥f x∥ = ∥f c∥` for all `x ∈ closure s`; - `complex.norm_eventually_eq_of_is_local_max`: if `f` is complex differentiable in a neighborhood of `c` and `∥f x∥` has a local maximum at `c`, then `∥f x∥` is locally a constant in a neighborhood of `c`. ### Theorems for a strictly convex codomain If the codomain `F` is a strictly convex space, then in the lemmas from the previous section we can prove `f w = f c` instead of `∥f w∥ = ∥f c∥`, see `complex.eq_on_of_is_preconnected_of_is_max_on_norm`, `complex.eq_on_closure_of_is_preconnected_of_is_max_on_norm`, `complex.eq_of_is_max_on_of_ball_subset`, `complex.eq_on_closed_ball_of_is_max_on_norm`, and `complex.eventually_eq_of_is_local_max_norm`. ### Values on the frontier Finally, we prove some corollaries that relate the (norm of the) values of a function on a set to its values on the frontier of the set. All these lemmas assume that `E` is a nontrivial space. In this section `f g : E → F` are functions that are complex differentiable on a bounded set `s` and are continuous on its closure. We prove the following theorems. - `complex.exists_mem_frontier_is_max_on_norm`: If `E` is a finite dimensional space and `s` is a nonempty bounded set, then there exists a point `z ∈ frontier s` such that `λ z, ∥f z∥` takes it maximum value on `closure s` at `z`. - `complex.norm_le_of_forall_mem_frontier_norm_le`: if `∥f z∥ ≤ C` for all `z ∈ frontier s`, then `∥f z∥ ≤ C` for all `z ∈ s`; note that this theorem does not require `E` to be a finite dimensional space. - `complex.eq_on_closure_of_eq_on_frontier`: if `f x = g x` on the frontier of `s`, then `f x = g x` on `closure s`; - `complex.eq_on_of_eq_on_frontier`: if `f x = g x` on the frontier of `s`, then `f x = g x` on `s`. ## Tags maximum modulus principle, complex analysis -/ open topological_space metric set filter asymptotics function measure_theory affine_map open_locale topological_space filter nnreal real universes u v w variables {E : Type u} [normed_add_comm_group E] [normed_space ℂ E] {F : Type v} [normed_add_comm_group F] [normed_space ℂ F] local postfix `̂`:100 := uniform_space.completion namespace complex /-! ### Auxiliary lemmas We split the proof into a series of lemmas. First we prove the principle for a function `f : ℂ → F` with an additional assumption that `F` is a complete space, then drop unneeded assumptions one by one. The lemmas with names `*_auxₙ` are considered to be private and should not be used outside of this file. -/ lemma norm_max_aux₁ [complete_space F] {f : ℂ → F} {z w : ℂ} (hd : diff_cont_on_cl ℂ f (ball z (dist w z))) (hz : is_max_on (norm ∘ f) (closed_ball z (dist w z)) z) : ∥f w∥ = ∥f z∥ := begin /- Consider a circle of radius `r = dist w z`. -/ set r : ℝ := dist w z, have hw : w ∈ closed_ball z r, from mem_closed_ball.2 le_rfl, /- Assume the converse. Since `∥f w∥ ≤ ∥f z∥`, we have `∥f w∥ < ∥f z∥`. -/ refine (is_max_on_iff.1 hz _ hw).antisymm (not_lt.1 _), rintro hw_lt : ∥f w∥ < ∥f z∥, have hr : 0 < r, from dist_pos.2 (ne_of_apply_ne (norm ∘ f) hw_lt.ne), /- Due to Cauchy integral formula, it suffices to prove the following inequality. -/ suffices : ∥∮ ζ in C(z, r), (ζ - z)⁻¹ • f ζ∥ < 2 * π * ∥f z∥, { refine this.ne _, have A : ∮ ζ in C(z, r), (ζ - z)⁻¹ • f ζ = (2 * π * I : ℂ) • f z := hd.circle_integral_sub_inv_smul (mem_ball_self hr), simp [A, norm_smul, real.pi_pos.le] }, suffices : ∥∮ ζ in C(z, r), (ζ - z)⁻¹ • f ζ∥ < 2 * π * r * (∥f z∥ / r), by rwa [mul_assoc, mul_div_cancel' _ hr.ne'] at this, /- This inequality is true because `∥(ζ - z)⁻¹ • f ζ∥ ≤ ∥f z∥ / r` for all `ζ` on the circle and this inequality is strict at `ζ = w`. -/ have hsub : sphere z r ⊆ closed_ball z r, from sphere_subset_closed_ball, refine circle_integral.norm_integral_lt_of_norm_le_const_of_lt hr _ _ ⟨w, rfl, _⟩, show continuous_on (λ (ζ : ℂ), (ζ - z)⁻¹ • f ζ) (sphere z r), { refine ((continuous_on_id.sub continuous_on_const).inv₀ _).smul (hd.continuous_on_ball.mono hsub), exact λ ζ hζ, sub_ne_zero.2 (ne_of_mem_sphere hζ hr.ne') }, show ∀ ζ ∈ sphere z r, ∥(ζ - z)⁻¹ • f ζ∥ ≤ ∥f z∥ / r, { rintros ζ (hζ : abs (ζ - z) = r), rw [le_div_iff hr, norm_smul, norm_inv, norm_eq_abs, hζ, mul_comm, mul_inv_cancel_left₀ hr.ne'], exact hz (hsub hζ) }, show ∥(w - z)⁻¹ • f w∥ < ∥f z∥ / r, { rw [norm_smul, norm_inv, norm_eq_abs, ← div_eq_inv_mul], exact (div_lt_div_right hr).2 hw_lt } end /-! Now we drop the assumption `complete_space F` by embedding `F` into its completion. -/ lemma norm_max_aux₂ {f : ℂ → F} {z w : ℂ} (hd : diff_cont_on_cl ℂ f (ball z (dist w z))) (hz : is_max_on (norm ∘ f) (closed_ball z (dist w z)) z) : ∥f w∥ = ∥f z∥ := begin set e : F →L[ℂ] F̂ := uniform_space.completion.to_complL, have he : ∀ x, ∥e x∥ = ∥x∥, from uniform_space.completion.norm_coe, replace hz : is_max_on (norm ∘ (e ∘ f)) (closed_ball z (dist w z)) z, by simpa only [is_max_on, (∘), he] using hz, simpa only [he] using norm_max_aux₁ (e.differentiable.comp_diff_cont_on_cl hd) hz end /-! Then we replace the assumption `is_max_on (norm ∘ f) (closed_ball z r) z` with a seemingly weaker assumption `is_max_on (norm ∘ f) (ball z r) z`. -/ lemma norm_max_aux₃ {f : ℂ → F} {z w : ℂ} {r : ℝ} (hr : dist w z = r) (hd : diff_cont_on_cl ℂ f (ball z r)) (hz : is_max_on (norm ∘ f) (ball z r) z) : ∥f w∥ = ∥f z∥ := begin subst r, rcases eq_or_ne w z with rfl|hne, { refl }, rw ← dist_ne_zero at hne, exact norm_max_aux₂ hd (closure_ball z hne ▸ hz.closure hd.continuous_on.norm) end /-! ### Maximum modulus principle for any codomain If we do not assume that the codomain is a strictly convex space, then we can only claim that the **norm** `∥f x∥` is locally constant. -/ /-! Finally, we generalize the theorem from a disk in `ℂ` to a closed ball in any normed space. -/ /-- **Maximum modulus principle** on a closed ball: if `f : E → F` is continuous on a closed ball, is complex differentiable on the corresponding open ball, and the norm `∥f w∥` takes its maximum value on the open ball at its center, then the norm `∥f w∥` is constant on the closed ball. -/ lemma norm_eq_on_closed_ball_of_is_max_on {f : E → F} {z : E} {r : ℝ} (hd : diff_cont_on_cl ℂ f (ball z r)) (hz : is_max_on (norm ∘ f) (ball z r) z) : eq_on (norm ∘ f) (const E ∥f z∥) (closed_ball z r) := begin intros w hw, rw [mem_closed_ball, dist_comm] at hw, rcases eq_or_ne z w with rfl|hne, { refl }, set e : ℂ → E := line_map z w, have hde : differentiable ℂ e := (differentiable_id.smul_const (w - z)).add_const z, suffices : ∥(f ∘ e) (1 : ℂ)∥ = ∥(f ∘ e) (0 : ℂ)∥, by simpa [e], have hr : dist (1 : ℂ) 0 = 1, by simp, have hball : maps_to e (ball 0 1) (ball z r), { refine ((lipschitz_with_line_map z w).maps_to_ball (mt nndist_eq_zero.1 hne) 0 1).mono subset.rfl _, simpa only [line_map_apply_zero, mul_one, coe_nndist] using ball_subset_ball hw }, exact norm_max_aux₃ hr (hd.comp hde.diff_cont_on_cl hball) (hz.comp_maps_to hball (line_map_apply_zero z w)) end /-- **Maximum modulus principle**: if `f : E → F` is complex differentiable on a set `s`, the norm of `f` takes it maximum on `s` at `z`, and `w` is a point such that the closed ball with center `z` and radius `dist w z` is included in `s`, then `∥f w∥ = ∥f z∥`. -/ lemma norm_eq_norm_of_is_max_on_of_ball_subset {f : E → F} {s : set E} {z w : E} (hd : diff_cont_on_cl ℂ f s) (hz : is_max_on (norm ∘ f) s z) (hsub : ball z (dist w z) ⊆ s) : ∥f w∥ = ∥f z∥ := norm_eq_on_closed_ball_of_is_max_on (hd.mono hsub) (hz.on_subset hsub) (mem_closed_ball.2 le_rfl) /-- **Maximum modulus principle**: if `f : E → F` is complex differentiable in a neighborhood of `c` and the norm `∥f z∥` has a local maximum at `c`, then `∥f z∥` is locally constant in a neighborhood of `c`. -/ lemma norm_eventually_eq_of_is_local_max {f : E → F} {c : E} (hd : ∀ᶠ z in 𝓝 c, differentiable_at ℂ f z) (hc : is_local_max (norm ∘ f) c) : ∀ᶠ y in 𝓝 c, ∥f y∥ = ∥f c∥ := begin rcases nhds_basis_closed_ball.eventually_iff.1 (hd.and hc) with ⟨r, hr₀, hr⟩, exact nhds_basis_closed_ball.eventually_iff.2 ⟨r, hr₀, norm_eq_on_closed_ball_of_is_max_on (differentiable_on.diff_cont_on_cl $ λ x hx, (hr $ closure_ball_subset_closed_ball hx).1.differentiable_within_at) (λ x hx, (hr $ ball_subset_closed_ball hx).2)⟩ end lemma is_open_set_of_mem_nhds_and_is_max_on_norm {f : E → F} {s : set E} (hd : differentiable_on ℂ f s) : is_open {z | s ∈ 𝓝 z ∧ is_max_on (norm ∘ f) s z} := begin refine is_open_iff_mem_nhds.2 (λ z hz, (eventually_eventually_nhds.2 hz.1).and _), replace hd : ∀ᶠ w in 𝓝 z, differentiable_at ℂ f w, from hd.eventually_differentiable_at hz.1, exact (norm_eventually_eq_of_is_local_max hd $ (hz.2.is_local_max hz.1)).mono (λ x hx y hy, le_trans (hz.2 hy) hx.ge) end /-- **Maximum modulus principle** on a connected set. Let `U` be a (pre)connected open set in a complex normed space. Let `f : E → F` be a function that is complex differentiable on `U`. Suppose that `∥f x∥` takes its maximum value on `U` at `c ∈ U`. Then `∥f x∥ = ∥f c∥` for all `x ∈ U`. -/ lemma norm_eq_on_of_is_preconnected_of_is_max_on {f : E → F} {U : set E} {c : E} (hc : is_preconnected U) (ho : is_open U) (hd : differentiable_on ℂ f U) (hcU : c ∈ U) (hm : is_max_on (norm ∘ f) U c) : eq_on (norm ∘ f) (const E ∥f c∥) U := begin set V := U ∩ {z | is_max_on (norm ∘ f) U z}, have hV : ∀ x ∈ V, ∥f x∥ = ∥f c∥, from λ x hx, le_antisymm (hm hx.1) (hx.2 hcU), suffices : U ⊆ V, from λ x hx, hV x (this hx), have hVo : is_open V, { simpa only [ho.mem_nhds_iff, set_of_and, set_of_mem_eq] using is_open_set_of_mem_nhds_and_is_max_on_norm hd }, have hVne : (U ∩ V).nonempty := ⟨c, hcU, hcU, hm⟩, set W := U ∩ {z | ∥f z∥ ≠ ∥f c∥}, have hWo : is_open W, from hd.continuous_on.norm.preimage_open_of_open ho is_open_ne, have hdVW : disjoint V W, from λ x ⟨hxV, hxW⟩, hxW.2 (hV x hxV), have hUVW : U ⊆ V ∪ W, from λ x hx, (eq_or_ne (∥f x∥) (∥f c∥)).imp (λ h, ⟨hx, λ y hy, (hm hy).out.trans_eq h.symm⟩) (and.intro hx), exact hc.subset_left_of_subset_union hVo hWo hdVW hUVW hVne, end /-- **Maximum modulus principle** on a connected set. Let `U` be a (pre)connected open set in a complex normed space. Let `f : E → F` be a function that is complex differentiable on `U` and is continuous on its closure. Suppose that `∥f x∥` takes its maximum value on `U` at `c ∈ U`. Then `∥f x∥ = ∥f c∥` for all `x ∈ closure U`. -/ lemma norm_eq_on_closure_of_is_preconnected_of_is_max_on {f : E → F} {U : set E} {c : E} (hc : is_preconnected U) (ho : is_open U) (hd : diff_cont_on_cl ℂ f U) (hcU : c ∈ U) (hm : is_max_on (norm ∘ f) U c) : eq_on (norm ∘ f) (const E ∥f c∥) (closure U) := (norm_eq_on_of_is_preconnected_of_is_max_on hc ho hd.differentiable_on hcU hm).of_subset_closure hd.continuous_on.norm continuous_on_const subset_closure subset.rfl section strict_convex /-! ### The case of a strictly convex codomain If the codomain `F` is a strictly convex space, then we can claim equalities like `f w = f z` instead of `∥f w∥ = ∥f z∥`. Instead of repeating the proof starting with lemmas about integrals, we apply a corresponding lemma above twice: for `f` and for `λ x, f x + f c`. Then we have `∥f w∥ = ∥f z∥` and `∥f w + f z∥ = ∥f z + f z∥`, thus `∥f w + f z∥ = ∥f w∥ + ∥f z∥`. This is only possible if `f w = f z`, see `eq_of_norm_eq_of_norm_add_eq`. -/ variables [strict_convex_space ℝ F] /-- **Maximum modulus principle** on a connected set. Let `U` be a (pre)connected open set in a complex normed space. Let `f : E → F` be a function that is complex differentiable on `U`. Suppose that `∥f x∥` takes its maximum value on `U` at `c ∈ U`. Then `f x = f c` for all `x ∈ U`. TODO: change assumption from `is_max_on` to `is_local_max`. -/ lemma eq_on_of_is_preconnected_of_is_max_on_norm {f : E → F} {U : set E} {c : E} (hc : is_preconnected U) (ho : is_open U) (hd : differentiable_on ℂ f U) (hcU : c ∈ U) (hm : is_max_on (norm ∘ f) U c) : eq_on f (const E (f c)) U := λ x hx, have H₁ : ∥f x∥ = ∥f c∥, from norm_eq_on_of_is_preconnected_of_is_max_on hc ho hd hcU hm hx, have H₂ : ∥f x + f c∥ = ∥f c + f c∥, from norm_eq_on_of_is_preconnected_of_is_max_on hc ho (hd.add_const _) hcU hm.norm_add_self hx, eq_of_norm_eq_of_norm_add_eq H₁ $ by simp only [H₂, same_ray.rfl.norm_add, H₁] /-- **Maximum modulus principle** on a connected set. Let `U` be a (pre)connected open set in a complex normed space. Let `f : E → F` be a function that is complex differentiable on `U` and is continuous on its closure. Suppose that `∥f x∥` takes its maximum value on `U` at `c ∈ U`. Then `f x = f c` for all `x ∈ closure U`. -/ lemma eq_on_closure_of_is_preconnected_of_is_max_on_norm {f : E → F} {U : set E} {c : E} (hc : is_preconnected U) (ho : is_open U) (hd : diff_cont_on_cl ℂ f U) (hcU : c ∈ U) (hm : is_max_on (norm ∘ f) U c) : eq_on f (const E (f c)) (closure U) := (eq_on_of_is_preconnected_of_is_max_on_norm hc ho hd.differentiable_on hcU hm).of_subset_closure hd.continuous_on continuous_on_const subset_closure subset.rfl /-- **Maximum modulus principle**. Let `f : E → F` be a function between complex normed spaces. Suppose that the codomain `F` is a strictly convex space, `f` is complex differentiable on a set `s`, `f` is continuous on the closure of `s`, the norm of `f` takes it maximum on `s` at `z`, and `w` is a point such that the closed ball with center `z` and radius `dist w z` is included in `s`, then `f w = f z`. -/ lemma eq_of_is_max_on_of_ball_subset {f : E → F} {s : set E} {z w : E} (hd : diff_cont_on_cl ℂ f s) (hz : is_max_on (norm ∘ f) s z) (hsub : ball z (dist w z) ⊆ s) : f w = f z := have H₁ : ∥f w∥ = ∥f z∥, from norm_eq_norm_of_is_max_on_of_ball_subset hd hz hsub, have H₂ : ∥f w + f z∥ = ∥f z + f z∥, from norm_eq_norm_of_is_max_on_of_ball_subset (hd.add_const _) hz.norm_add_self hsub, eq_of_norm_eq_of_norm_add_eq H₁ $ by simp only [H₂, same_ray.rfl.norm_add, H₁] /-- **Maximum modulus principle** on a closed ball. Suppose that a function `f : E → F` from a normed complex space to a strictly convex normed complex space has the following properties: - it is continuous on a closed ball `metric.closed_ball z r`, - it is complex differentiable on the corresponding open ball; - the norm `∥f w∥` takes its maximum value on the open ball at its center. Then `f` is a constant on the closed ball. -/ lemma eq_on_closed_ball_of_is_max_on_norm {f : E → F} {z : E} {r : ℝ} (hd : diff_cont_on_cl ℂ f (ball z r)) (hz : is_max_on (norm ∘ f) (ball z r) z) : eq_on f (const E (f z)) (closed_ball z r) := λ x hx, eq_of_is_max_on_of_ball_subset hd hz $ ball_subset_ball hx /-- **Maximum modulus principle**: if `f : E → F` is complex differentiable in a neighborhood of `c` and the norm `∥f z∥` has a local maximum at `c`, then `f` is locally constant in a neighborhood of `c`. -/ lemma eventually_eq_of_is_local_max_norm {f : E → F} {c : E} (hd : ∀ᶠ z in 𝓝 c, differentiable_at ℂ f z) (hc : is_local_max (norm ∘ f) c) : ∀ᶠ y in 𝓝 c, f y = f c := begin rcases nhds_basis_closed_ball.eventually_iff.1 (hd.and hc) with ⟨r, hr₀, hr⟩, exact nhds_basis_closed_ball.eventually_iff.2 ⟨r, hr₀, eq_on_closed_ball_of_is_max_on_norm (differentiable_on.diff_cont_on_cl $ λ x hx, (hr $ closure_ball_subset_closed_ball hx).1.differentiable_within_at) (λ x hx, (hr $ ball_subset_closed_ball hx).2)⟩ end end strict_convex /-! ### Maximum on a set vs maximum on its frontier In this section we prove corollaries of the maximum modulus principle that relate the values of a function on a set to its values on the frontier of this set. -/ variable [nontrivial E] /-- **Maximum modulus principle**: if `f : E → F` is complex differentiable on a nonempty bounded set `U` and is continuous on its closure, then there exists a point `z ∈ frontier U` such that `λ z, ∥f z∥` takes it maximum value on `closure U` at `z`. -/ lemma exists_mem_frontier_is_max_on_norm [finite_dimensional ℂ E] {f : E → F} {U : set E} (hb : bounded U) (hne : U.nonempty) (hd : diff_cont_on_cl ℂ f U) : ∃ z ∈ frontier U, is_max_on (norm ∘ f) (closure U) z := begin have hc : is_compact (closure U), from hb.is_compact_closure, obtain ⟨w, hwU, hle⟩ : ∃ w ∈ closure U, is_max_on (norm ∘ f) (closure U) w, from hc.exists_forall_ge hne.closure hd.continuous_on.norm, rw [closure_eq_interior_union_frontier, mem_union_eq] at hwU, cases hwU, rotate, { exact ⟨w, hwU, hle⟩ }, have : interior U ≠ univ, from ne_top_of_le_ne_top hc.ne_univ interior_subset_closure, rcases exists_mem_frontier_inf_dist_compl_eq_dist hwU this with ⟨z, hzU, hzw⟩, refine ⟨z, frontier_interior_subset hzU, λ x hx, (mem_set_of_eq.mp $ hle hx).trans_eq _⟩, refine (norm_eq_norm_of_is_max_on_of_ball_subset hd (hle.on_subset subset_closure) _).symm, rw [dist_comm, ← hzw], exact ball_inf_dist_compl_subset.trans interior_subset end /-- **Maximum modulus principle**: if `f : E → F` is complex differentiable on a bounded set `U` and `∥f z∥ ≤ C` for any `z ∈ frontier U`, then the same is true for any `z ∈ closure U`. -/ lemma norm_le_of_forall_mem_frontier_norm_le {f : E → F} {U : set E} (hU : bounded U) (hd : diff_cont_on_cl ℂ f U) {C : ℝ} (hC : ∀ z ∈ frontier U, ∥f z∥ ≤ C) {z : E} (hz : z ∈ closure U) : ∥f z∥ ≤ C := begin rw [closure_eq_self_union_frontier, union_comm, mem_union_eq] at hz, cases hz, { exact hC z hz }, /- In case of a finite dimensional domain, one can just apply `complex.exists_mem_frontier_is_max_on_norm`. To make it work in any Banach space, we restrict the function to a line first. -/ rcases exists_ne z with ⟨w, hne⟩, set e : ℂ → E := line_map z w, have hde : differentiable ℂ e := (differentiable_id.smul_const (w - z)).add_const z, have hL : antilipschitz_with (nndist z w)⁻¹ e, from antilipschitz_with_line_map hne.symm, replace hd : diff_cont_on_cl ℂ (f ∘ e) (e ⁻¹' U), from hd.comp hde.diff_cont_on_cl (maps_to_preimage _ _), have h₀ : (0 : ℂ) ∈ e ⁻¹' U, by simpa only [e, mem_preimage, line_map_apply_zero], rcases exists_mem_frontier_is_max_on_norm (hL.bounded_preimage hU) ⟨0, h₀⟩ hd with ⟨ζ, hζU, hζ⟩, calc ∥f z∥ = ∥f (e 0)∥ : by simp only [e, line_map_apply_zero] ... ≤ ∥f (e ζ)∥ : hζ (subset_closure h₀) ... ≤ C : hC _ (hde.continuous.frontier_preimage_subset _ hζU) end /-- If two complex differentiable functions `f g : E → F` are equal on the boundary of a bounded set `U`, then they are equal on `closure U`. -/ lemma eq_on_closure_of_eq_on_frontier {f g : E → F} {U : set E} (hU : bounded U) (hf : diff_cont_on_cl ℂ f U) (hg : diff_cont_on_cl ℂ g U) (hfg : eq_on f g (frontier U)) : eq_on f g (closure U) := begin suffices H : ∀ z ∈ closure U, ∥(f - g) z∥ ≤ 0, by simpa [sub_eq_zero] using H, refine λ z hz, norm_le_of_forall_mem_frontier_norm_le hU (hf.sub hg) (λ w hw, _) hz, simp [hfg hw] end /-- If two complex differentiable functions `f g : E → F` are equal on the boundary of a bounded set `U`, then they are equal on `U`. -/ lemma eq_on_of_eq_on_frontier {f g : E → F} {U : set E} (hU : bounded U) (hf : diff_cont_on_cl ℂ f U) (hg : diff_cont_on_cl ℂ g U) (hfg : eq_on f g (frontier U)) : eq_on f g U := (eq_on_closure_of_eq_on_frontier hU hf hg hfg).mono subset_closure end complex
1a4ddaa8a779162981966622d90c03adc5a0193d
6fca17f8d5025f89be1b2d9d15c9e0c4b4900cbf
/src/game/world4/level2.lean
54f961fc49df771345c775906a8f8982955c6ea2
[ "Apache-2.0" ]
permissive
arolihas/natural_number_game
4f0c93feefec93b8824b2b96adff8b702b8b43ce
8e4f7b4b42888a3b77429f90cce16292bd288138
refs/heads/master
1,621,872,426,808
1,586,270,467,000
1,586,270,467,000
253,648,466
0
0
null
1,586,219,694,000
1,586,219,694,000
null
UTF-8
Lean
false
false
277
lean
import game.world4.level1 -- hide namespace mynat -- hide /- # Power World ## Level 2: `zero_pow_succ` -/ /- Lemma For all naturals $m$, $0 ^{succ (m)} = 0$. -/ lemma zero_pow_succ (m : mynat) : (0 : mynat) ^ (succ m) = 0 := begin [nat_num_game] end end mynat -- hide
9bbd93be6675b9b15ddf57e400e321e5931338f1
c777c32c8e484e195053731103c5e52af26a25d1
/src/number_theory/modular_forms/slash_invariant_forms.lean
98b6074ce71eef42d1645e322b05230cadcfe5d1
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
6,316
lean
/- Copyright (c) 2022 Chris Birkbeck. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Birkbeck -/ import number_theory.modular_forms.slash_actions /-! # Slash invariant forms This file defines functions that are invariant under a `slash_action` which forms the basis for defining `modular_form` and `cusp_form`. We prove several instances for such spaces, in particular that they form a module. -/ open complex upper_half_plane open_locale upper_half_plane modular_form noncomputable theory local prefix `↑ₘ`:1024 := @coe _ (matrix (fin 2) (fin 2) _) _ -- like `↑ₘ`, but allows the user to specify the ring `R`. Useful to help Lean elaborate. local notation `↑ₘ[` R `]` := @coe _ (matrix (fin 2) (fin 2) R) _ local notation `GL(` n `, ` R `)`⁺ := matrix.GL_pos (fin n) R local notation `SL(` n `, ` R `)` := matrix.special_linear_group (fin n) R section slash_invariant_forms set_option old_structure_cmd true open modular_form variables (F : Type*) (Γ : out_param $ subgroup SL(2, ℤ)) (k : out_param ℤ) /--Functions `ℍ → ℂ` that are invariant under the `slash_action`. -/ structure slash_invariant_form := (to_fun : ℍ → ℂ) (slash_action_eq' : ∀ γ : Γ, to_fun ∣[k] γ = to_fun) /--`slash_invariant_form_class F Γ k` asserts `F` is a type of bundled functions that are invariant under the `slash_action`. -/ class slash_invariant_form_class extends fun_like F ℍ (λ _, ℂ) := (slash_action_eq : ∀ (f : F) (γ : Γ), (f : ℍ → ℂ) ∣[k] γ = f) attribute [nolint dangerous_instance] slash_invariant_form_class.to_fun_like @[priority 100] instance slash_invariant_form_class.slash_invariant_form : slash_invariant_form_class (slash_invariant_form Γ k) Γ k := { coe := slash_invariant_form.to_fun, coe_injective' := λ f g h, by cases f; cases g; congr', slash_action_eq := slash_invariant_form.slash_action_eq' } variables {F Γ k} instance : has_coe_to_fun (slash_invariant_form Γ k) (λ _, ℍ → ℂ) := fun_like.has_coe_to_fun @[simp] lemma slash_invariant_form_to_fun_eq_coe {f : slash_invariant_form Γ k} : f.to_fun = (f : ℍ → ℂ) := rfl @[ext] theorem slash_invariant_form_ext {f g : slash_invariant_form Γ k} (h : ∀ x, f x = g x) : f = g := fun_like.ext f g h /-- Copy of a `slash_invariant_form` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def slash_invariant_form.copy (f : slash_invariant_form Γ k) (f' : ℍ → ℂ) (h : f' = ⇑f) : slash_invariant_form Γ k := { to_fun := f', slash_action_eq' := h.symm ▸ f.slash_action_eq',} end slash_invariant_forms namespace slash_invariant_form open slash_invariant_form variables {F : Type*} {Γ : out_param $ subgroup SL(2, ℤ)} {k : out_param ℤ} @[priority 100, nolint dangerous_instance] instance slash_invariant_form_class.coe_to_fun [slash_invariant_form_class F Γ k] : has_coe_to_fun F (λ _, ℍ → ℂ) := fun_like.has_coe_to_fun @[simp] lemma slash_action_eqn [slash_invariant_form_class F Γ k] (f : F) (γ : Γ) : ⇑f ∣[k] γ = ⇑f := slash_invariant_form_class.slash_action_eq f γ lemma slash_action_eqn' (k : ℤ) (Γ : subgroup SL(2, ℤ)) [slash_invariant_form_class F Γ k] (f : F) (γ : Γ) (z : ℍ) : f (γ • z) = ((↑ₘ[ℤ]γ 1 0 : ℂ) * z +(↑ₘ[ℤ]γ 1 1 : ℂ))^k * f z := begin rw ←modular_form.slash_action_eq'_iff, simp, end instance [slash_invariant_form_class F Γ k] : has_coe_t F (slash_invariant_form Γ k) := ⟨λ f, { to_fun := f, slash_action_eq' := slash_action_eqn f }⟩ @[simp] lemma slash_invariant_form_class.coe_coe [slash_invariant_form_class F Γ k] (f : F) : ((f : slash_invariant_form Γ k) : ℍ → ℂ) = f := rfl instance has_add : has_add (slash_invariant_form Γ k) := ⟨ λ f g, { to_fun := f + g, slash_action_eq' := λ γ, by rw [slash_action.add_slash, slash_action_eqn, slash_action_eqn] }⟩ @[simp] lemma coe_add (f g : slash_invariant_form Γ k) : ⇑(f + g) = f + g := rfl @[simp] lemma add_apply (f g : slash_invariant_form Γ k) (z : ℍ) : (f + g) z = f z + g z := rfl instance has_zero : has_zero (slash_invariant_form Γ k) := ⟨ { to_fun := 0, slash_action_eq' := slash_action.zero_slash _} ⟩ @[simp] lemma coe_zero : ⇑(0 : slash_invariant_form Γ k) = (0 : ℍ → ℂ) := rfl section variables {α : Type*} [has_smul α ℂ] [is_scalar_tower α ℂ ℂ] instance has_smul : has_smul α (slash_invariant_form Γ k) := ⟨ λ c f, { to_fun := c • f, slash_action_eq' := λ γ, by rw [slash_action.smul_slash_of_tower, slash_action_eqn] }⟩ @[simp] lemma coe_smul (f : slash_invariant_form Γ k) (n : α) : ⇑(n • f) = n • f := rfl @[simp] lemma smul_apply (f : slash_invariant_form Γ k) (n : α) (z : ℍ) : (n • f) z = n • (f z) := rfl end instance has_neg : has_neg (slash_invariant_form Γ k) := ⟨ λ f, { to_fun := -f, slash_action_eq' := λ γ, by rw [slash_action.neg_slash, slash_action_eqn] } ⟩ @[simp] lemma coe_neg (f : slash_invariant_form Γ k) : ⇑(-f) = -f := rfl @[simp] lemma neg_apply (f : slash_invariant_form Γ k) (z : ℍ) : (-f) z = - (f z) := rfl instance has_sub : has_sub (slash_invariant_form Γ k) := ⟨ λ f g, f + -g ⟩ @[simp] lemma coe_sub (f g : slash_invariant_form Γ k) : ⇑(f - g) = f - g := rfl @[simp] lemma sub_apply (f g : slash_invariant_form Γ k) (z : ℍ) : (f - g) z = f z - g z := rfl instance : add_comm_group (slash_invariant_form Γ k) := fun_like.coe_injective.add_comm_group _ rfl coe_add coe_neg coe_sub coe_smul coe_smul /--Additive coercion from `slash_invariant_form` to `ℍ → ℂ`.-/ def coe_hom : slash_invariant_form Γ k →+ (ℍ → ℂ) := { to_fun := λ f, f, map_zero' := rfl, map_add' := λ _ _, rfl } lemma coe_hom_injective : function.injective (@coe_hom Γ k) := fun_like.coe_injective instance : module ℂ (slash_invariant_form Γ k) := coe_hom_injective.module ℂ coe_hom (λ _ _, rfl) instance : has_one (slash_invariant_form Γ 0) := ⟨ { to_fun := 1, slash_action_eq' := λ A, modular_form.is_invariant_one A } ⟩ @[simp] lemma one_coe_eq_one : ((1 : slash_invariant_form Γ 0) : ℍ → ℂ) = 1 := rfl instance : inhabited (slash_invariant_form Γ k) := ⟨0⟩ end slash_invariant_form
1b4c5ae665f5415898aca1eeb613fa685dd72af0
4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d
/src/Lean/Parser/Extra.lean
af88d4416363e5ae095b190dcfa759d7d3ee0519
[ "Apache-2.0" ]
permissive
subfish-zhou/leanprover-zh_CN.github.io
30b9fba9bd790720bd95764e61ae796697d2f603
8b2985d4a3d458ceda9361ac454c28168d920d3f
refs/heads/master
1,689,709,967,820
1,632,503,056,000
1,632,503,056,000
409,962,097
1
0
null
null
null
null
UTF-8
Lean
false
false
5,131
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Parser.Extension -- necessary for auto-generation import Lean.PrettyPrinter.Parenthesizer import Lean.PrettyPrinter.Formatter namespace Lean namespace Parser -- synthesize pretty printers for parsers declared prior to `Lean.PrettyPrinter` -- (because `Parser.Extension` depends on them) attribute [runBuiltinParserAttributeHooks] leadingNode termParser commandParser mkAntiquot nodeWithAntiquot sepBy sepBy1 unicodeSymbol nonReservedSymbol @[runBuiltinParserAttributeHooks] def optional (p : Parser) : Parser := optionalNoAntiquot (withAntiquotSpliceAndSuffix `optional p (symbol "?")) @[runBuiltinParserAttributeHooks] def many (p : Parser) : Parser := manyNoAntiquot (withAntiquotSpliceAndSuffix `many p (symbol "*")) @[runBuiltinParserAttributeHooks] def many1 (p : Parser) : Parser := many1NoAntiquot (withAntiquotSpliceAndSuffix `many p (symbol "*")) @[runBuiltinParserAttributeHooks] def ident : Parser := withAntiquot (mkAntiquot "ident" identKind) identNoAntiquot -- `ident` and `rawIdent` produce the same syntax tree, so we reuse the antiquotation kind name @[runBuiltinParserAttributeHooks] def rawIdent : Parser := withAntiquot (mkAntiquot "ident" identKind) rawIdentNoAntiquot @[runBuiltinParserAttributeHooks] def numLit : Parser := withAntiquot (mkAntiquot "numLit" numLitKind) numLitNoAntiquot @[runBuiltinParserAttributeHooks] def scientificLit : Parser := withAntiquot (mkAntiquot "scientificLit" scientificLitKind) scientificLitNoAntiquot @[runBuiltinParserAttributeHooks] def strLit : Parser := withAntiquot (mkAntiquot "strLit" strLitKind) strLitNoAntiquot @[runBuiltinParserAttributeHooks] def charLit : Parser := withAntiquot (mkAntiquot "charLit" charLitKind) charLitNoAntiquot @[runBuiltinParserAttributeHooks] def nameLit : Parser := withAntiquot (mkAntiquot "nameLit" nameLitKind) nameLitNoAntiquot @[runBuiltinParserAttributeHooks, inline] def group (p : Parser) : Parser := node groupKind p @[runBuiltinParserAttributeHooks, inline] def many1Indent (p : Parser) : Parser := withPosition $ many1 (checkColGe "irrelevant" >> p) @[runBuiltinParserAttributeHooks, inline] def manyIndent (p : Parser) : Parser := withPosition $ many (checkColGe "irrelevant" >> p) @[runBuiltinParserAttributeHooks] abbrev notSymbol (s : String) : Parser := notFollowedBy (symbol s) s /-- No-op parser that advises the pretty printer to emit a non-breaking space. -/ @[inline] def ppHardSpace : Parser := skip /-- No-op parser that advises the pretty printer to emit a space/soft line break. -/ @[inline] def ppSpace : Parser := skip /-- No-op parser that advises the pretty printer to emit a hard line break. -/ @[inline] def ppLine : Parser := skip /-- No-op parser combinator that advises the pretty printer to group and indent the given syntax. By default, only syntax categories are grouped. -/ @[inline] def ppGroup : Parser → Parser := id /-- No-op parser combinator that advises the pretty printer to indent the given syntax without grouping it. -/ @[inline] def ppIndent : Parser → Parser := id /-- No-op parser combinator that advises the pretty printer to dedent the given syntax. Dedenting can in particular be used to counteract automatic indentation. -/ @[inline] def ppDedent : Parser → Parser := id end Parser section open PrettyPrinter @[combinatorFormatter Lean.Parser.ppHardSpace] def ppHardSpace.formatter : Formatter := Formatter.push " " @[combinatorFormatter Lean.Parser.ppSpace] def ppSpace.formatter : Formatter := Formatter.pushLine @[combinatorFormatter Lean.Parser.ppLine] def ppLine.formatter : Formatter := Formatter.push "\n" @[combinatorFormatter Lean.Parser.ppGroup] def ppGroup.formatter (p : Formatter) : Formatter := Formatter.group $ Formatter.indent p @[combinatorFormatter Lean.Parser.ppIndent] def ppIndent.formatter (p : Formatter) : Formatter := Formatter.indent p @[combinatorFormatter Lean.Parser.ppDedent] def ppDedent.formatter (p : Formatter) : Formatter := do let opts ← getOptions Formatter.indent p (some ((0:Int) - Std.Format.getIndent opts)) end namespace Parser -- now synthesize parenthesizers attribute [runBuiltinParserAttributeHooks] ppHardSpace ppSpace ppLine ppGroup ppIndent ppDedent macro "register_parser_alias" aliasName?:optional(strLit) declName:ident : term => let aliasName := aliasName?.getD (Syntax.mkStrLit declName.getId.toString) `(do Parser.registerAlias $aliasName $declName PrettyPrinter.Formatter.registerAlias $aliasName $(mkIdentFrom declName (declName.getId ++ `formatter)) PrettyPrinter.Parenthesizer.registerAlias $aliasName $(mkIdentFrom declName (declName.getId ++ `parenthesizer))) builtin_initialize register_parser_alias group register_parser_alias ppHardSpace register_parser_alias ppSpace register_parser_alias ppLine register_parser_alias ppGroup register_parser_alias ppIndent register_parser_alias ppDedent end Parser end Lean
8dd4f7b945e9fca88c7aff7119136f72de6b5430
88fb7558b0636ec6b181f2a548ac11ad3919f8a5
/tests/lean/run/elab_crash1.lean
ffcd4d9816a4f9417885be6e0e50df41e43c16f0
[ "Apache-2.0" ]
permissive
moritayasuaki/lean
9f666c323cb6fa1f31ac597d777914aed41e3b7a
ae96ebf6ee953088c235ff7ae0e8c95066ba8001
refs/heads/master
1,611,135,440,814
1,493,852,869,000
1,493,852,869,000
90,269,903
0
0
null
1,493,906,291,000
1,493,906,291,000
null
UTF-8
Lean
false
false
321
lean
open expr tactic meta definition to_expr_target (a : pexpr) : tactic expr := do tgt ← target, to_expr `((%%a : %%tgt)) example (A : Type) (a : A) : A := by do to_expr_target `(sorry) >>= exact example (A : Type) (a : A) : A := by do refine `(sorry) example (a : nat) : nat := by do to_expr `(nat.zero) >>= exact
d66a78d6019212fdf74a5e460d36426e98905c66
491068d2ad28831e7dade8d6dff871c3e49d9431
/library/theories/group_theory/hom.lean
e13ae3f9f60e8dbca589f3caade4d307e493b38c
[ "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
7,140
lean
/- Copyright (c) 2015 Haitao Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author : Haitao Zhang -/ import algebra.group data.set .subgroup namespace group open algebra -- ⁻¹ in eq.ops conflicts with group ⁻¹ -- open eq.ops notation H1 ▸ H2 := eq.subst H1 H2 open set open function open group.ops open quot local attribute set [reducible] section defs variables {A B : Type} variable [s1 : group A] variable [s2 : group B] include s1 include s2 -- the Prop of being hom definition homomorphic [reducible] (f : A → B) : Prop := ∀ a b, f (a*b) = (f a)*(f b) -- type class for inference structure is_hom_class [class] (f : A → B) : Type := (is_hom : homomorphic f) -- the proof of hom_prop if the class can be inferred definition is_hom (f : A → B) [h : is_hom_class f] : homomorphic f := @is_hom_class.is_hom A B s1 s2 f h definition ker (f : A → B) [h : is_hom_class f] : set A := {a : A | f a = 1} definition isomorphic (f : A → B) := injective f ∧ homomorphic f structure is_iso_class [class] (f : A → B) extends is_hom_class f : Type := (inj : injective f) lemma iso_is_inj (f : A → B) [h : is_iso_class f] : injective f:= @is_iso_class.inj A B s1 s2 f h lemma iso_is_iso (f : A → B) [h : is_iso_class f] : isomorphic f:= and.intro (iso_is_inj f) (is_hom f) end defs section variables {A B : Type} variable [s1 : group A] definition id_is_iso [instance] : @is_hom_class A A s1 s1 (@id A) := is_iso_class.mk (take a b, rfl) injective_id variable [s2 : group B] include s1 include s2 variable f : A → B variable [h : is_hom_class f] include h theorem hom_map_one : f 1 = 1 := have P : f 1 = (f 1) * (f 1), from calc f 1 = f (1*1) : mul_one ... = (f 1) * (f 1) : is_hom f, eq.symm (mul.right_inv (f 1) ▸ (mul_inv_eq_of_eq_mul P)) theorem hom_map_inv (a : A) : f a⁻¹ = (f a)⁻¹ := assert P : f 1 = 1, from hom_map_one f, assert P1 : f (a⁻¹ * a) = 1, from (eq.symm (mul.left_inv a)) ▸ P, assert P2 : (f a⁻¹) * (f a) = 1, from (is_hom f a⁻¹ a) ▸ P1, assert P3 : (f a⁻¹) * (f a) = (f a)⁻¹ * (f a), from eq.symm (mul.left_inv (f a)) ▸ P2, mul_right_cancel P3 theorem hom_map_mul_closed (H : set A) : mul_closed_on H → mul_closed_on (f '[H]) := assume Pclosed, assume b1, assume b2, assume Pb1 : b1 ∈ f '[ H], assume Pb2 : b2 ∈ f '[ H], obtain a1 (Pa1 : a1 ∈ H ∧ f a1 = b1), from Pb1, obtain a2 (Pa2 : a2 ∈ H ∧ f a2 = b2), from Pb2, assert Pa1a2 : a1 * a2 ∈ H, from Pclosed a1 a2 (and.left Pa1) (and.left Pa2), assert Pb1b2 : f (a1 * a2) = b1 * b2, from calc f (a1 * a2) = f a1 * f a2 : is_hom f a1 a2 ... = b1 * f a2 : {and.right Pa1} ... = b1 * b2 : {and.right Pa2}, mem_image Pa1a2 Pb1b2 lemma ker.has_one : 1 ∈ ker f := hom_map_one f lemma ker.has_inv : subgroup.has_inv (ker f) := take a, assume Pa : f a = 1, calc f a⁻¹ = (f a)⁻¹ : by rewrite (hom_map_inv f) ... = 1⁻¹ : by rewrite Pa ... = 1 : by rewrite one_inv lemma ker.mul_closed : mul_closed_on (ker f) := take x y, assume (Px : f x = 1) (Py : f y = 1), calc f (x*y) = (f x) * (f y) : by rewrite [is_hom f] ... = 1 : by rewrite [Px, Py, mul_one] lemma ker.normal : same_left_right_coset (ker f) := take a, funext (assume x, begin esimp [ker, set_of, glcoset, grcoset], rewrite [*(is_hom f), mul_eq_one_iff_mul_eq_one (f a⁻¹) (f x)] end) definition ker_is_normal_subgroup : is_normal_subgroup (ker f) := is_normal_subgroup.mk (ker.has_one f) (ker.mul_closed f) (ker.has_inv f) (ker.normal f) -- additional subgroup variable variable {H : set A} variable [is_subgH : is_subgroup H] include is_subgH theorem hom_map_subgroup : is_subgroup (f '[H]) := have Pone : 1 ∈ f '[H], from mem_image subg_has_one (hom_map_one f), have Pclosed : mul_closed_on (f '[H]), from hom_map_mul_closed f H subg_mul_closed, assert Pinv : ∀ b, b ∈ f '[H] → b⁻¹ ∈ f '[H], from assume b, assume Pimg, obtain a (Pa : a ∈ H ∧ f a = b), from Pimg, assert Painv : a⁻¹ ∈ H, from subg_has_inv a (and.left Pa), assert Pfainv : (f a)⁻¹ ∈ f '[H], from mem_image Painv (hom_map_inv f a), and.right Pa ▸ Pfainv, is_subgroup.mk Pone Pclosed Pinv end section hom_theorem variables {A B : Type} variable [s1 : group A] variable [s2 : group B] include s1 include s2 variable {f : A → B} variable [h : is_hom_class f] include h definition ker_nsubg [instance] : is_normal_subgroup (ker f) := is_normal_subgroup.mk (ker.has_one f) (ker.mul_closed f) (ker.has_inv f) (ker.normal f) definition quot_over_ker [instance] : group (coset_of (ker f)) := mk_quotient_group (ker f) -- under the wrap the tower of concepts collapse to a simple condition example (a x : A) : (x ∈ a ∘> ker f) = (f (a⁻¹*x) = 1) := rfl lemma ker_coset_same_val (a b : A): same_lcoset (ker f) a b → f a = f b := assume Psame, assert Pin : f (b⁻¹*a) = 1, from subg_same_lcoset_in_lcoset a b Psame, assert P : (f b)⁻¹ * (f a) = 1, from calc (f b)⁻¹ * (f a) = (f b⁻¹) * (f a) : (hom_map_inv f) ... = f (b⁻¹*a) : by rewrite [is_hom f] ... = 1 : by rewrite Pin, eq.symm (inv_inv (f b) ▸ inv_eq_of_mul_eq_one P) definition ker_natural_map : (coset_of (ker f)) → B := quot.lift f ker_coset_same_val example (a : A) : ker_natural_map ⟦a⟧ = f a := rfl lemma ker_coset_hom (a b : A) : ker_natural_map (⟦a⟧*⟦b⟧) = (ker_natural_map ⟦a⟧) * (ker_natural_map ⟦b⟧) := calc ker_natural_map (⟦a⟧*⟦b⟧) = ker_natural_map ⟦a*b⟧ : rfl ... = f (a*b) : rfl ... = (f a) * (f b) : by rewrite [is_hom f] ... = (ker_natural_map ⟦a⟧) * (ker_natural_map ⟦b⟧) : rfl lemma ker_map_is_hom : homomorphic (ker_natural_map : coset_of (ker f) → B) := take aK bK, quot.ind (λ a, quot.ind (λ b, ker_coset_hom a b) bK) aK lemma ker_coset_inj (a b : A) : (ker_natural_map ⟦a⟧ = ker_natural_map ⟦b⟧) → ⟦a⟧ = ⟦b⟧ := assume Pfeq : f a = f b, assert Painb : a ∈ b ∘> ker f, from calc f (b⁻¹*a) = (f b⁻¹) * (f a) : by rewrite [is_hom f] ... = (f b)⁻¹ * (f a) : by rewrite (hom_map_inv f) ... = (f a)⁻¹ * (f a) : by rewrite Pfeq ... = 1 : by rewrite (mul.left_inv (f a)), quot.sound (@subg_in_lcoset_same_lcoset _ _ (ker f) _ a b Painb) lemma ker_map_is_inj : injective (ker_natural_map : coset_of (ker f) → B) := take aK bK, quot.ind (λ a, quot.ind (λ b, ker_coset_inj a b) bK) aK -- a special case of the fundamental homomorphism theorem or the first isomorphism theorem theorem first_isomorphism_theorem : isomorphic (ker_natural_map : coset_of (ker f) → B) := and.intro ker_map_is_inj ker_map_is_hom end hom_theorem end group
d9c4a47ee5350ce512d3f0397cb7bce948784377
ea80d7bb31b9673a3a06d5148363b44b66c53796
/thys/core/pre.lean
36c40364956bad438b1833c9db1f8346f40318f4
[]
no_license
gitter-badger/electrolysis
2a59d6e0fe1b6629a14a1202e31b1a8ff1c93ced
4f63846e817cb52bdac4ae65ef3d17634e6ffc36
refs/heads/master
1,608,825,996,259
1,467,154,609,000
1,467,154,609,000
62,184,345
0
0
null
null
null
null
UTF-8
Lean
false
false
7,113
lean
import data.nat data.list import move open bool open eq.ops open int open nat open option open [notation] partial open prod open prod.ops open sum open option notation `do` binder ` ← ` x `; ` r:(scoped f, option.bind f x) := r open [class] classical -- a general loop combinator for separating tail-recursive definitions from their well-foundedness proofs section parameters {State Res : Type} parameters (body : State → State + Res) section parameter (R : State → State → Prop) private definition State' := State + Res private definition R' [unfold 4] : State' → State' → Prop | (inl s') (inl s) := R s' s | _ _ := false private definition R'.wf [trans_instance] [H : well_founded R] : well_founded R' := let f := sum.rec some (λr, none) in have subrelation R' (partial.inv_image R f), begin intro x y R'xy, cases x, cases y, repeat (apply R'xy), end, subrelation.wf this (partial.inv_image.wf f H) private noncomputable definition F (x : State') (f : Π (x' : State'), R' x' x → option State') : option State' := do s ← sum.inl_opt x; match body s with | inr r := some (inr r) | x' := if H : R' x' x then f x' H else none end protected noncomputable definition loop.fix [Hwf: well_founded R] (s : State) : option Res := do x ← well_founded.fix F (inl s); sum.inr_opt x private noncomputable definition term_rel (s : State) := if Hwf : well_founded R then loop.fix s ≠ none else false end noncomputable definition loop (s : State) : option Res := if Hex : ∃ R, term_rel R s then @loop.fix (classical.some Hex) (classical.dite_else_false (classical.some_spec Hex)) s else none parameter {body} protected theorem loop.fix_eq {R : State → State → Prop} [Hwf_R : well_founded R] {s : State} : loop.fix R s = match body s with | inl s' := if R s' s then loop.fix R s' else none | inr r := some r end := begin rewrite [↑loop.fix, well_founded.fix_eq, ↑F at {2}], cases body s with s' r, { esimp, cases classical.prop_decidable (R s' s), esimp, esimp }, { esimp } end private lemma fix_eq_fix {R₁ R₂ : State → State → Prop} [Hwf_R₁ : well_founded R₁] [well_founded R₂] {s : State} (Hterm₁ : loop.fix R₁ s ≠ none) (Hterm₂ : loop.fix R₂ s ≠ none) : loop.fix R₁ s = loop.fix R₂ s := begin revert Hterm₁ Hterm₂, induction (well_founded.apply Hwf_R₁ s) with s acc ih, rewrite [↑loop.fix, well_founded.fix_eq (F R₁), well_founded.fix_eq (F R₂), ↑F at {2, 4}], cases body s with s' r, { esimp, cases classical.prop_decidable (R₁ s' s) with HR₁, { cases classical.prop_decidable (R₂ s' s) with HR₂ HnR₂, { esimp, intro Hterm₁ Hterm₂, apply ih _ HR₁ Hterm₁ Hterm₂ }, { esimp, intro Hterm₁ Hterm₂, exfalso, apply Hterm₂ rfl } }, { esimp, intro Hterm₁ Hterm₂, exfalso, apply Hterm₁ rfl } }, { intros, apply rfl } end protected theorem loop.fix_eq_loop {R : State → State → Prop} [Hwf_R : well_founded R] {s : State} (Hterm : loop.fix R s ≠ none) : loop.fix R s = loop s := have Hterm_rel : ∃ R, term_rel R s, begin existsi R, rewrite [↑term_rel, dif_pos _], assumption end, let R₀ := classical.some Hterm_rel in have well_founded R₀, from classical.dite_else_false (classical.some_spec Hterm_rel), have loop.fix R₀ s ≠ none, from dif_pos this ▸ classical.some_spec Hterm_rel, begin rewrite [↑loop, dif_pos Hterm_rel], apply fix_eq_fix Hterm this, end end -- lifting loop to partial body functions section parameters {State Res : Type} parameters (body : State ⇀ State + Res) parameter (R : State → State → Prop) parameter [well_founded R] variable (s : State) private definition body' : State + option Res := match body s with | some (inl s') := inl s' | some (inr r) := inr (some r) | none := inr none end protected noncomputable definition loop'.fix := do res ← loop.fix body' R s; res noncomputable definition loop' : option Res := do res ← loop body' s; res parameters {body} protected theorem loop'.fix_eq : loop'.fix s = match body s with | some (inl s') := if R s' s then loop'.fix s' else none | some (inr r) := some r | none := none end := begin rewrite [↑loop'.fix, loop.fix_eq, ↑body'], apply generalize_with_eq (body s), intro b, cases b with x', { intro, apply rfl }, { intro, cases x' with s' r, { esimp, cases classical.prop_decidable (R s' s), esimp, esimp }, esimp } end theorem loop'.fix_eq_loop' (Hterm : loop'.fix s ≠ none) : loop'.fix s = loop' s := have loop.fix body' R s ≠ none, begin intro Hcontr, esimp [loop'.fix] at Hterm, apply (Hcontr ▸ Hterm) rfl end, begin rewrite [↑loop', ↑loop'.fix, loop.fix_eq_loop this] end end abbreviation u8 [parsing_only] := nat abbreviation u16 [parsing_only] := nat abbreviation u32 [parsing_only] := nat abbreviation u64 [parsing_only] := nat abbreviation usize [parsing_only] := nat abbreviation slice [parsing_only] := list definition checked.sub (n : nat) (m : nat) := if n ≥ m then some (n-m) else none definition checked.div (n : nat) (m : nat) := if m ≠ 0 then some (div n m) else none definition checked.mod (n : nat) (m : nat) := if m ≠ 0 then some (mod n m) else none /- TODO: actually check something -/ definition checked.shl (n : nat) (m : nat) := some (n * 2^m) definition checked.shr (n : nat) (m : int) := some (div n (2^nat.of_int m)) namespace core abbreviation intrinsics.add_with_overflow (n : nat) (m : nat) := some (n + m, false) abbreviation mem.swap {T : Type} (x y : T) := some (unit.star,y,x) abbreviation slice._T_.slice_SliceExt.len {T : Type} (self : slice T) := some (list.length self) abbreviation slice._T_.slice_SliceExt.get_unchecked [parsing_only] {T : Type} (self : slice T) (index : usize) := list.nth self index namespace ops structure FnOnce [class] (Args : Type) (Self : Type) (Output : Type) := (call_once : Self → Args → option (Output)) -- easy without mutable closures abbreviation FnMut [parsing_only] := FnOnce abbreviation Fn := FnOnce definition FnMut.call_mut [unfold_full] (Args : Type) (Self : Type) (Output : Type) [FnOnce : FnOnce Args Self Output] : Self → Args → option (Output × Self) := λself x, do y ← @FnOnce.call_once Args Self Output FnOnce self x; some (y, self) definition Fn.call (Args : Type) (Self : Type) (Output : Type) [FnMut : FnMut Args Self Output] : Self → Args → option Output := @FnOnce.call_once Args Self Output FnMut end ops end core open core.ops definition fn [instance] {A B : Type} : FnOnce A (A → option B) B := ⦃FnOnce, call_once := id ⦄ notation `let` binder ` ← ` x `; ` r:(scoped f, f x) := r
02b32e2c144d7ead62f690707eea035d82aa266c
67190c9aacc0cac64fb4463d93e84c696a5be896
/Classes/2019-10-17.lean
0b25e80e1d48c3476cf93d41f54231b4df5549bf
[]
no_license
lucasresck/Discrete-Mathematics
ffbaf55943e7ce2c7bc50cef7e3ef66a0212f738
0a08081c5f393e5765259d3f1253c3a6dd043dac
refs/heads/master
1,596,627,857,734
1,573,411,500,000
1,573,411,500,000
212,489,764
0
0
null
null
null
null
UTF-8
Lean
false
false
740
lean
variable U : Type variables A B C : set U example : ∀ x, x ∈ A ∩ C → x ∈ A ∪ B := begin assume x, intro, have h1, from a.left, exact or.inl h1, end example : ∀ x, x ∈ A ∩ C → x ∈ A ∪ B := assume x, show x ∈ A ∩ C → x ∈ A ∪ B, from assume h1 : x ∈ A ∩ C, show x ∈ A ∪ B, from or.inl h1.left example : ∀ x, x ∈ -(A ∪ B) → x ∈ -A := begin intros x h1 h2, apply h1, exact or.inl h2 end example : ∀ x, x ∈ -(A ∪ B) → x ∈ -A := assume x, assume h1 : x ∈ -(A ∪ B), show x ∈ -A, from assume h2 : x ∈ A, show false, from h1 $ or.inl h2
dbf23cae02d3a6ad0c9cb39b333eb9b626dcf218
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/run/fib_wrec.lean
9272cf85c0d66e08740c935d3b7c866562b80583
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
965
lean
open nat definition fib.F (n : nat) : (Π (m : nat), m < n → nat) → nat := nat.cases_on n (λ (f : Π (m : nat), m < 0 → nat), succ 0) (λ (n₁ : nat), nat.cases_on n₁ (λ (f : Π (m : nat), m < (succ 0) → nat), succ 0) (λ (n₂ : nat) (f : Π (m : nat), m < (succ (succ n₂)) → nat), have l₁ : succ n₂ < succ (succ n₂), from lt_succ_self (succ n₂), have l₂ : n₂ < succ (succ n₂), from nat.lt_trans (lt_succ_self n₂) l₁, f (succ n₂) l₁ + f n₂ l₂)) definition fib (n : nat) := well_founded.fix lt_wf fib.F n theorem fib.zero_eq : fib 0 = 1 := well_founded.fix_eq lt_wf fib.F 0 theorem fib.one_eq : fib 1 = 1 := well_founded.fix_eq lt_wf fib.F 1 theorem fib.succ_succ_eq (n : nat) : fib (succ (succ n)) = fib (succ n) + fib n := well_founded.fix_eq lt_wf fib.F (succ (succ n)) example : fib 5 = 8 := rfl example : fib 6 = 13 := rfl #print "------------" #reduce fib 10 #eval fib 10
8d1ee046c56fc319d2dfd8327727771f1ed2dc6f
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/order/antisymmetrization.lean
ca73c3d0b8a098e9a5ccc763f0049faaa250372b
[ "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
9,188
lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import order.hom.basic import logic.relation /-! # Turning a preorder into a partial order This file allows to make a preorder into a partial order by quotienting out the elements `a`, `b` such that `a ≤ b` and `b ≤ a`. `antisymmetrization` is a functor from `Preorder` to `PartialOrder`. See `Preorder_to_PartialOrder`. ## Main declarations * `antisymm_rel`: The antisymmetrization relation. `antisymm_rel r a b` means that `a` and `b` are related both ways by `r`. * `antisymmetrization α r`: The quotient of `α` by `antisymm_rel r`. Even when `r` is just a preorder, `antisymmetrization α` is a partial order. -/ open function order_dual variables {α β : Type*} section relation variables (r : α → α → Prop) /-- The antisymmetrization relation. -/ def antisymm_rel (a b : α) : Prop := r a b ∧ r b a lemma antisymm_rel_swap : antisymm_rel (swap r) = antisymm_rel r := funext $ λ _, funext $ λ _, propext and.comm @[refl] lemma antisymm_rel_refl [is_refl α r] (a : α) : antisymm_rel r a a := ⟨refl _, refl _⟩ variables {r} @[symm] lemma antisymm_rel.symm {a b : α} : antisymm_rel r a b → antisymm_rel r b a := and.symm @[trans] lemma antisymm_rel.trans [is_trans α r] {a b c : α} (hab : antisymm_rel r a b) (hbc : antisymm_rel r b c) : antisymm_rel r a c := ⟨trans hab.1 hbc.1, trans hbc.2 hab.2⟩ instance antisymm_rel.decidable_rel [decidable_rel r] : decidable_rel (antisymm_rel r) := λ _ _, and.decidable @[simp] lemma antisymm_rel_iff_eq [is_refl α r] [is_antisymm α r] {a b : α} : antisymm_rel r a b ↔ a = b := antisymm_iff alias antisymm_rel_iff_eq ↔ antisymm_rel.eq _ end relation section is_preorder variables (α) (r : α → α → Prop) [is_preorder α r] /-- The antisymmetrization relation as an equivalence relation. -/ @[simps] def antisymm_rel.setoid : setoid α := ⟨antisymm_rel r, antisymm_rel_refl _, λ _ _, antisymm_rel.symm, λ _ _ _, antisymm_rel.trans⟩ /-- The partial order derived from a preorder by making pairwise comparable elements equal. This is the quotient by `λ a b, a ≤ b ∧ b ≤ a`. -/ def antisymmetrization : Type* := quotient $ antisymm_rel.setoid α r variables {α} /-- Turn an element into its antisymmetrization. -/ def to_antisymmetrization : α → antisymmetrization α r := quotient.mk' /-- Get a representative from the antisymmetrization. -/ noncomputable def of_antisymmetrization : antisymmetrization α r → α := quotient.out' instance [inhabited α] : inhabited (antisymmetrization α r) := quotient.inhabited _ @[elab_as_eliminator] protected lemma antisymmetrization.ind {p : antisymmetrization α r → Prop} : (∀ a, p $ to_antisymmetrization r a) → ∀ q, p q := quot.ind @[elab_as_eliminator] protected lemma antisymmetrization.induction_on {p : antisymmetrization α r → Prop} (a : antisymmetrization α r) (h : ∀ a, p $ to_antisymmetrization r a) : p a := quotient.induction_on' a h @[simp] lemma to_antisymmetrization_of_antisymmetrization (a : antisymmetrization α r) : to_antisymmetrization r (of_antisymmetrization r a) = a := quotient.out_eq' _ end is_preorder section preorder variables {α} [preorder α] [preorder β] {a b : α} lemma antisymm_rel.image {a b : α} (h : antisymm_rel (≤) a b) {f : α → β} (hf : monotone f) : antisymm_rel (≤) (f a) (f b) := ⟨hf h.1, hf h.2⟩ instance : partial_order (antisymmetrization α (≤)) := { le := λ a b, quotient.lift_on₂' a b (≤) $ λ (a₁ a₂ b₁ b₂ : α) h₁ h₂, propext ⟨λ h, h₁.2.trans $ h.trans h₂.1, λ h, h₁.1.trans $ h.trans h₂.2⟩, lt := λ a b, quotient.lift_on₂' a b (<) $ λ (a₁ a₂ b₁ b₂ : α) h₁ h₂, propext ⟨λ h, h₁.2.trans_lt $ h.trans_le h₂.1, λ h, h₁.1.trans_lt $ h.trans_le h₂.2⟩, le_refl := λ a, quotient.induction_on' a $ le_refl, le_trans := λ a b c, quotient.induction_on₃' a b c $ λ a b c, le_trans, lt_iff_le_not_le := λ a b, quotient.induction_on₂' a b $ λ a b, lt_iff_le_not_le, le_antisymm := λ a b, quotient.induction_on₂' a b $ λ a b hab hba, quotient.sound' ⟨hab, hba⟩ } lemma antisymmetrization_fibration : relation.fibration (<) (<) (@to_antisymmetrization α (≤) _) := by { rintro a ⟨b⟩ h, exact ⟨b, h, rfl⟩ } lemma acc_antisymmetrization_iff : acc (<) (to_antisymmetrization (≤) a) ↔ acc (<) a := ⟨λ h, by { have := inv_image.accessible _ h, exact this }, acc.of_fibration _ antisymmetrization_fibration⟩ lemma well_founded_antisymmetrization_iff : well_founded (@has_lt.lt (antisymmetrization α (≤)) _) ↔ well_founded (@has_lt.lt α _) := ⟨λ h, ⟨λ a, acc_antisymmetrization_iff.1 $ h.apply _⟩, λ h, ⟨by { rintro ⟨a⟩, exact acc_antisymmetrization_iff.2 (h.apply a) }⟩⟩ instance [well_founded_lt α] : well_founded_lt (antisymmetrization α (≤)) := ⟨well_founded_antisymmetrization_iff.2 is_well_founded.wf⟩ instance [@decidable_rel α (≤)] [@decidable_rel α (<)] [is_total α (≤)] : linear_order (antisymmetrization α (≤)) := { le_total := λ a b, quotient.induction_on₂' a b $ total_of (≤), decidable_eq := @quotient.decidable_eq _ (antisymm_rel.setoid _ (≤)) antisymm_rel.decidable_rel, decidable_le := λ _ _, quotient.lift_on₂'.decidable _ _ _ _, decidable_lt := λ _ _, quotient.lift_on₂'.decidable _ _ _ _, ..antisymmetrization.partial_order } @[simp] lemma to_antisymmetrization_le_to_antisymmetrization_iff : to_antisymmetrization (≤) a ≤ to_antisymmetrization (≤) b ↔ a ≤ b := iff.rfl @[simp] lemma to_antisymmetrization_lt_to_antisymmetrization_iff : to_antisymmetrization (≤) a < to_antisymmetrization (≤) b ↔ a < b := iff.rfl @[simp] lemma of_antisymmetrization_le_of_antisymmetrization_iff {a b : antisymmetrization α (≤)} : of_antisymmetrization (≤) a ≤ of_antisymmetrization (≤) b ↔ a ≤ b := by convert to_antisymmetrization_le_to_antisymmetrization_iff.symm; exact (to_antisymmetrization_of_antisymmetrization _ _).symm @[simp] lemma of_antisymmetrization_lt_of_antisymmetrization_iff {a b : antisymmetrization α (≤)} : of_antisymmetrization (≤) a < of_antisymmetrization (≤) b ↔ a < b := by convert to_antisymmetrization_lt_to_antisymmetrization_iff.symm; exact (to_antisymmetrization_of_antisymmetrization _ _).symm @[mono] lemma to_antisymmetrization_mono : monotone (@to_antisymmetrization α (≤) _) := λ a b, id /-- `to_antisymmetrization` as an order homomorphism. -/ @[simps] def order_hom.to_antisymmetrization : α →o antisymmetrization α (≤) := ⟨to_antisymmetrization (≤), λ a b, id⟩ private lemma lift_fun_antisymm_rel (f : α →o β) : ((antisymm_rel.setoid α (≤)).r ⇒ (antisymm_rel.setoid β (≤)).r) f f := λ a b h, ⟨f.mono h.1, f.mono h.2⟩ /-- Turns an order homomorphism from `α` to `β` into one from `antisymmetrization α` to `antisymmetrization β`. `antisymmetrization` is actually a functor. See `Preorder_to_PartialOrder`. -/ protected def order_hom.antisymmetrization (f : α →o β) : antisymmetrization α (≤) →o antisymmetrization β (≤) := ⟨quotient.map' f $ lift_fun_antisymm_rel f, λ a b, quotient.induction_on₂' a b $ f.mono⟩ @[simp] lemma order_hom.coe_antisymmetrization (f : α →o β) : ⇑f.antisymmetrization = quotient.map' f (lift_fun_antisymm_rel f) := rfl @[simp] lemma order_hom.antisymmetrization_apply (f : α →o β) (a : antisymmetrization α (≤)) : f.antisymmetrization a = quotient.map' f (lift_fun_antisymm_rel f) a := rfl @[simp] lemma order_hom.antisymmetrization_apply_mk (f : α →o β) (a : α) : f.antisymmetrization (to_antisymmetrization _ a) = (to_antisymmetrization _ (f a)) := quotient.map'_mk' f (lift_fun_antisymm_rel f) _ variables (α) /-- `of_antisymmetrization` as an order embedding. -/ @[simps] noncomputable def order_embedding.of_antisymmetrization : antisymmetrization α (≤) ↪o α := { to_fun := of_antisymmetrization _, inj' := λ _ _, quotient.out_inj.1, map_rel_iff' := λ a b, of_antisymmetrization_le_of_antisymmetrization_iff } /-- `antisymmetrization` and `order_dual` commute. -/ def order_iso.dual_antisymmetrization : (antisymmetrization α (≤))ᵒᵈ ≃o antisymmetrization αᵒᵈ (≤) := { to_fun := quotient.map' id $ λ _ _, and.symm, inv_fun := quotient.map' id $ λ _ _, and.symm, left_inv := λ a, quotient.induction_on' a $ λ a, by simp_rw [quotient.map'_mk', id], right_inv := λ a, quotient.induction_on' a $ λ a, by simp_rw [quotient.map'_mk', id], map_rel_iff' := λ a b, quotient.induction_on₂' a b $ λ a b, iff.rfl } @[simp] lemma order_iso.dual_antisymmetrization_apply (a : α) : order_iso.dual_antisymmetrization _ (to_dual $ to_antisymmetrization _ a) = to_antisymmetrization _ (to_dual a) := rfl @[simp] lemma order_iso.dual_antisymmetrization_symm_apply (a : α) : (order_iso.dual_antisymmetrization _).symm (to_antisymmetrization _ $ to_dual a) = to_dual (to_antisymmetrization _ a) := rfl end preorder
23890139d2820f2ee21d479dca18dd250908eb0e
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/group_theory/commensurable.lean
73e3da604faba37793798c63f26ac77d3cf2d8c9
[ "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
4,182
lean
/- Copyright (c) 2021 Chris Birkbeck. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Birkbeck -/ import group_theory.index import group_theory.subgroup.pointwise import group_theory.group_action.conj_act /-! # Commensurability for subgroups This file defines commensurability for subgroups of a group `G`. It then goes on to prove that commensurability defines an equivalence relation and finally defines the commensurator of a subgroup of `G`. ## Main definitions * `commensurable`: defines commensurability for two subgroups `H`, `K` of `G` * `commensurator`: defines the commensurator of a subgroup `H` of `G`. ## Implementation details We define the commensurator of a subgroup `H` of `G` by first defining it as a subgroup of `(conj_act G)`, which we call commensurator' and then taking the pre-image under the map `G → (conj_act G)` to obtain our commensurator as a subgroup of `G`. -/ variables {G : Type*} [group G] /--Two subgroups `H K` of `G` are commensurable if `H ⊓ K` has finite index in both `H` and `K` -/ def commensurable (H K : subgroup G) : Prop := H.relindex K ≠ 0 ∧ K.relindex H ≠ 0 namespace commensurable open_locale pointwise @[refl] protected lemma refl (H : subgroup G) : commensurable H H := by simp [commensurable] lemma comm {H K : subgroup G} : commensurable H K ↔ commensurable K H := and.comm @[symm] lemma symm {H K : subgroup G} : commensurable H K → commensurable K H := and.symm @[trans] lemma trans {H K L : subgroup G} (hhk : commensurable H K) (hkl : commensurable K L) : commensurable H L := ⟨subgroup.relindex_ne_zero_trans hhk.1 hkl.1, subgroup.relindex_ne_zero_trans hkl.2 hhk.2⟩ lemma equivalence : equivalence (@commensurable G _) := ⟨commensurable.refl, λ _ _, commensurable.symm, λ _ _ _, commensurable.trans⟩ /--Equivalence of `K/H ⊓ K` with `gKg⁻¹/gHg⁻¹ ⊓ gKg⁻¹`-/ def quot_conj_equiv (H K : subgroup G) (g : conj_act G) : K ⧸ (H.subgroup_of K) ≃ (g • K).1 ⧸ ((g • H).subgroup_of (g • K)) := quotient.congr (K.equiv_smul g).to_equiv (λ a b, by { rw [←quotient.eq', ←quotient.eq', quotient_group.eq', quotient_group.eq', subgroup.mem_subgroup_of, subgroup.mem_subgroup_of, mul_equiv.to_equiv_eq_coe, mul_equiv.coe_to_equiv, ←mul_equiv.map_inv, ←mul_equiv.map_mul, subgroup.equiv_smul_apply_coe, subgroup.smul_mem_pointwise_smul_iff] }) lemma commensurable_conj {H K : subgroup G} (g : conj_act G) : commensurable H K ↔ commensurable (g • H) (g • K) := and_congr (not_iff_not.mpr (eq.congr_left (cardinal.to_nat_congr (quot_conj_equiv H K g)))) (not_iff_not.mpr (eq.congr_left (cardinal.to_nat_congr (quot_conj_equiv K H g)))) lemma commensurable_inv (H : subgroup G) (g : conj_act G) : commensurable (g • H) H ↔ commensurable H (g⁻¹ • H) := by rw [commensurable_conj, inv_smul_smul] /-- For `H` a subgroup of `G`, this is the subgroup of all elements `g : conj_aut G` such that `commensurable (g • H) H` -/ def commensurator' (H : subgroup G) : subgroup (conj_act G) := { carrier := {g : conj_act G | commensurable (g • H) H}, one_mem' := by rw [set.mem_set_of_eq, one_smul], mul_mem' := λ a b ha hb, by { rw [set.mem_set_of_eq, mul_smul], exact trans ((commensurable_conj a).mp hb) ha }, inv_mem' := λ a ha, by rwa [set.mem_set_of_eq, comm, ←commensurable_inv] } /-- For `H` a subgroup of `G`, this is the subgroup of all elements `g : G` such that `commensurable (g H g⁻¹) H` -/ def commensurator (H : subgroup G) : subgroup G := (commensurator' H).comap (conj_act.to_conj_act.to_monoid_hom) @[simp] lemma commensurator'_mem_iff (H : subgroup G) (g : conj_act G) : g ∈ (commensurator' H) ↔ commensurable (g • H) H := iff.rfl @[simp] lemma commensurator_mem_iff (H : subgroup G) (g : G) : g ∈ (commensurator H) ↔ commensurable (conj_act.to_conj_act g • H) H := iff.rfl lemma eq {H K : subgroup G} (hk : commensurable H K) : commensurator H = commensurator K := subgroup.ext (λ x, let hx := (commensurable_conj x).1 hk in ⟨λ h, hx.symm.trans (h.trans hk), λ h, hx.trans (h.trans hk.symm)⟩) end commensurable
92ae45d0206e39e00283e4dd79d85f4407092abe
4fa161becb8ce7378a709f5992a594764699e268
/src/data/seq/computation.lean
48a71dde3c303b73a79eb38117594716eed32614
[ "Apache-2.0" ]
permissive
laughinggas/mathlib
e4aa4565ae34e46e834434284cb26bd9d67bc373
86dcd5cda7a5017c8b3c8876c89a510a19d49aad
refs/heads/master
1,669,496,232,688
1,592,831,995,000
1,592,831,995,000
274,155,979
0
0
Apache-2.0
1,592,835,190,000
1,592,835,189,000
null
UTF-8
Lean
false
false
37,548
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Coinductive formalization of unbounded computations. -/ import data.stream import tactic.basic universes u v w /- coinductive computation (α : Type u) : Type u | return : α → computation α | think : computation α → computation α -/ /-- `computation α` is the type of unbounded computations returning `α`. An element of `computation α` is an infinite sequence of `option α` such that if `f n = some a` for some `n` then it is constantly `some a` after that. -/ def computation (α : Type u) : Type u := { f : stream (option α) // ∀ {n a}, f n = some a → f (n+1) = some a } namespace computation variables {α : Type u} {β : Type v} {γ : Type w} -- constructors /-- `return a` is the computation that immediately terminates with result `a`. -/ def return (a : α) : computation α := ⟨stream.const (some a), λn a', id⟩ instance : has_coe_t α (computation α) := ⟨return⟩ -- note [use has_coe_t] /-- `think c` is the computation that delays for one "tick" and then performs computation `c`. -/ def think (c : computation α) : computation α := ⟨none :: c.1, λn a h, by {cases n with n, contradiction, exact c.2 h}⟩ /-- `thinkN c n` is the computation that delays for `n` ticks and then performs computation `c`. -/ def thinkN (c : computation α) : ℕ → computation α | 0 := c | (n+1) := think (thinkN n) -- check for immediate result /-- `head c` is the first step of computation, either `some a` if `c = return a` or `none` if `c = think c'`. -/ def head (c : computation α) : option α := c.1.head -- one step of computation /-- `tail c` is the remainder of computation, either `c` if `c = return a` or `c'` if `c = think c'`. -/ def tail (c : computation α) : computation α := ⟨c.1.tail, λ n a, let t := c.2 in t⟩ /-- `empty α` is the computation that never returns, an infinite sequence of `think`s. -/ def empty (α) : computation α := ⟨stream.const none, λn a', id⟩ instance : inhabited (computation α) := ⟨empty _⟩ /-- `run_for c n` evaluates `c` for `n` steps and returns the result, or `none` if it did not terminate after `n` steps. -/ def run_for : computation α → ℕ → option α := subtype.val /-- `destruct c` is the destructor for `computation α` as a coinductive type. It returns `inl a` if `c = return a` and `inr c'` if `c = think c'`. -/ def destruct (c : computation α) : α ⊕ computation α := match c.1 0 with | none := sum.inr (tail c) | some a := sum.inl a end /-- `run c` is an unsound meta function that runs `c` to completion, possibly resulting in an infinite loop in the VM. -/ meta def run : computation α → α | c := match destruct c with | sum.inl a := a | sum.inr ca := run ca end theorem destruct_eq_ret {s : computation α} {a : α} : destruct s = sum.inl a → s = return a := begin dsimp [destruct], induction f0 : s.1 0; intro h, { contradiction }, { apply subtype.eq, funext n, induction n with n IH, { injection h with h', rwa h' at f0 }, { exact s.2 IH } } end theorem destruct_eq_think {s : computation α} {s'} : destruct s = sum.inr s' → s = think s' := begin dsimp [destruct], induction f0 : s.1 0 with a'; intro h, { injection h with h', rw ←h', cases s with f al, apply subtype.eq, dsimp [think, tail], rw ←f0, exact (stream.eta f).symm }, { contradiction } end @[simp] theorem destruct_ret (a : α) : destruct (return a) = sum.inl a := rfl @[simp] theorem destruct_think : ∀ s : computation α, destruct (think s) = sum.inr s | ⟨f, al⟩ := rfl @[simp] theorem destruct_empty : destruct (empty α) = sum.inr (empty α) := rfl @[simp] theorem head_ret (a : α) : head (return a) = some a := rfl @[simp] theorem head_think (s : computation α) : head (think s) = none := rfl @[simp] theorem head_empty : head (empty α) = none := rfl @[simp] theorem tail_ret (a : α) : tail (return a) = return a := rfl @[simp] theorem tail_think (s : computation α) : tail (think s) = s := by cases s with f al; apply subtype.eq; dsimp [tail, think]; rw [stream.tail_cons] @[simp] theorem tail_empty : tail (empty α) = empty α := rfl theorem think_empty : empty α = think (empty α) := destruct_eq_think destruct_empty def cases_on {C : computation α → Sort v} (s : computation α) (h1 : ∀ a, C (return a)) (h2 : ∀ s, C (think s)) : C s := begin induction H : destruct s with v v, { rw destruct_eq_ret H, apply h1 }, { cases v with a s', rw destruct_eq_think H, apply h2 } end def corec.F (f : β → α ⊕ β) : α ⊕ β → option α × (α ⊕ β) | (sum.inl a) := (some a, sum.inl a) | (sum.inr b) := (match f b with | sum.inl a := some a | sum.inr b' := none end, f b) /-- `corec f b` is the corecursor for `computation α` as a coinductive type. If `f b = inl a` then `corec f b = return a`, and if `f b = inl b'` then `corec f b = think (corec f b')`. -/ def corec (f : β → α ⊕ β) (b : β) : computation α := begin refine ⟨stream.corec' (corec.F f) (sum.inr b), λn a' h, _⟩, rw stream.corec'_eq, change stream.corec' (corec.F f) (corec.F f (sum.inr b)).2 n = some a', revert h, generalize : sum.inr b = o, revert o, induction n with n IH; intro o, { change (corec.F f o).1 = some a' → (corec.F f (corec.F f o).2).1 = some a', cases o with a b; intro h, { exact h }, dsimp [corec.F] at h, dsimp [corec.F], cases f b with a b', { exact h }, { contradiction } }, { rw [stream.corec'_eq (corec.F f) (corec.F f o).2, stream.corec'_eq (corec.F f) o], exact IH (corec.F f o).2 } end /-- left map of `⊕` -/ def lmap (f : α → β) : α ⊕ γ → β ⊕ γ | (sum.inl a) := sum.inl (f a) | (sum.inr b) := sum.inr b /-- right map of `⊕` -/ def rmap (f : β → γ) : α ⊕ β → α ⊕ γ | (sum.inl a) := sum.inl a | (sum.inr b) := sum.inr (f b) attribute [simp] lmap rmap @[simp] lemma corec_eq (f : β → α ⊕ β) (b : β) : destruct (corec f b) = rmap (corec f) (f b) := begin dsimp [corec, destruct], change stream.corec' (corec.F f) (sum.inr b) 0 with corec.F._match_1 (f b), induction h : f b with a b', { refl }, dsimp [corec.F, destruct], apply congr_arg, apply subtype.eq, dsimp [corec, tail], rw [stream.corec'_eq, stream.tail_cons], dsimp [corec.F], rw h end section bisim variable (R : computation α → computation α → Prop) local infix ~ := R def bisim_o : α ⊕ computation α → α ⊕ computation α → Prop | (sum.inl a) (sum.inl a') := a = a' | (sum.inr s) (sum.inr s') := R s s' | _ _ := false attribute [simp] bisim_o def is_bisimulation := ∀ ⦃s₁ s₂⦄, s₁ ~ s₂ → bisim_o R (destruct s₁) (destruct s₂) -- If two computations are bisimilar, then they are equal theorem eq_of_bisim (bisim : is_bisimulation R) {s₁ s₂} (r : s₁ ~ s₂) : s₁ = s₂ := begin apply subtype.eq, apply stream.eq_of_bisim (λx y, ∃ s s' : computation α, s.1 = x ∧ s'.1 = y ∧ R s s'), dsimp [stream.is_bisimulation], intros t₁ t₂ e, exact match t₁, t₂, e with ._, ._, ⟨s, s', rfl, rfl, r⟩ := suffices head s = head s' ∧ R (tail s) (tail s'), from and.imp id (λr, ⟨tail s, tail s', by cases s; refl, by cases s'; refl, r⟩) this, begin have := bisim r, revert r this, apply cases_on s _ _; intros; apply cases_on s' _ _; intros; intros r this, { constructor, dsimp at this, rw this, assumption }, { rw [destruct_ret, destruct_think] at this, exact false.elim this }, { rw [destruct_ret, destruct_think] at this, exact false.elim this }, { simp at this, simp [*] } end end, exact ⟨s₁, s₂, rfl, rfl, r⟩ end end bisim -- It's more of a stretch to use ∈ for this relation, but it -- asserts that the computation limits to the given value. protected def mem (a : α) (s : computation α) := some a ∈ s.1 instance : has_mem α (computation α) := ⟨computation.mem⟩ theorem le_stable (s : computation α) {a m n} (h : m ≤ n) : s.1 m = some a → s.1 n = some a := by {cases s with f al, induction h with n h IH, exacts [id, λ h2, al (IH h2)]} theorem mem_unique : relator.left_unique ((∈) : α → computation α → Prop) := λa s b ⟨m, ha⟩ ⟨n, hb⟩, by injection (le_stable s (le_max_left m n) ha.symm).symm.trans (le_stable s (le_max_right m n) hb.symm) /-- `terminates s` asserts that the computation `s` eventually terminates with some value. -/ @[class] def terminates (s : computation α) : Prop := ∃ a, a ∈ s theorem terminates_of_mem {s : computation α} {a : α} : a ∈ s → terminates s := exists.intro a theorem terminates_def (s : computation α) : terminates s ↔ ∃ n, (s.1 n).is_some := ⟨λ⟨a, n, h⟩, ⟨n, by {dsimp [stream.nth] at h, rw ←h, exact rfl}⟩, λ⟨n, h⟩, ⟨option.get h, n, (option.eq_some_of_is_some h).symm⟩⟩ theorem ret_mem (a : α) : a ∈ return a := exists.intro 0 rfl theorem eq_of_ret_mem {a a' : α} (h : a' ∈ return a) : a' = a := mem_unique h (ret_mem _) instance ret_terminates (a : α) : terminates (return a) := terminates_of_mem (ret_mem _) theorem think_mem {s : computation α} {a} : a ∈ s → a ∈ think s | ⟨n, h⟩ := ⟨n+1, h⟩ instance think_terminates (s : computation α) : ∀ [terminates s], terminates (think s) | ⟨a, n, h⟩ := ⟨a, n+1, h⟩ theorem of_think_mem {s : computation α} {a} : a ∈ think s → a ∈ s | ⟨n, h⟩ := by {cases n with n', contradiction, exact ⟨n', h⟩} theorem of_think_terminates {s : computation α} : terminates (think s) → terminates s | ⟨a, h⟩ := ⟨a, of_think_mem h⟩ theorem not_mem_empty (a : α) : a ∉ empty α := λ ⟨n, h⟩, by clear _fun_match; contradiction theorem not_terminates_empty : ¬ terminates (empty α) := λ ⟨a, h⟩, not_mem_empty a h theorem eq_empty_of_not_terminates {s} (H : ¬ terminates s) : s = empty α := begin apply subtype.eq, funext n, induction h : s.val n, {refl}, refine absurd _ H, exact ⟨_, _, h.symm⟩ end theorem thinkN_mem {s : computation α} {a} : ∀ n, a ∈ thinkN s n ↔ a ∈ s | 0 := iff.rfl | (n+1) := iff.trans ⟨of_think_mem, think_mem⟩ (thinkN_mem n) instance thinkN_terminates (s : computation α) : ∀ [terminates s] n, terminates (thinkN s n) | ⟨a, h⟩ n := ⟨a, (thinkN_mem n).2 h⟩ theorem of_thinkN_terminates (s : computation α) (n) : terminates (thinkN s n) → terminates s | ⟨a, h⟩ := ⟨a, (thinkN_mem _).1 h⟩ /-- `promises s a`, or `s ~> a`, asserts that although the computation `s` may not terminate, if it does, then the result is `a`. -/ def promises (s : computation α) (a : α) : Prop := ∀ ⦃a'⦄, a' ∈ s → a = a' infix ` ~> `:50 := promises theorem mem_promises {s : computation α} {a : α} : a ∈ s → s ~> a := λ h a', mem_unique h theorem empty_promises (a : α) : empty α ~> a := λ a' h, absurd h (not_mem_empty _) section get variables (s : computation α) [h : terminates s] include s h /-- `length s` gets the number of steps of a terminating computation -/ def length : ℕ := nat.find ((terminates_def _).1 h) /-- `get s` returns the result of a terminating computation -/ def get : α := option.get (nat.find_spec $ (terminates_def _).1 h) theorem get_mem : get s ∈ s := exists.intro (length s) (option.eq_some_of_is_some _).symm theorem get_eq_of_mem {a} : a ∈ s → get s = a := mem_unique (get_mem _) theorem mem_of_get_eq {a} : get s = a → a ∈ s := by intro h; rw ←h; apply get_mem @[simp] theorem get_think : get (think s) = get s := get_eq_of_mem _ $ let ⟨n, h⟩ := get_mem s in ⟨n+1, h⟩ @[simp] theorem get_thinkN (n) : get (thinkN s n) = get s := get_eq_of_mem _ $ (thinkN_mem _).2 (get_mem _) theorem get_promises : s ~> get s := λ a, get_eq_of_mem _ theorem mem_of_promises {a} (p : s ~> a) : a ∈ s := by unfreezeI; cases h with a' h; rw p h; exact h theorem get_eq_of_promises {a} : s ~> a → get s = a := get_eq_of_mem _ ∘ mem_of_promises _ end get /-- `results s a n` completely characterizes a terminating computation: it asserts that `s` terminates after exactly `n` steps, with result `a`. -/ def results (s : computation α) (a : α) (n : ℕ) := ∃ (h : a ∈ s), @length _ s (terminates_of_mem h) = n theorem results_of_terminates (s : computation α) [T : terminates s] : results s (get s) (length s) := ⟨get_mem _, rfl⟩ theorem results_of_terminates' (s : computation α) [T : terminates s] {a} (h : a ∈ s) : results s a (length s) := by rw ←get_eq_of_mem _ h; apply results_of_terminates theorem results.mem {s : computation α} {a n} : results s a n → a ∈ s | ⟨m, _⟩ := m theorem results.terminates {s : computation α} {a n} (h : results s a n) : terminates s := terminates_of_mem h.mem theorem results.length {s : computation α} {a n} [T : terminates s] : results s a n → length s = n | ⟨_, h⟩ := h theorem results.val_unique {s : computation α} {a b m n} (h1 : results s a m) (h2 : results s b n) : a = b := mem_unique h1.mem h2.mem theorem results.len_unique {s : computation α} {a b m n} (h1 : results s a m) (h2 : results s b n) : m = n := by haveI := h1.terminates; haveI := h2.terminates; rw [←h1.length, h2.length] theorem exists_results_of_mem {s : computation α} {a} (h : a ∈ s) : ∃ n, results s a n := by haveI := terminates_of_mem h; exact ⟨_, results_of_terminates' s h⟩ @[simp] theorem get_ret (a : α) : get (return a) = a := get_eq_of_mem _ ⟨0, rfl⟩ @[simp] theorem length_ret (a : α) : length (return a) = 0 := let h := computation.ret_terminates a in nat.eq_zero_of_le_zero $ nat.find_min' ((terminates_def (return a)).1 h) rfl theorem results_ret (a : α) : results (return a) a 0 := ⟨_, length_ret _⟩ @[simp] theorem length_think (s : computation α) [h : terminates s] : length (think s) = length s + 1 := begin apply le_antisymm, { exact nat.find_min' _ (nat.find_spec ((terminates_def _).1 h)) }, { have : (option.is_some ((think s).val (length (think s))) : Prop) := nat.find_spec ((terminates_def _).1 s.think_terminates), cases length (think s) with n, { contradiction }, { apply nat.succ_le_succ, apply nat.find_min', apply this } } end theorem results_think {s : computation α} {a n} (h : results s a n) : results (think s) a (n + 1) := by haveI := h.terminates; exact ⟨think_mem h.mem, by rw [length_think, h.length]⟩ theorem of_results_think {s : computation α} {a n} (h : results (think s) a n) : ∃ m, results s a m ∧ n = m + 1 := begin haveI := of_think_terminates h.terminates, have := results_of_terminates' _ (of_think_mem h.mem), exact ⟨_, this, results.len_unique h (results_think this)⟩, end @[simp] theorem results_think_iff {s : computation α} {a n} : results (think s) a (n + 1) ↔ results s a n := ⟨λ h, let ⟨n', r, e⟩ := of_results_think h in by injection e with h'; rwa h', results_think⟩ theorem results_thinkN {s : computation α} {a m} : ∀ n, results s a m → results (thinkN s n) a (m + n) | 0 h := h | (n+1) h := results_think (results_thinkN n h) theorem results_thinkN_ret (a : α) (n) : results (thinkN (return a) n) a n := by have := results_thinkN n (results_ret a); rwa nat.zero_add at this @[simp] theorem length_thinkN (s : computation α) [h : terminates s] (n) : length (thinkN s n) = length s + n := (results_thinkN n (results_of_terminates _)).length theorem eq_thinkN {s : computation α} {a n} (h : results s a n) : s = thinkN (return a) n := begin revert s, induction n with n IH; intro s; apply cases_on s (λ a', _) (λ s, _); intro h, { rw ←eq_of_ret_mem h.mem, refl }, { cases of_results_think h with n h, cases h, contradiction }, { have := h.len_unique (results_ret _), contradiction }, { rw IH (results_think_iff.1 h), refl } end theorem eq_thinkN' (s : computation α) [h : terminates s] : s = thinkN (return (get s)) (length s) := eq_thinkN (results_of_terminates _) def mem_rec_on {C : computation α → Sort v} {a s} (M : a ∈ s) (h1 : C (return a)) (h2 : ∀ s, C s → C (think s)) : C s := begin haveI T := terminates_of_mem M, rw [eq_thinkN' s, get_eq_of_mem s M], generalize : length s = n, induction n with n IH, exacts [h1, h2 _ IH] end def terminates_rec_on {C : computation α → Sort v} (s) [terminates s] (h1 : ∀ a, C (return a)) (h2 : ∀ s, C s → C (think s)) : C s := mem_rec_on (get_mem s) (h1 _) h2 /-- Map a function on the result of a computation. -/ def map (f : α → β) : computation α → computation β | ⟨s, al⟩ := ⟨s.map (λo, option.cases_on o none (some ∘ f)), λn b, begin dsimp [stream.map, stream.nth], induction e : s n with a; intro h, { contradiction }, { rw [al e, ←h] } end⟩ def bind.G : β ⊕ computation β → β ⊕ computation α ⊕ computation β | (sum.inl b) := sum.inl b | (sum.inr cb') := sum.inr $ sum.inr cb' def bind.F (f : α → computation β) : computation α ⊕ computation β → β ⊕ computation α ⊕ computation β | (sum.inl ca) := match destruct ca with | sum.inl a := bind.G $ destruct (f a) | sum.inr ca' := sum.inr $ sum.inl ca' end | (sum.inr cb) := bind.G $ destruct cb /-- Compose two computations into a monadic `bind` operation. -/ def bind (c : computation α) (f : α → computation β) : computation β := corec (bind.F f) (sum.inl c) instance : has_bind computation := ⟨@bind⟩ theorem has_bind_eq_bind {β} (c : computation α) (f : α → computation β) : c >>= f = bind c f := rfl /-- Flatten a computation of computations into a single computation. -/ def join (c : computation (computation α)) : computation α := c >>= id @[simp] theorem map_ret (f : α → β) (a) : map f (return a) = return (f a) := rfl @[simp] theorem map_think (f : α → β) : ∀ s, map f (think s) = think (map f s) | ⟨s, al⟩ := by apply subtype.eq; dsimp [think, map]; rw stream.map_cons @[simp] theorem destruct_map (f : α → β) (s) : destruct (map f s) = lmap f (rmap (map f) (destruct s)) := by apply s.cases_on; intro; simp @[simp] theorem map_id : ∀ (s : computation α), map id s = s | ⟨f, al⟩ := begin apply subtype.eq; simp [map, function.comp], have e : (@option.rec α (λ_, option α) none some) = id, { ext ⟨⟩; refl }, simp [e, stream.map_id] end theorem map_comp (f : α → β) (g : β → γ) : ∀ (s : computation α), map (g ∘ f) s = map g (map f s) | ⟨s, al⟩ := begin apply subtype.eq; dsimp [map], rw stream.map_map, apply congr_arg (λ f : _ → option γ, stream.map f s), ext ⟨⟩; refl end @[simp] theorem ret_bind (a) (f : α → computation β) : bind (return a) f = f a := begin apply eq_of_bisim (λc₁ c₂, c₁ = bind (return a) f ∧ c₂ = f a ∨ c₁ = corec (bind.F f) (sum.inr c₂)), { intros c₁ c₂ h, exact match c₁, c₂, h with | ._, ._, or.inl ⟨rfl, rfl⟩ := begin simp [bind, bind.F], cases destruct (f a) with b cb; simp [bind.G] end | ._, c, or.inr rfl := begin simp [bind.F], cases destruct c with b cb; simp [bind.G] end end }, { simp } end @[simp] theorem think_bind (c) (f : α → computation β) : bind (think c) f = think (bind c f) := destruct_eq_think $ by simp [bind, bind.F] @[simp] theorem bind_ret (f : α → β) (s) : bind s (return ∘ f) = map f s := begin apply eq_of_bisim (λc₁ c₂, c₁ = c₂ ∨ ∃ s, c₁ = bind s (return ∘ f) ∧ c₂ = map f s), { intros c₁ c₂ h, exact match c₁, c₂, h with | _, _, or.inl (eq.refl c) := begin cases destruct c with b cb; simp end | _, _, or.inr ⟨s, rfl, rfl⟩ := begin apply cases_on s; intros s; simp, exact or.inr ⟨s, rfl, rfl⟩ end end }, { exact or.inr ⟨s, rfl, rfl⟩ } end @[simp] theorem bind_ret' (s : computation α) : bind s return = s := by rw bind_ret; change (λ x : α, x) with @id α; rw map_id @[simp] theorem bind_assoc (s : computation α) (f : α → computation β) (g : β → computation γ) : bind (bind s f) g = bind s (λ (x : α), bind (f x) g) := begin apply eq_of_bisim (λc₁ c₂, c₁ = c₂ ∨ ∃ s, c₁ = bind (bind s f) g ∧ c₂ = bind s (λ (x : α), bind (f x) g)), { intros c₁ c₂ h, exact match c₁, c₂, h with | _, _, or.inl (eq.refl c) := by cases destruct c with b cb; simp | ._, ._, or.inr ⟨s, rfl, rfl⟩ := begin apply cases_on s; intros s; simp, { generalize : f s = fs, apply cases_on fs; intros t; simp, { cases destruct (g t) with b cb; simp } }, { exact or.inr ⟨s, rfl, rfl⟩ } end end }, { exact or.inr ⟨s, rfl, rfl⟩ } end theorem results_bind {s : computation α} {f : α → computation β} {a b m n} (h1 : results s a m) (h2 : results (f a) b n) : results (bind s f) b (n + m) := begin have := h1.mem, revert m, apply mem_rec_on this _ (λ s IH, _); intros m h1, { rw [ret_bind], rw h1.len_unique (results_ret _), exact h2 }, { rw [think_bind], cases of_results_think h1 with m' h, cases h with h1 e, rw e, exact results_think (IH h1) } end theorem mem_bind {s : computation α} {f : α → computation β} {a b} (h1 : a ∈ s) (h2 : b ∈ f a) : b ∈ bind s f := let ⟨m, h1⟩ := exists_results_of_mem h1, ⟨n, h2⟩ := exists_results_of_mem h2 in (results_bind h1 h2).mem instance terminates_bind (s : computation α) (f : α → computation β) [terminates s] [terminates (f (get s))] : terminates (bind s f) := terminates_of_mem (mem_bind (get_mem s) (get_mem (f (get s)))) @[simp] theorem get_bind (s : computation α) (f : α → computation β) [terminates s] [terminates (f (get s))] : get (bind s f) = get (f (get s)) := get_eq_of_mem _ (mem_bind (get_mem s) (get_mem (f (get s)))) @[simp] theorem length_bind (s : computation α) (f : α → computation β) [T1 : terminates s] [T2 : terminates (f (get s))] : length (bind s f) = length (f (get s)) + length s := (results_of_terminates _).len_unique $ results_bind (results_of_terminates _) (results_of_terminates _) theorem of_results_bind {s : computation α} {f : α → computation β} {b k} : results (bind s f) b k → ∃ a m n, results s a m ∧ results (f a) b n ∧ k = n + m := begin induction k with n IH generalizing s; apply cases_on s (λ a, _) (λ s', _); intro e, { simp [thinkN] at e, refine ⟨a, _, _, results_ret _, e, rfl⟩ }, { have := congr_arg head (eq_thinkN e), contradiction }, { simp at e, refine ⟨a, _, n+1, results_ret _, e, rfl⟩ }, { simp at e, exact let ⟨a, m, n', h1, h2, e'⟩ := IH e in by rw e'; exact ⟨a, m.succ, n', results_think h1, h2, rfl⟩ } end theorem exists_of_mem_bind {s : computation α} {f : α → computation β} {b} (h : b ∈ bind s f) : ∃ a ∈ s, b ∈ f a := let ⟨k, h⟩ := exists_results_of_mem h, ⟨a, m, n, h1, h2, e⟩ := of_results_bind h in ⟨a, h1.mem, h2.mem⟩ theorem bind_promises {s : computation α} {f : α → computation β} {a b} (h1 : s ~> a) (h2 : f a ~> b) : bind s f ~> b := λ b' bB, begin rcases exists_of_mem_bind bB with ⟨a', a's, ba'⟩, rw ←h1 a's at ba', exact h2 ba' end instance : monad computation := { map := @map, pure := @return, bind := @bind } instance : is_lawful_monad computation := { id_map := @map_id, bind_pure_comp_eq_map := @bind_ret, pure_bind := @ret_bind, bind_assoc := @bind_assoc } theorem has_map_eq_map {β} (f : α → β) (c : computation α) : f <$> c = map f c := rfl @[simp] theorem return_def (a) : (_root_.return a : computation α) = return a := rfl @[simp] theorem map_ret' {α β} : ∀ (f : α → β) (a), f <$> return a = return (f a) := map_ret @[simp] theorem map_think' {α β} : ∀ (f : α → β) s, f <$> think s = think (f <$> s) := map_think theorem mem_map (f : α → β) {a} {s : computation α} (m : a ∈ s) : f a ∈ map f s := by rw ←bind_ret; apply mem_bind m; apply ret_mem theorem exists_of_mem_map {f : α → β} {b : β} {s : computation α} (h : b ∈ map f s) : ∃ a, a ∈ s ∧ f a = b := by rw ←bind_ret at h; exact let ⟨a, as, fb⟩ := exists_of_mem_bind h in ⟨a, as, mem_unique (ret_mem _) fb⟩ instance terminates_map (f : α → β) (s : computation α) [terminates s] : terminates (map f s) := by rw ←bind_ret; apply_instance theorem terminates_map_iff (f : α → β) (s : computation α) : terminates (map f s) ↔ terminates s := ⟨λ⟨a, h⟩, let ⟨b, h1, _⟩ := exists_of_mem_map h in ⟨_, h1⟩, @computation.terminates_map _ _ _ _⟩ -- Parallel computation /-- `c₁ <|> c₂` calculates `c₁` and `c₂` simultaneously, returning the first one that gives a result. -/ def orelse (c₁ c₂ : computation α) : computation α := @computation.corec α (computation α × computation α) (λ⟨c₁, c₂⟩, match destruct c₁ with | sum.inl a := sum.inl a | sum.inr c₁' := match destruct c₂ with | sum.inl a := sum.inl a | sum.inr c₂' := sum.inr (c₁', c₂') end end) (c₁, c₂) instance : alternative computation := { orelse := @orelse, failure := @empty, ..computation.monad } @[simp] theorem ret_orelse (a : α) (c₂ : computation α) : (return a <|> c₂) = return a := destruct_eq_ret $ by unfold has_orelse.orelse; simp [orelse] @[simp] theorem orelse_ret (c₁ : computation α) (a : α) : (think c₁ <|> return a) = return a := destruct_eq_ret $ by unfold has_orelse.orelse; simp [orelse] @[simp] theorem orelse_think (c₁ c₂ : computation α) : (think c₁ <|> think c₂) = think (c₁ <|> c₂) := destruct_eq_think $ by unfold has_orelse.orelse; simp [orelse] @[simp] theorem empty_orelse (c) : (empty α <|> c) = c := begin apply eq_of_bisim (λc₁ c₂, (empty α <|> c₂) = c₁) _ rfl, intros s' s h, rw ←h, apply cases_on s; intros s; rw think_empty; simp, rw ←think_empty, end @[simp] theorem orelse_empty (c : computation α) : (c <|> empty α) = c := begin apply eq_of_bisim (λc₁ c₂, (c₂ <|> empty α) = c₁) _ rfl, intros s' s h, rw ←h, apply cases_on s; intros s; rw think_empty; simp, rw←think_empty, end /-- `c₁ ~ c₂` asserts that `c₁` and `c₂` either both terminate with the same result, or both loop forever. -/ def equiv (c₁ c₂ : computation α) : Prop := ∀ a, a ∈ c₁ ↔ a ∈ c₂ infix ~ := equiv @[refl] theorem equiv.refl (s : computation α) : s ~ s := λ_, iff.rfl @[symm] theorem equiv.symm {s t : computation α} : s ~ t → t ~ s := λh a, (h a).symm @[trans] theorem equiv.trans {s t u : computation α} : s ~ t → t ~ u → s ~ u := λh1 h2 a, (h1 a).trans (h2 a) theorem equiv.equivalence : equivalence (@equiv α) := ⟨@equiv.refl _, @equiv.symm _, @equiv.trans _⟩ theorem equiv_of_mem {s t : computation α} {a} (h1 : a ∈ s) (h2 : a ∈ t) : s ~ t := λa', ⟨λma, by rw mem_unique ma h1; exact h2, λma, by rw mem_unique ma h2; exact h1⟩ theorem terminates_congr {c₁ c₂ : computation α} (h : c₁ ~ c₂) : terminates c₁ ↔ terminates c₂ := exists_congr h theorem promises_congr {c₁ c₂ : computation α} (h : c₁ ~ c₂) (a) : c₁ ~> a ↔ c₂ ~> a := forall_congr (λa', imp_congr (h a') iff.rfl) theorem get_equiv {c₁ c₂ : computation α} (h : c₁ ~ c₂) [terminates c₁] [terminates c₂] : get c₁ = get c₂ := get_eq_of_mem _ $ (h _).2 $ get_mem _ theorem think_equiv (s : computation α) : think s ~ s := λ a, ⟨of_think_mem, think_mem⟩ theorem thinkN_equiv (s : computation α) (n) : thinkN s n ~ s := λ a, thinkN_mem n theorem bind_congr {s1 s2 : computation α} {f1 f2 : α → computation β} (h1 : s1 ~ s2) (h2 : ∀ a, f1 a ~ f2 a) : bind s1 f1 ~ bind s2 f2 := λ b, ⟨λh, let ⟨a, ha, hb⟩ := exists_of_mem_bind h in mem_bind ((h1 a).1 ha) ((h2 a b).1 hb), λh, let ⟨a, ha, hb⟩ := exists_of_mem_bind h in mem_bind ((h1 a).2 ha) ((h2 a b).2 hb)⟩ theorem equiv_ret_of_mem {s : computation α} {a} (h : a ∈ s) : s ~ return a := equiv_of_mem h (ret_mem _) /-- `lift_rel R ca cb` is a generalization of `equiv` to relations other than equality. It asserts that if `ca` terminates with `a`, then `cb` terminates with some `b` such that `R a b`, and if `cb` terminates with `b` then `ca` terminates with some `a` such that `R a b`. -/ def lift_rel (R : α → β → Prop) (ca : computation α) (cb : computation β) : Prop := (∀ {a}, a ∈ ca → ∃ {b}, b ∈ cb ∧ R a b) ∧ ∀ {b}, b ∈ cb → ∃ {a}, a ∈ ca ∧ R a b theorem lift_rel.swap (R : α → β → Prop) (ca : computation α) (cb : computation β) : lift_rel (function.swap R) cb ca ↔ lift_rel R ca cb := and_comm _ _ theorem lift_eq_iff_equiv (c₁ c₂ : computation α) : lift_rel (=) c₁ c₂ ↔ c₁ ~ c₂ := ⟨λ⟨h1, h2⟩ a, ⟨λ a1, let ⟨b, b2, ab⟩ := h1 a1 in by rwa ab, λ a2, let ⟨b, b1, ab⟩ := h2 a2 in by rwa ←ab⟩, λe, ⟨λ a a1, ⟨a, (e _).1 a1, rfl⟩, λ a a2, ⟨a, (e _).2 a2, rfl⟩⟩⟩ theorem lift_rel.refl (R : α → α → Prop) (H : reflexive R) : reflexive (lift_rel R) := λ s, ⟨λ a as, ⟨a, as, H a⟩, λ b bs, ⟨b, bs, H b⟩⟩ theorem lift_rel.symm (R : α → α → Prop) (H : symmetric R) : symmetric (lift_rel R) := λ s1 s2 ⟨l, r⟩, ⟨λ a a2, let ⟨b, b1, ab⟩ := r a2 in ⟨b, b1, H ab⟩, λ a a1, let ⟨b, b2, ab⟩ := l a1 in ⟨b, b2, H ab⟩⟩ theorem lift_rel.trans (R : α → α → Prop) (H : transitive R) : transitive (lift_rel R) := λ s1 s2 s3 ⟨l1, r1⟩ ⟨l2, r2⟩, ⟨λ a a1, let ⟨b, b2, ab⟩ := l1 a1, ⟨c, c3, bc⟩ := l2 b2 in ⟨c, c3, H ab bc⟩, λ c c3, let ⟨b, b2, bc⟩ := r2 c3, ⟨a, a1, ab⟩ := r1 b2 in ⟨a, a1, H ab bc⟩⟩ theorem lift_rel.equiv (R : α → α → Prop) : equivalence R → equivalence (lift_rel R) | ⟨refl, symm, trans⟩ := ⟨lift_rel.refl R refl, lift_rel.symm R symm, lift_rel.trans R trans⟩ theorem lift_rel.imp {R S : α → β → Prop} (H : ∀ {a b}, R a b → S a b) (s t) : lift_rel R s t → lift_rel S s t | ⟨l, r⟩ := ⟨λ a as, let ⟨b, bt, ab⟩ := l as in ⟨b, bt, H ab⟩, λ b bt, let ⟨a, as, ab⟩ := r bt in ⟨a, as, H ab⟩⟩ theorem terminates_of_lift_rel {R : α → β → Prop} {s t} : lift_rel R s t → (terminates s ↔ terminates t) | ⟨l, r⟩ := ⟨λ ⟨a, as⟩, let ⟨b, bt, ab⟩ := l as in ⟨b, bt⟩, λ ⟨b, bt⟩, let ⟨a, as, ab⟩ := r bt in ⟨a, as⟩⟩ theorem rel_of_lift_rel {R : α → β → Prop} {ca cb} : lift_rel R ca cb → ∀ {a b}, a ∈ ca → b ∈ cb → R a b | ⟨l, r⟩ a b ma mb := let ⟨b', mb', ab'⟩ := l ma in by rw mem_unique mb mb'; exact ab' theorem lift_rel_of_mem {R : α → β → Prop} {a b ca cb} (ma : a ∈ ca) (mb : b ∈ cb) (ab : R a b) : lift_rel R ca cb := ⟨λ a' ma', by rw mem_unique ma' ma; exact ⟨b, mb, ab⟩, λ b' mb', by rw mem_unique mb' mb; exact ⟨a, ma, ab⟩⟩ theorem exists_of_lift_rel_left {R : α → β → Prop} {ca cb} (H : lift_rel R ca cb) {a} (h : a ∈ ca) : ∃ {b}, b ∈ cb ∧ R a b := H.left h theorem exists_of_lift_rel_right {R : α → β → Prop} {ca cb} (H : lift_rel R ca cb) {b} (h : b ∈ cb) : ∃ {a}, a ∈ ca ∧ R a b := H.right h theorem lift_rel_def {R : α → β → Prop} {ca cb} : lift_rel R ca cb ↔ (terminates ca ↔ terminates cb) ∧ ∀ {a b}, a ∈ ca → b ∈ cb → R a b := ⟨λh, ⟨terminates_of_lift_rel h, λ a b ma mb, let ⟨b', mb', ab⟩ := h.left ma in by rwa mem_unique mb mb'⟩, λ⟨l, r⟩, ⟨λ a ma, let ⟨b, mb⟩ := l.1 ⟨_, ma⟩ in ⟨b, mb, r ma mb⟩, λ b mb, let ⟨a, ma⟩ := l.2 ⟨_, mb⟩ in ⟨a, ma, r ma mb⟩⟩⟩ theorem lift_rel_bind {δ} (R : α → β → Prop) (S : γ → δ → Prop) {s1 : computation α} {s2 : computation β} {f1 : α → computation γ} {f2 : β → computation δ} (h1 : lift_rel R s1 s2) (h2 : ∀ {a b}, R a b → lift_rel S (f1 a) (f2 b)) : lift_rel S (bind s1 f1) (bind s2 f2) := let ⟨l1, r1⟩ := h1 in ⟨λ c cB, let ⟨a, a1, c₁⟩ := exists_of_mem_bind cB, ⟨b, b2, ab⟩ := l1 a1, ⟨l2, r2⟩ := h2 ab, ⟨d, d2, cd⟩ := l2 c₁ in ⟨_, mem_bind b2 d2, cd⟩, λ d dB, let ⟨b, b1, d1⟩ := exists_of_mem_bind dB, ⟨a, a2, ab⟩ := r1 b1, ⟨l2, r2⟩ := h2 ab, ⟨c, c₂, cd⟩ := r2 d1 in ⟨_, mem_bind a2 c₂, cd⟩⟩ @[simp] theorem lift_rel_return_left (R : α → β → Prop) (a : α) (cb : computation β) : lift_rel R (return a) cb ↔ ∃ {b}, b ∈ cb ∧ R a b := ⟨λ⟨l, r⟩, l (ret_mem _), λ⟨b, mb, ab⟩, ⟨λ a' ma', by rw eq_of_ret_mem ma'; exact ⟨b, mb, ab⟩, λ b' mb', ⟨_, ret_mem _, by rw mem_unique mb' mb; exact ab⟩⟩⟩ @[simp] theorem lift_rel_return_right (R : α → β → Prop) (ca : computation α) (b : β) : lift_rel R ca (return b) ↔ ∃ {a}, a ∈ ca ∧ R a b := by rw [lift_rel.swap, lift_rel_return_left] @[simp] theorem lift_rel_return (R : α → β → Prop) (a : α) (b : β) : lift_rel R (return a) (return b) ↔ R a b := by rw [lift_rel_return_left]; exact ⟨λ⟨b', mb', ab'⟩, by rwa eq_of_ret_mem mb' at ab', λab, ⟨_, ret_mem _, ab⟩⟩ @[simp] theorem lift_rel_think_left (R : α → β → Prop) (ca : computation α) (cb : computation β) : lift_rel R (think ca) cb ↔ lift_rel R ca cb := and_congr (forall_congr $ λb, imp_congr ⟨of_think_mem, think_mem⟩ iff.rfl) (forall_congr $ λb, imp_congr iff.rfl $ exists_congr $ λ b, and_congr ⟨of_think_mem, think_mem⟩ iff.rfl) @[simp] theorem lift_rel_think_right (R : α → β → Prop) (ca : computation α) (cb : computation β) : lift_rel R ca (think cb) ↔ lift_rel R ca cb := by rw [←lift_rel.swap R, ←lift_rel.swap R]; apply lift_rel_think_left theorem lift_rel_mem_cases {R : α → β → Prop} {ca cb} (Ha : ∀ a ∈ ca, lift_rel R ca cb) (Hb : ∀ b ∈ cb, lift_rel R ca cb) : lift_rel R ca cb := ⟨λ a ma, (Ha _ ma).left ma, λ b mb, (Hb _ mb).right mb⟩ theorem lift_rel_congr {R : α → β → Prop} {ca ca' : computation α} {cb cb' : computation β} (ha : ca ~ ca') (hb : cb ~ cb') : lift_rel R ca cb ↔ lift_rel R ca' cb' := and_congr (forall_congr $ λ a, imp_congr (ha _) $ exists_congr $ λ b, and_congr (hb _) iff.rfl) (forall_congr $ λ b, imp_congr (hb _) $ exists_congr $ λ a, and_congr (ha _) iff.rfl) theorem lift_rel_map {δ} (R : α → β → Prop) (S : γ → δ → Prop) {s1 : computation α} {s2 : computation β} {f1 : α → γ} {f2 : β → δ} (h1 : lift_rel R s1 s2) (h2 : ∀ {a b}, R a b → S (f1 a) (f2 b)) : lift_rel S (map f1 s1) (map f2 s2) := by rw [←bind_ret, ←bind_ret]; apply lift_rel_bind _ _ h1; simp; exact @h2 theorem map_congr (R : α → α → Prop) (S : β → β → Prop) {s1 s2 : computation α} {f : α → β} (h1 : s1 ~ s2) : map f s1 ~ map f s2 := by rw [←lift_eq_iff_equiv]; exact lift_rel_map eq _ ((lift_eq_iff_equiv _ _).2 h1) (λ a b, congr_arg _) def lift_rel_aux (R : α → β → Prop) (C : computation α → computation β → Prop) : α ⊕ computation α → β ⊕ computation β → Prop | (sum.inl a) (sum.inl b) := R a b | (sum.inl a) (sum.inr cb) := ∃ {b}, b ∈ cb ∧ R a b | (sum.inr ca) (sum.inl b) := ∃ {a}, a ∈ ca ∧ R a b | (sum.inr ca) (sum.inr cb) := C ca cb attribute [simp] lift_rel_aux @[simp] lemma lift_rel_aux.ret_left (R : α → β → Prop) (C : computation α → computation β → Prop) (a cb) : lift_rel_aux R C (sum.inl a) (destruct cb) ↔ ∃ {b}, b ∈ cb ∧ R a b := begin apply cb.cases_on (λ b, _) (λ cb, _), { exact ⟨λ h, ⟨_, ret_mem _, h⟩, λ ⟨b', mb, h⟩, by rw [mem_unique (ret_mem _) mb]; exact h⟩ }, { rw [destruct_think], exact ⟨λ ⟨b, h, r⟩, ⟨b, think_mem h, r⟩, λ ⟨b, h, r⟩, ⟨b, of_think_mem h, r⟩⟩ } end theorem lift_rel_aux.swap (R : α → β → Prop) (C) (a b) : lift_rel_aux (function.swap R) (function.swap C) b a = lift_rel_aux R C a b := by cases a with a ca; cases b with b cb; simp only [lift_rel_aux] @[simp] lemma lift_rel_aux.ret_right (R : α → β → Prop) (C : computation α → computation β → Prop) (b ca) : lift_rel_aux R C (destruct ca) (sum.inl b) ↔ ∃ {a}, a ∈ ca ∧ R a b := by rw [←lift_rel_aux.swap, lift_rel_aux.ret_left] theorem lift_rel_rec.lem {R : α → β → Prop} (C : computation α → computation β → Prop) (H : ∀ {ca cb}, C ca cb → lift_rel_aux R C (destruct ca) (destruct cb)) (ca cb) (Hc : C ca cb) (a) (ha : a ∈ ca) : lift_rel R ca cb := begin revert cb, refine mem_rec_on ha _ (λ ca' IH, _); intros cb Hc; have h := H Hc, { simp at h, simp [h] }, { have h := H Hc, simp, revert h, apply cb.cases_on (λ b, _) (λ cb', _); intro h; simp at h; simp [h], exact IH _ h } end theorem lift_rel_rec {R : α → β → Prop} (C : computation α → computation β → Prop) (H : ∀ {ca cb}, C ca cb → lift_rel_aux R C (destruct ca) (destruct cb)) (ca cb) (Hc : C ca cb) : lift_rel R ca cb := lift_rel_mem_cases (lift_rel_rec.lem C @H ca cb Hc) (λ b hb, (lift_rel.swap _ _ _).2 $ lift_rel_rec.lem (function.swap C) (λ cb ca h, cast (lift_rel_aux.swap _ _ _ _).symm $ H h) cb ca Hc b hb) end computation
9647a196233f2c835c675c4763ee6f460cde2a51
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/topology/algebra/uniform_group.lean
32e163dcd874b3c81cae91958eba013845fc8967
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
18,134
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Johannes Hölzl -/ import topology.uniform_space.uniform_embedding import topology.uniform_space.complete_separated import topology.algebra.group import tactic.abel /-! # Uniform structure on topological groups * `topological_add_group.to_uniform_space` and `topological_add_group_is_uniform` can be used to construct a canonical uniformity for a topological add group. * extension of ℤ-bilinear maps to complete groups (useful for ring completions) -/ noncomputable theory open_locale classical uniformity topological_space filter section uniform_add_group open filter set variables {α : Type*} {β : Type*} /-- A uniform (additive) group is a group in which the addition and negation are uniformly continuous. -/ class uniform_add_group (α : Type*) [uniform_space α] [add_group α] : Prop := (uniform_continuous_sub : uniform_continuous (λp:α×α, p.1 - p.2)) theorem uniform_add_group.mk' {α} [uniform_space α] [add_group α] (h₁ : uniform_continuous (λp:α×α, p.1 + p.2)) (h₂ : uniform_continuous (λp:α, -p)) : uniform_add_group α := ⟨by simpa only [sub_eq_add_neg] using h₁.comp (uniform_continuous_fst.prod_mk (h₂.comp uniform_continuous_snd))⟩ variables [uniform_space α] [add_group α] [uniform_add_group α] lemma uniform_continuous_sub : uniform_continuous (λp:α×α, p.1 - p.2) := uniform_add_group.uniform_continuous_sub lemma uniform_continuous.sub [uniform_space β] {f : β → α} {g : β → α} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (λx, f x - g x) := uniform_continuous_sub.comp (hf.prod_mk hg) lemma uniform_continuous.neg [uniform_space β] {f : β → α} (hf : uniform_continuous f) : uniform_continuous (λx, - f x) := have uniform_continuous (λx, 0 - f x), from uniform_continuous_const.sub hf, by simp * at * lemma uniform_continuous_neg : uniform_continuous (λx:α, - x) := uniform_continuous_id.neg lemma uniform_continuous.add [uniform_space β] {f : β → α} {g : β → α} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (λx, f x + g x) := have uniform_continuous (λx, f x - - g x), from hf.sub hg.neg, by simp [*, sub_eq_add_neg] at * lemma uniform_continuous_add : uniform_continuous (λp:α×α, p.1 + p.2) := uniform_continuous_fst.add uniform_continuous_snd @[priority 10] instance uniform_add_group.to_topological_add_group : topological_add_group α := { continuous_add := uniform_continuous_add.continuous, continuous_neg := uniform_continuous_neg.continuous } instance [uniform_space β] [add_group β] [uniform_add_group β] : uniform_add_group (α × β) := ⟨((uniform_continuous_fst.comp uniform_continuous_fst).sub (uniform_continuous_fst.comp uniform_continuous_snd)).prod_mk ((uniform_continuous_snd.comp uniform_continuous_fst).sub (uniform_continuous_snd.comp uniform_continuous_snd))⟩ lemma uniformity_translate (a : α) : (𝓤 α).map (λx:α×α, (x.1 + a, x.2 + a)) = 𝓤 α := le_antisymm (uniform_continuous_id.add uniform_continuous_const) (calc 𝓤 α = ((𝓤 α).map (λx:α×α, (x.1 + -a, x.2 + -a))).map (λx:α×α, (x.1 + a, x.2 + a)) : by simp [filter.map_map, (∘)]; exact filter.map_id.symm ... ≤ (𝓤 α).map (λx:α×α, (x.1 + a, x.2 + a)) : filter.map_mono (uniform_continuous_id.add uniform_continuous_const)) lemma uniform_embedding_translate (a : α) : uniform_embedding (λx:α, x + a) := { comap_uniformity := begin rw [← uniformity_translate a, comap_map] {occs := occurrences.pos [1]}, rintros ⟨p₁, p₂⟩ ⟨q₁, q₂⟩, simp [prod.eq_iff_fst_eq_snd_eq] {contextual := tt} end, inj := add_left_injective a } section variables (α) lemma uniformity_eq_comap_nhds_zero : 𝓤 α = comap (λx:α×α, x.2 - x.1) (𝓝 (0:α)) := begin rw [nhds_eq_comap_uniformity, filter.comap_comap], refine le_antisymm (filter.map_le_iff_le_comap.1 _) _, { assume s hs, rcases mem_uniformity_of_uniform_continuous_invariant uniform_continuous_sub hs with ⟨t, ht, hts⟩, refine mem_map.2 (mem_of_superset ht _), rintros ⟨a, b⟩, simpa [subset_def] using hts a b a }, { assume s hs, rcases mem_uniformity_of_uniform_continuous_invariant uniform_continuous_add hs with ⟨t, ht, hts⟩, refine ⟨_, ht, _⟩, rintros ⟨a, b⟩, simpa [subset_def] using hts 0 (b - a) a } end end lemma group_separation_rel (x y : α) : (x, y) ∈ separation_rel α ↔ x - y ∈ closure ({0} : set α) := have embedding (λa, a + (y - x)), from (uniform_embedding_translate (y - x)).embedding, show (x, y) ∈ ⋂₀ (𝓤 α).sets ↔ x - y ∈ closure ({0} : set α), begin rw [this.closure_eq_preimage_closure_image, uniformity_eq_comap_nhds_zero α, sInter_comap_sets], simp [mem_closure_iff_nhds, inter_singleton_nonempty, sub_eq_add_neg, add_assoc] end lemma uniform_continuous_of_tendsto_zero [uniform_space β] [add_group β] [uniform_add_group β] {f : α →+ β} (h : tendsto f (𝓝 0) (𝓝 0)) : uniform_continuous f := begin have : ((λx:β×β, x.2 - x.1) ∘ (λx:α×α, (f x.1, f x.2))) = (λx:α×α, f (x.2 - x.1)), { simp only [f.map_sub] }, rw [uniform_continuous, uniformity_eq_comap_nhds_zero α, uniformity_eq_comap_nhds_zero β, tendsto_comap_iff, this], exact tendsto.comp h tendsto_comap end lemma add_monoid_hom.uniform_continuous_of_continuous_at_zero [uniform_space β] [add_group β] [uniform_add_group β] (f : α →+ β) (hf : continuous_at f 0) : uniform_continuous f := uniform_continuous_of_tendsto_zero (by simpa using hf.tendsto) lemma uniform_continuous_of_continuous [uniform_space β] [add_group β] [uniform_add_group β] {f : α →+ β} (h : continuous f) : uniform_continuous f := uniform_continuous_of_tendsto_zero $ suffices tendsto f (𝓝 0) (𝓝 (f 0)), by rwa f.map_zero at this, h.tendsto 0 lemma cauchy_seq.add {ι : Type*} [semilattice_sup ι] {u v : ι → α} (hu : cauchy_seq u) (hv : cauchy_seq v) : cauchy_seq (u + v) := uniform_continuous_add.comp_cauchy_seq (hu.prod hv) end uniform_add_group section topological_add_comm_group universes u v w x open filter variables {G : Type u} [add_comm_group G] [topological_space G] [topological_add_group G] variable (G) /-- The right uniformity on a topological group. -/ def topological_add_group.to_uniform_space : uniform_space G := { uniformity := comap (λp:G×G, p.2 - p.1) (𝓝 0), refl := by refine map_le_iff_le_comap.1 (le_trans _ (pure_le_nhds 0)); simp [set.subset_def] {contextual := tt}, symm := begin suffices : tendsto ((λp, -p) ∘ (λp:G×G, p.2 - p.1)) (comap (λp:G×G, p.2 - p.1) (𝓝 0)) (𝓝 (-0)), { simpa [(∘), tendsto_comap_iff] }, exact tendsto.comp (tendsto.neg tendsto_id) tendsto_comap end, comp := begin intros D H, rw mem_lift'_sets, { rcases H with ⟨U, U_nhds, U_sub⟩, rcases exists_nhds_zero_half U_nhds with ⟨V, ⟨V_nhds, V_sum⟩⟩, existsi ((λp:G×G, p.2 - p.1) ⁻¹' V), have H : (λp:G×G, p.2 - p.1) ⁻¹' V ∈ comap (λp:G×G, p.2 - p.1) (𝓝 (0 : G)), by existsi [V, V_nhds] ; refl, existsi H, have comp_rel_sub : comp_rel ((λp:G×G, p.2 - p.1) ⁻¹' V) ((λp, p.2 - p.1) ⁻¹' V) ⊆ (λp:G×G, p.2 - p.1) ⁻¹' U, begin intros p p_comp_rel, rcases p_comp_rel with ⟨z, ⟨Hz1, Hz2⟩⟩, simpa [sub_eq_add_neg, add_comm, add_left_comm] using V_sum _ Hz1 _ Hz2 end, exact set.subset.trans comp_rel_sub U_sub }, { exact monotone_comp_rel monotone_id monotone_id } end, is_open_uniformity := begin intro S, let S' := λ x, {p : G × G | p.1 = x → p.2 ∈ S}, show is_open S ↔ ∀ (x : G), x ∈ S → S' x ∈ comap (λp:G×G, p.2 - p.1) (𝓝 (0 : G)), rw [is_open_iff_mem_nhds], refine forall_congr (assume a, forall_congr (assume ha, _)), rw [← nhds_translation_sub, mem_comap, mem_comap], refine exists_congr (assume t, exists_congr (assume ht, _)), show (λ (y : G), y - a) ⁻¹' t ⊆ S ↔ (λ (p : G × G), p.snd - p.fst) ⁻¹' t ⊆ S' a, split, { rintros h ⟨x, y⟩ hx rfl, exact h hx }, { rintros h x hx, exact @h (a, x) hx rfl } end } section local attribute [instance] topological_add_group.to_uniform_space lemma uniformity_eq_comap_nhds_zero' : 𝓤 G = comap (λp:G×G, p.2 - p.1) (𝓝 (0 : G)) := rfl variable {G} lemma topological_add_group_is_uniform : uniform_add_group G := have tendsto ((λp:(G×G), p.1 - p.2) ∘ (λp:(G×G)×(G×G), (p.1.2 - p.1.1, p.2.2 - p.2.1))) (comap (λp:(G×G)×(G×G), (p.1.2 - p.1.1, p.2.2 - p.2.1)) ((𝓝 0).prod (𝓝 0))) (𝓝 (0 - 0)) := (tendsto_fst.sub tendsto_snd).comp tendsto_comap, begin constructor, rw [uniform_continuous, uniformity_prod_eq_prod, tendsto_map'_iff, uniformity_eq_comap_nhds_zero' G, tendsto_comap_iff, prod_comap_comap_eq], simpa [(∘), sub_eq_add_neg, add_comm, add_left_comm] using this end local attribute [instance] topological_add_group_is_uniform open set lemma topological_add_group.separated_iff_zero_closed : separated_space G ↔ is_closed ({0} : set G) := begin rw [separated_space_iff, ← closure_eq_iff_is_closed], split; intro h, { apply subset.antisymm, { intros x x_in, have := group_separation_rel x 0, rw sub_zero at this, rw [← this, h] at x_in, change x = 0 at x_in, simp [x_in] }, { exact subset_closure } }, { ext p, cases p with x y, rw [group_separation_rel x, h, mem_singleton_iff, sub_eq_zero], refl } end lemma topological_add_group.separated_of_zero_sep (H : ∀ x : G, x ≠ 0 → ∃ U ∈ nhds (0 : G), x ∉ U) : separated_space G:= begin rw [topological_add_group.separated_iff_zero_closed, ← is_open_compl_iff, is_open_iff_mem_nhds], intros x x_not, have : x ≠ 0, from mem_compl_singleton_iff.mp x_not, rcases H x this with ⟨U, U_in, xU⟩, rw ← nhds_zero_symm G at U_in, rcases U_in with ⟨W, W_in, UW⟩, rw ← nhds_translation_add_neg, use [W, W_in], rw subset_compl_comm, suffices : -x ∉ W, by simpa, exact λ h, xU (UW h) end end lemma to_uniform_space_eq {G : Type*} [u : uniform_space G] [add_comm_group G] [uniform_add_group G] : topological_add_group.to_uniform_space G = u := begin ext : 1, show @uniformity G (topological_add_group.to_uniform_space G) = 𝓤 G, rw [uniformity_eq_comap_nhds_zero' G, uniformity_eq_comap_nhds_zero G] end end topological_add_comm_group open add_comm_group filter set function section variables {α : Type*} {β : Type*} variables [topological_space α] [add_comm_group α] [topological_add_group α] -- β is a dense subgroup of α, inclusion is denoted by e variables [topological_space β] [add_comm_group β] variables {e : β →+ α} (de : dense_inducing e) include de lemma tendsto_sub_comap_self (x₀ : α) : tendsto (λt:β×β, t.2 - t.1) (comap (λp:β×β, (e p.1, e p.2)) $ 𝓝 (x₀, x₀)) (𝓝 0) := begin have comm : (λx:α×α, x.2-x.1) ∘ (λt:β×β, (e t.1, e t.2)) = e ∘ (λt:β×β, t.2 - t.1), { ext t, change e t.2 - e t.1 = e (t.2 - t.1), rwa ← e.map_sub t.2 t.1 }, have lim : tendsto (λ x : α × α, x.2-x.1) (𝓝 (x₀, x₀)) (𝓝 (e 0)), { simpa using (continuous_sub.comp (@continuous_swap α α _ _)).tendsto (x₀, x₀) }, simpa using de.tendsto_comap_nhds_nhds lim comm end end namespace dense_inducing variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} variables {G : Type*} -- β is a dense subgroup of α, inclusion is denoted by e -- δ is a dense subgroup of γ, inclusion is denoted by f variables [topological_space α] [add_comm_group α] [topological_add_group α] variables [topological_space β] [add_comm_group β] [topological_add_group β] variables [topological_space γ] [add_comm_group γ] [topological_add_group γ] variables [topological_space δ] [add_comm_group δ] [topological_add_group δ] variables [uniform_space G] [add_comm_group G] [uniform_add_group G] [separated_space G] [complete_space G] variables {e : β →+ α} (de : dense_inducing e) variables {f : δ →+ γ} (df : dense_inducing f) variables {φ : β →+ δ →+ G} local notation `Φ` := λ p : β × δ, φ p.1 p.2 variables (hφ : continuous Φ) include de df hφ variables {W' : set G} (W'_nhd : W' ∈ 𝓝 (0 : G)) include W'_nhd private lemma extend_Z_bilin_aux (x₀ : α) (y₁ : δ) : ∃ U₂ ∈ comap e (𝓝 x₀), ∀ x x' ∈ U₂, Φ (x' - x, y₁) ∈ W' := begin let Nx := 𝓝 x₀, let ee := λ u : β × β, (e u.1, e u.2), have lim1 : tendsto (λ a : β × β, (a.2 - a.1, y₁)) (comap e Nx ×ᶠ comap e Nx) (𝓝 (0, y₁)), { have := tendsto.prod_mk (tendsto_sub_comap_self de x₀) (tendsto_const_nhds : tendsto (λ (p : β × β), y₁) (comap ee $ 𝓝 (x₀, x₀)) (𝓝 y₁)), rw [nhds_prod_eq, prod_comap_comap_eq, ←nhds_prod_eq], exact (this : _) }, have lim2 : tendsto Φ (𝓝 (0, y₁)) (𝓝 0), by simpa using hφ.tendsto (0, y₁), have lim := lim2.comp lim1, rw tendsto_prod_self_iff at lim, exact lim W' W'_nhd end private lemma extend_Z_bilin_key (x₀ : α) (y₀ : γ) : ∃ U ∈ comap e (𝓝 x₀), ∃ V ∈ comap f (𝓝 y₀), ∀ x x' ∈ U, ∀ y y' ∈ V, Φ (x', y') - Φ (x, y) ∈ W' := begin let Nx := 𝓝 x₀, let Ny := 𝓝 y₀, let dp := dense_inducing.prod de df, let ee := λ u : β × β, (e u.1, e u.2), let ff := λ u : δ × δ, (f u.1, f u.2), have lim_φ : filter.tendsto Φ (𝓝 (0, 0)) (𝓝 0), { simpa using hφ.tendsto (0, 0) }, have lim_φ_sub_sub : tendsto (λ (p : (β × β) × (δ × δ)), Φ (p.1.2 - p.1.1, p.2.2 - p.2.1)) ((comap ee $ 𝓝 (x₀, x₀)) ×ᶠ (comap ff $ 𝓝 (y₀, y₀))) (𝓝 0), { have lim_sub_sub : tendsto (λ (p : (β × β) × δ × δ), (p.1.2 - p.1.1, p.2.2 - p.2.1)) ((comap ee (𝓝 (x₀, x₀))) ×ᶠ (comap ff (𝓝 (y₀, y₀)))) (𝓝 0 ×ᶠ 𝓝 0), { have := filter.prod_mono (tendsto_sub_comap_self de x₀) (tendsto_sub_comap_self df y₀), rwa prod_map_map_eq at this }, rw ← nhds_prod_eq at lim_sub_sub, exact tendsto.comp lim_φ lim_sub_sub }, rcases exists_nhds_zero_quarter W'_nhd with ⟨W, W_nhd, W4⟩, have : ∃ U₁ ∈ comap e (𝓝 x₀), ∃ V₁ ∈ comap f (𝓝 y₀), ∀ x x' ∈ U₁, ∀ y y' ∈ V₁, Φ (x'-x, y'-y) ∈ W, { have := tendsto_prod_iff.1 lim_φ_sub_sub W W_nhd, repeat { rw [nhds_prod_eq, ←prod_comap_comap_eq] at this }, rcases this with ⟨U, U_in, V, V_in, H⟩, rw [mem_prod_same_iff] at U_in V_in, rcases U_in with ⟨U₁, U₁_in, HU₁⟩, rcases V_in with ⟨V₁, V₁_in, HV₁⟩, existsi [U₁, U₁_in, V₁, V₁_in], intros x x' x_in x'_in y y' y_in y'_in, exact H _ _ (HU₁ (mk_mem_prod x_in x'_in)) (HV₁ (mk_mem_prod y_in y'_in)) }, rcases this with ⟨U₁, U₁_nhd, V₁, V₁_nhd, H⟩, obtain ⟨x₁, x₁_in⟩ : U₁.nonempty := ((de.comap_nhds_ne_bot _).nonempty_of_mem U₁_nhd), obtain ⟨y₁, y₁_in⟩ : V₁.nonempty := ((df.comap_nhds_ne_bot _).nonempty_of_mem V₁_nhd), have cont_flip : continuous (λ p : δ × β, φ.flip p.1 p.2), { show continuous (Φ ∘ prod.swap), from hφ.comp continuous_swap }, rcases (extend_Z_bilin_aux de df hφ W_nhd x₀ y₁) with ⟨U₂, U₂_nhd, HU⟩, rcases (extend_Z_bilin_aux df de cont_flip W_nhd y₀ x₁) with ⟨V₂, V₂_nhd, HV⟩, existsi [U₁ ∩ U₂, inter_mem U₁_nhd U₂_nhd, V₁ ∩ V₂, inter_mem V₁_nhd V₂_nhd], rintros x x' ⟨xU₁, xU₂⟩ ⟨x'U₁, x'U₂⟩ y y' ⟨yV₁, yV₂⟩ ⟨y'V₁, y'V₂⟩, have key_formula : φ x' y' - φ x y = φ(x' - x) y₁ + φ (x' - x) (y' - y₁) + φ x₁ (y' - y) + φ (x - x₁) (y' - y), { simp, abel }, rw key_formula, have h₁ := HU x x' xU₂ x'U₂, have h₂ := H x x' xU₁ x'U₁ y₁ y' y₁_in y'V₁, have h₃ := HV y y' yV₂ y'V₂, have h₄ := H x₁ x x₁_in xU₁ y y' yV₁ y'V₁, exact W4 h₁ h₂ h₃ h₄ end omit W'_nhd open dense_inducing /-- Bourbaki GT III.6.5 Theorem I: ℤ-bilinear continuous maps from dense images into a complete Hausdorff group extend by continuity. Note: Bourbaki assumes that α and β are also complete Hausdorff, but this is not necessary. -/ theorem extend_Z_bilin : continuous (extend (de.prod df) Φ) := begin refine continuous_extend_of_cauchy _ _, rintro ⟨x₀, y₀⟩, split, { apply ne_bot.map, apply comap_ne_bot, intros U h, rcases mem_closure_iff_nhds.1 ((de.prod df).dense (x₀, y₀)) U h with ⟨x, x_in, ⟨z, z_x⟩⟩, existsi z, cc }, { suffices : map (λ (p : (β × δ) × (β × δ)), Φ p.2 - Φ p.1) (comap (λ (p : (β × δ) × β × δ), ((e p.1.1, f p.1.2), (e p.2.1, f p.2.2))) (𝓝 (x₀, y₀) ×ᶠ 𝓝 (x₀, y₀))) ≤ 𝓝 0, by rwa [uniformity_eq_comap_nhds_zero G, prod_map_map_eq, ←map_le_iff_le_comap, filter.map_map, prod_comap_comap_eq], intros W' W'_nhd, have key := extend_Z_bilin_key de df hφ W'_nhd x₀ y₀, rcases key with ⟨U, U_nhd, V, V_nhd, h⟩, rw mem_comap at U_nhd, rcases U_nhd with ⟨U', U'_nhd, U'_sub⟩, rw mem_comap at V_nhd, rcases V_nhd with ⟨V', V'_nhd, V'_sub⟩, rw [mem_map, mem_comap, nhds_prod_eq], existsi set.prod (set.prod U' V') (set.prod U' V'), rw mem_prod_same_iff, simp only [exists_prop], split, { change U' ∈ 𝓝 x₀ at U'_nhd, change V' ∈ 𝓝 y₀ at V'_nhd, have := prod_mem_prod U'_nhd V'_nhd, tauto }, { intros p h', simp only [set.mem_preimage, set.prod_mk_mem_set_prod_eq] at h', rcases p with ⟨⟨x, y⟩, ⟨x', y'⟩⟩, apply h ; tauto } } end end dense_inducing
aa18191ab0c57a01ab4c32dba239031021b7647f
5c5878e769950eabe897ad08485b3ba1a619cea9
/src/categories/tactics/default.lean
a55e47fb57fb4877e5d15a4a73741aff86ccf820
[ "Apache-2.0" ]
permissive
semorrison/lean-category-theory-pr
39dc2077fcb41b438e61be1685e4cbca298767ed
7adc8d91835e883db0fe75aa33661bc1480dbe55
refs/heads/master
1,583,748,682,010
1,535,111,040,000
1,535,111,040,000
128,731,071
1
2
Apache-2.0
1,528,069,880,000
1,523,258,452,000
Lean
UTF-8
Lean
false
false
502
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Stephen Morgan, Scott Morrison import tidy.at_least_one import tidy.backwards_reasoning import tidy.rewrite_all import tidy.injections import tidy.tidy import tidy.transport import category_theory.category @[obviously] meta def obviously_impl := obviously' universes u v open tactic set_option formatter.hide_full_terms false set_option pp.proofs false
c3e1fddc08ba3ad3ffc91eb0b134b9de967571be
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/analysis/calculus/fderiv_symmetric.lean
a21d6ab8b1df8a1ca366f762faa7002f4a2dc5a9
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
19,113
lean
/- Copyright (c) 2021 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.calculus.deriv import analysis.calculus.mean_value import analysis.convex.topology /-! # Symmetry of the second derivative We show that, over the reals, the second derivative is symmetric. The most precise result is `convex.second_derivative_within_at_symmetric`. It asserts that, if a function is differentiable inside a convex set `s` with nonempty interior, and has a second derivative within `s` at a point `x`, then this second derivative at `x` is symmetric. Note that this result does not require continuity of the first derivative. The following particular cases of this statement are especially relevant: `second_derivative_symmetric_of_eventually` asserts that, if a function is differentiable on a neighborhood of `x`, and has a second derivative at `x`, then this second derivative is symmetric. `second_derivative_symmetric` asserts that, if a function is differentiable, and has a second derivative at `x`, then this second derivative is symmetric. ## Implementation note For the proof, we obtain an asymptotic expansion to order two of `f (x + v + w) - f (x + v)`, by using the mean value inequality applied to a suitable function along the segment `[x + v, x + v + w]`. This expansion involves `f'' ⬝ w` as we move along a segment directed by `w` (see `convex.taylor_approx_two_segment`). Consider the alternate sum `f (x + v + w) + f x - f (x + v) - f (x + w)`, corresponding to the values of `f` along a rectangle based at `x` with sides `v` and `w`. One can write it using the two sides directed by `w`, as `(f (x + v + w) - f (x + v)) - (f (x + w) - f x)`. Together with the previous asymptotic expansion, one deduces that it equals `f'' v w + o(1)` when `v, w` tends to `0`. Exchanging the roles of `v` and `w`, one instead gets an asymptotic expansion `f'' w v`, from which the equality `f'' v w = f'' w v` follows. In our most general statement, we only assume that `f` is differentiable inside a convex set `s`, so a few modifications have to be made. Since we don't assume continuity of `f` at `x`, we consider instead the rectangle based at `x + v + w` with sides `v` and `w`, in `convex.is_o_alternate_sum_square`, but the argument is essentially the same. It only works when `v` and `w` both point towards the interior of `s`, to make sure that all the sides of the rectangle are contained in `s` by convexity. The general case follows by linearity, though. -/ open asymptotics set open_locale topological_space variables {E F : Type*} [normed_group E] [normed_space ℝ E] [normed_group F] [normed_space ℝ F] {s : set E} (s_conv : convex ℝ s) {f : E → F} {f' : E → (E →L[ℝ] F)} {f'' : E →L[ℝ] (E →L[ℝ] F)} (hf : ∀ x ∈ interior s, has_fderiv_at f (f' x) x) {x : E} (xs : x ∈ s) (hx : has_fderiv_within_at f' f'' (interior s) x) include s_conv xs hx hf /-- Assume that `f` is differentiable inside a convex set `s`, and that its derivative `f'` is differentiable at a point `x`. Then, given two vectors `v` and `w` pointing inside `s`, one can Taylor-expand to order two the function `f` on the segment `[x + h v, x + h (v + w)]`, giving a bilinear estimate for `f (x + hv + hw) - f (x + hv)` in terms of `f' w` and of `f'' ⬝ w`, up to `o(h^2)`. This is a technical statement used to show that the second derivative is symmetric. -/ lemma convex.taylor_approx_two_segment {v w : E} (hv : x + v ∈ interior s) (hw : x + v + w ∈ interior s) : is_o (λ (h : ℝ), f (x + h • v + h • w) - f (x + h • v) - h • f' x w - h^2 • f'' v w - (h^2/2) • f'' w w) (λ h, h^2) (𝓝[>] (0 : ℝ)) := begin -- it suffices to check that the expression is bounded by `ε * ((∥v∥ + ∥w∥) * ∥w∥) * h^2` for -- small enough `h`, for any positive `ε`. apply is_o.trans_is_O (is_o_iff.2 (λ ε εpos, _)) (is_O_const_mul_self ((∥v∥ + ∥w∥) * ∥w∥) _ _), -- consider a ball of radius `δ` around `x` in which the Taylor approximation for `f''` is -- good up to `δ`. rw [has_fderiv_within_at, has_fderiv_at_filter, is_o_iff] at hx, rcases metric.mem_nhds_within_iff.1 (hx εpos) with ⟨δ, δpos, sδ⟩, have E1 : ∀ᶠ h in 𝓝[>] (0:ℝ), h * (∥v∥ + ∥w∥) < δ, { have : filter.tendsto (λ h, h * (∥v∥ + ∥w∥)) (𝓝[>] (0:ℝ)) (𝓝 (0 * (∥v∥ + ∥w∥))) := (continuous_id.mul continuous_const).continuous_within_at, apply (tendsto_order.1 this).2 δ, simpa only [zero_mul] using δpos }, have E2 : ∀ᶠ h in 𝓝[>] (0:ℝ), (h : ℝ) < 1 := mem_nhds_within_Ioi_iff_exists_Ioo_subset.2 ⟨(1 : ℝ), by simp only [mem_Ioi, zero_lt_one], λ x hx, hx.2⟩, filter_upwards [E1, E2, self_mem_nhds_within] with h hδ h_lt_1 hpos, -- we consider `h` small enough that all points under consideration belong to this ball, -- and also with `0 < h < 1`. replace hpos : 0 < h := hpos, have xt_mem : ∀ t ∈ Icc (0 : ℝ) 1, x + h • v + (t * h) • w ∈ interior s, { assume t ht, have : x + h • v ∈ interior s := s_conv.add_smul_mem_interior xs hv ⟨hpos, h_lt_1.le⟩, rw [← smul_smul], apply s_conv.interior.add_smul_mem this _ ht, rw add_assoc at hw, convert s_conv.add_smul_mem_interior xs hw ⟨hpos, h_lt_1.le⟩ using 1, simp only [add_assoc, smul_add] }, -- define a function `g` on `[0,1]` (identified with `[v, v + w]`) such that `g 1 - g 0` is the -- quantity to be estimated. We will check that its derivative is given by an explicit -- expression `g'`, that we can bound. Then the desired bound for `g 1 - g 0` follows from the -- mean value inequality. let g := λ t, f (x + h • v + (t * h) • w) - (t * h) • f' x w - (t * h^2) • f'' v w - ((t * h)^2/2) • f'' w w, set g' := λ t, f' (x + h • v + (t * h) • w) (h • w) - h • f' x w - h^2 • f'' v w - (t * h^2) • f'' w w with hg', -- check that `g'` is the derivative of `g`, by a straightforward computation have g_deriv : ∀ t ∈ Icc (0 : ℝ) 1, has_deriv_within_at g (g' t) (Icc 0 1) t, { assume t ht, apply_rules [has_deriv_within_at.sub, has_deriv_within_at.add], { refine (hf _ _).comp_has_deriv_within_at _ _, { exact xt_mem t ht }, apply_rules [has_deriv_at.has_deriv_within_at, has_deriv_at.const_add, has_deriv_at.smul_const, has_deriv_at_mul_const] }, { apply_rules [has_deriv_at.has_deriv_within_at, has_deriv_at.smul_const, has_deriv_at_mul_const] }, { apply_rules [has_deriv_at.has_deriv_within_at, has_deriv_at.smul_const, has_deriv_at_mul_const] }, { suffices H : has_deriv_within_at (λ u, ((u * h) ^ 2 / 2) • f'' w w) (((((2 : ℕ) : ℝ) * (t * h) ^ (2 - 1) * (1 * h))/2) • f'' w w) (Icc 0 1) t, { convert H using 2, simp only [one_mul, nat.cast_bit0, pow_one, nat.cast_one], ring }, apply_rules [has_deriv_at.has_deriv_within_at, has_deriv_at.smul_const, has_deriv_at_id', has_deriv_at.pow, has_deriv_at.mul_const] } }, -- check that `g'` is uniformly bounded, with a suitable bound `ε * ((∥v∥ + ∥w∥) * ∥w∥) * h^2`. have g'_bound : ∀ t ∈ Ico (0 : ℝ) 1, ∥g' t∥ ≤ ε * ((∥v∥ + ∥w∥) * ∥w∥) * h^2, { assume t ht, have I : ∥h • v + (t * h) • w∥ ≤ h * (∥v∥ + ∥w∥) := calc ∥h • v + (t * h) • w∥ ≤ ∥h • v∥ + ∥(t * h) • w∥ : norm_add_le _ _ ... = h * ∥v∥ + t * (h * ∥w∥) : by simp only [norm_smul, real.norm_eq_abs, hpos.le, abs_of_nonneg, abs_mul, ht.left, mul_assoc] ... ≤ h * ∥v∥ + 1 * (h * ∥w∥) : add_le_add le_rfl (mul_le_mul_of_nonneg_right ht.2.le (mul_nonneg hpos.le (norm_nonneg _))) ... = h * (∥v∥ + ∥w∥) : by ring, calc ∥g' t∥ = ∥(f' (x + h • v + (t * h) • w) - f' x - f'' (h • v + (t * h) • w)) (h • w)∥ : begin rw hg', have : h * (t * h) = t * (h * h), by ring, simp only [continuous_linear_map.coe_sub', continuous_linear_map.map_add, pow_two, continuous_linear_map.add_apply, pi.smul_apply, smul_sub, smul_add, smul_smul, ← sub_sub, continuous_linear_map.coe_smul', pi.sub_apply, continuous_linear_map.map_smul, this] end ... ≤ ∥f' (x + h • v + (t * h) • w) - f' x - f'' (h • v + (t * h) • w)∥ * ∥h • w∥ : continuous_linear_map.le_op_norm _ _ ... ≤ (ε * ∥h • v + (t * h) • w∥) * (∥h • w∥) : begin apply mul_le_mul_of_nonneg_right _ (norm_nonneg _), have H : x + h • v + (t * h) • w ∈ metric.ball x δ ∩ interior s, { refine ⟨_, xt_mem t ⟨ht.1, ht.2.le⟩⟩, rw [add_assoc, add_mem_ball_iff_norm], exact I.trans_lt hδ }, simpa only [mem_set_of_eq, add_assoc x, add_sub_cancel'] using sδ H, end ... ≤ (ε * (∥h • v∥ + ∥h • w∥)) * (∥h • w∥) : begin apply mul_le_mul_of_nonneg_right _ (norm_nonneg _), apply mul_le_mul_of_nonneg_left _ (εpos.le), apply (norm_add_le _ _).trans, refine add_le_add le_rfl _, simp only [norm_smul, real.norm_eq_abs, abs_mul, abs_of_nonneg, ht.1, hpos.le, mul_assoc], exact mul_le_of_le_one_left (mul_nonneg hpos.le (norm_nonneg _)) ht.2.le, end ... = ε * ((∥v∥ + ∥w∥) * ∥w∥) * h^2 : by { simp only [norm_smul, real.norm_eq_abs, abs_mul, abs_of_nonneg, hpos.le], ring } }, -- conclude using the mean value inequality have I : ∥g 1 - g 0∥ ≤ ε * ((∥v∥ + ∥w∥) * ∥w∥) * h^2, by simpa only [mul_one, sub_zero] using norm_image_sub_le_of_norm_deriv_le_segment' g_deriv g'_bound 1 (right_mem_Icc.2 zero_le_one), convert I using 1, { congr' 1, dsimp only [g], simp only [nat.one_ne_zero, add_zero, one_mul, zero_div, zero_mul, sub_zero, zero_smul, ne.def, not_false_iff, bit0_eq_zero, zero_pow'], abel }, { simp only [real.norm_eq_abs, abs_mul, add_nonneg (norm_nonneg v) (norm_nonneg w), abs_of_nonneg, mul_assoc, pow_bit0_abs, norm_nonneg, abs_pow] } end /-- One can get `f'' v w` as the limit of `h ^ (-2)` times the alternate sum of the values of `f` along the vertices of a quadrilateral with sides `h v` and `h w` based at `x`. In a setting where `f` is not guaranteed to be continuous at `f`, we can still get this if we use a quadrilateral based at `h v + h w`. -/ lemma convex.is_o_alternate_sum_square {v w : E} (h4v : x + (4 : ℝ) • v ∈ interior s) (h4w : x + (4 : ℝ) • w ∈ interior s) : is_o (λ (h : ℝ), f (x + h • (2 • v + 2 • w)) + f (x + h • (v + w)) - f (x + h • (2 • v + w)) - f (x + h • (v + 2 • w)) - h^2 • f'' v w) (λ h, h^2) (𝓝[>] (0 : ℝ)) := begin have A : (1 : ℝ)/2 ∈ Ioc (0 : ℝ) 1 := ⟨by norm_num, by norm_num⟩, have B : (1 : ℝ)/2 ∈ Icc (0 : ℝ) 1 := ⟨by norm_num, by norm_num⟩, have C : ∀ (w : E), (2 : ℝ) • w = 2 • w := λ w, by simp only [two_smul], have h2v2w : x + (2 : ℝ) • v + (2 : ℝ) • w ∈ interior s, { convert s_conv.interior.add_smul_sub_mem h4v h4w B using 1, simp only [smul_sub, smul_smul, one_div, add_sub_add_left_eq_sub, mul_add, add_smul], norm_num, simp only [show (4 : ℝ) = (2 : ℝ) + (2 : ℝ), by norm_num, add_smul], abel }, have h2vww : x + (2 • v + w) + w ∈ interior s, { convert h2v2w using 1, simp only [two_smul], abel }, have h2v : x + (2 : ℝ) • v ∈ interior s, { convert s_conv.add_smul_sub_mem_interior xs h4v A using 1, simp only [smul_smul, one_div, add_sub_cancel', add_right_inj], norm_num }, have h2w : x + (2 : ℝ) • w ∈ interior s, { convert s_conv.add_smul_sub_mem_interior xs h4w A using 1, simp only [smul_smul, one_div, add_sub_cancel', add_right_inj], norm_num }, have hvw : x + (v + w) ∈ interior s, { convert s_conv.add_smul_sub_mem_interior xs h2v2w A using 1, simp only [smul_smul, one_div, add_sub_cancel', add_right_inj, smul_add, smul_sub], norm_num, abel }, have h2vw : x + (2 • v + w) ∈ interior s, { convert s_conv.interior.add_smul_sub_mem h2v h2v2w B using 1, simp only [smul_add, smul_sub, smul_smul, ← C], norm_num, abel }, have hvww : x + (v + w) + w ∈ interior s, { convert s_conv.interior.add_smul_sub_mem h2w h2v2w B using 1, simp only [one_div, add_sub_cancel', inv_smul_smul₀, add_sub_add_right_eq_sub, ne.def, not_false_iff, bit0_eq_zero, one_ne_zero], rw two_smul, abel }, have TA1 := s_conv.taylor_approx_two_segment hf xs hx h2vw h2vww, have TA2 := s_conv.taylor_approx_two_segment hf xs hx hvw hvww, convert TA1.sub TA2, ext h, simp only [two_smul, smul_add, ← add_assoc, continuous_linear_map.map_add, continuous_linear_map.add_apply, pi.smul_apply, continuous_linear_map.coe_smul', continuous_linear_map.map_smul], abel, end /-- Assume that `f` is differentiable inside a convex set `s`, and that its derivative `f'` is differentiable at a point `x`. Then, given two vectors `v` and `w` pointing inside `s`, one has `f'' v w = f'' w v`. Superseded by `convex.second_derivative_within_at_symmetric`, which removes the assumption that `v` and `w` point inside `s`. -/ lemma convex.second_derivative_within_at_symmetric_of_mem_interior {v w : E} (h4v : x + (4 : ℝ) • v ∈ interior s) (h4w : x + (4 : ℝ) • w ∈ interior s) : f'' w v = f'' v w := begin have A : is_o (λ (h : ℝ), h^2 • (f'' w v- f'' v w)) (λ h, h^2) (𝓝[>] (0 : ℝ)), { convert (s_conv.is_o_alternate_sum_square hf xs hx h4v h4w).sub (s_conv.is_o_alternate_sum_square hf xs hx h4w h4v), ext h, simp only [add_comm, smul_add, smul_sub], abel }, have B : is_o (λ (h : ℝ), f'' w v - f'' v w) (λ h, (1 : ℝ)) (𝓝[>] (0 : ℝ)), { have : is_O (λ (h : ℝ), 1/h^2) (λ h, 1/h^2) (𝓝[>] (0 : ℝ)) := is_O_refl _ _, have C := this.smul_is_o A, apply C.congr' _ _, { filter_upwards [self_mem_nhds_within], assume h hpos, rw [← one_smul ℝ (f'' w v - f'' v w), smul_smul, smul_smul], congr' 1, field_simp [has_lt.lt.ne' hpos] }, { filter_upwards [self_mem_nhds_within] with _ hpos, field_simp [has_lt.lt.ne' hpos, has_scalar.smul], }, }, simpa only [sub_eq_zero] using (is_o_const_const_iff (@one_ne_zero ℝ _ _)).1 B, end omit s_conv xs hx hf /-- If a function is differentiable inside a convex set with nonempty interior, and has a second derivative at a point of this convex set, then this second derivative is symmetric. -/ theorem convex.second_derivative_within_at_symmetric {s : set E} (s_conv : convex ℝ s) (hne : (interior s).nonempty) {f : E → F} {f' : E → (E →L[ℝ] F)} {f'' : E →L[ℝ] (E →L[ℝ] F)} (hf : ∀ x ∈ interior s, has_fderiv_at f (f' x) x) {x : E} (xs : x ∈ s) (hx : has_fderiv_within_at f' f'' (interior s) x) (v w : E) : f'' v w = f'' w v := begin /- we work around a point `x + 4 z` in the interior of `s`. For any vector `m`, then `x + 4 (z + t m)` also belongs to the interior of `s` for small enough `t`. This means that we will be able to apply `second_derivative_within_at_symmetric_of_mem_interior` to show that `f''` is symmetric, after cancelling all the contributions due to `z`. -/ rcases hne with ⟨y, hy⟩, obtain ⟨z, hz⟩ : ∃ z, z = ((1:ℝ) / 4) • (y - x) := ⟨((1:ℝ) / 4) • (y - x), rfl⟩, have A : ∀ (m : E), filter.tendsto (λ (t : ℝ), x + (4 : ℝ) • (z + t • m)) (𝓝 0) (𝓝 y), { assume m, have : x + (4 : ℝ) • (z + (0 : ℝ) • m) = y, by simp [hz], rw ← this, refine tendsto_const_nhds.add _, refine tendsto_const_nhds.smul _, refine tendsto_const_nhds.add _, exact continuous_at_id.smul continuous_at_const }, have B : ∀ (m : E), ∀ᶠ t in 𝓝[>] (0 : ℝ), x + (4 : ℝ) • (z + t • m) ∈ interior s, { assume m, apply nhds_within_le_nhds, apply A m, rw [mem_interior_iff_mem_nhds] at hy, exact interior_mem_nhds.2 hy }, -- we choose `t m > 0` such that `x + 4 (z + (t m) m)` belongs to the interior of `s`, for any -- vector `m`. choose t ts tpos using λ m, ((B m).and self_mem_nhds_within).exists, -- applying `second_derivative_within_at_symmetric_of_mem_interior` to the vectors `z` -- and `z + (t m) m`, we deduce that `f'' m z = f'' z m` for all `m`. have C : ∀ (m : E), f'' m z = f'' z m, { assume m, have : f'' (z + t m • m) (z + t 0 • 0) = f'' (z + t 0 • 0) (z + t m • m) := s_conv.second_derivative_within_at_symmetric_of_mem_interior hf xs hx (ts 0) (ts m), simp only [continuous_linear_map.map_add, continuous_linear_map.map_smul, add_right_inj, continuous_linear_map.add_apply, pi.smul_apply, continuous_linear_map.coe_smul', add_zero, continuous_linear_map.zero_apply, smul_zero, continuous_linear_map.map_zero] at this, exact smul_right_injective F (tpos m).ne' this }, -- applying `second_derivative_within_at_symmetric_of_mem_interior` to the vectors `z + (t v) v` -- and `z + (t w) w`, we deduce that `f'' v w = f'' w v`. Cross terms involving `z` can be -- eliminated thanks to the fact proved above that `f'' m z = f'' z m`. have : f'' (z + t v • v) (z + t w • w) = f'' (z + t w • w) (z + t v • v) := s_conv.second_derivative_within_at_symmetric_of_mem_interior hf xs hx (ts w) (ts v), simp only [continuous_linear_map.map_add, continuous_linear_map.map_smul, smul_add, smul_smul, continuous_linear_map.add_apply, pi.smul_apply, continuous_linear_map.coe_smul', C] at this, rw ← sub_eq_zero at this, abel at this, simp only [one_zsmul, neg_smul, sub_eq_zero, mul_comm, ← sub_eq_add_neg] at this, apply smul_right_injective F _ this, simp [(tpos v).ne', (tpos w).ne'] end /-- If a function is differentiable around `x`, and has two derivatives at `x`, then the second derivative is symmetric. -/ theorem second_derivative_symmetric_of_eventually {f : E → F} {f' : E → (E →L[ℝ] F)} {f'' : E →L[ℝ] (E →L[ℝ] F)} (hf : ∀ᶠ y in 𝓝 x, has_fderiv_at f (f' y) y) (hx : has_fderiv_at f' f'' x) (v w : E) : f'' v w = f'' w v := begin rcases metric.mem_nhds_iff.1 hf with ⟨ε, εpos, hε⟩, have A : (interior (metric.ball x ε)).nonempty, by rwa [metric.is_open_ball.interior_eq, metric.nonempty_ball], exact convex.second_derivative_within_at_symmetric (convex_ball x ε) A (λ y hy, hε (interior_subset hy)) (metric.mem_ball_self εpos) hx.has_fderiv_within_at v w, end /-- If a function is differentiable, and has two derivatives at `x`, then the second derivative is symmetric. -/ theorem second_derivative_symmetric {f : E → F} {f' : E → (E →L[ℝ] F)} {f'' : E →L[ℝ] (E →L[ℝ] F)} (hf : ∀ y, has_fderiv_at f (f' y) y) (hx : has_fderiv_at f' f'' x) (v w : E) : f'' v w = f'' w v := second_derivative_symmetric_of_eventually (filter.eventually_of_forall hf) hx v w
cf6bb00380b4ec232cc658b872005e5671bc2137
367134ba5a65885e863bdc4507601606690974c1
/src/ring_theory/hahn_series.lean
550870712abd4c8b492a77bee2b2c6d12136e6a7
[ "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
21,417
lean
/- Copyright (c) 2021 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import order.well_founded_set import algebra.big_operators import algebra.module.pi import ring_theory.power_series.basic /-! # Hahn Series ## Main Definitions * If `Γ` is linearly ordered and `R` has zero, then `hahn_series Γ R` consists of formal series over `Γ` with coefficients in `R`, whose supports are well-founded. * If `R` is a (commutative) additive monoid or group, then so is `hahn_series Γ R`. * If `R` is a (comm_)(semi)ring, then so is `hahn_series Γ R`. ## TODO * Given `[linear_ordered_add_comm_group Γ]` and `[field R]`, define `field (hahn_series Γ R)`. * Build an API for the variable `X` * Define Laurent series -/ open_locale big_operators classical noncomputable theory /-- If `Γ` is linearly ordered and `R` has zero, then `hahn_series Γ R` consists of formal series over `Γ` with coefficients in `R`, whose supports are well-founded. -/ @[ext] structure hahn_series (Γ : Type*) (R : Type*) [linear_order Γ] [has_zero R] := (coeff : Γ → R) (is_wf_support' : (function.support coeff).is_wf) variables {Γ : Type*} {R : Type*} namespace hahn_series section zero variables [linear_order Γ] [has_zero R] /-- The support of a Hahn series is just the set of indices whose coefficients are nonzero. Notably, it is well-founded. -/ def support (x : hahn_series Γ R) : set Γ := function.support x.coeff @[simp] lemma is_wf_support (x : hahn_series Γ R) : x.support.is_wf := x.is_wf_support' @[simp] lemma mem_support (x : hahn_series Γ R) (a : Γ) : a ∈ x.support ↔ x.coeff a ≠ 0 := iff.refl _ instance : has_zero (hahn_series Γ R) := ⟨{ coeff := 0, is_wf_support' := by simp }⟩ instance : inhabited (hahn_series Γ R) := ⟨0⟩ @[simp] lemma zero_coeff {a : Γ} : (0 : hahn_series Γ R).coeff a = 0 := rfl @[simp] lemma support_zero : support (0 : hahn_series Γ R) = ∅ := function.support_zero /-- `single a r` is the Hahn series which has coefficient `r` at `a` and zero otherwise. -/ def single (a : Γ) : zero_hom R (hahn_series Γ R) := { to_fun := λ r, { coeff := pi.single a r, is_wf_support' := (set.is_wf_singleton a).mono pi.support_single_subset }, map_zero' := ext _ _ (pi.single_zero _) } variables {a b : Γ} {r : R} @[simp] theorem single_coeff_same : (single a r).coeff a = r := pi.single_eq_same a r @[simp] theorem single_coeff_of_ne (h : b ≠ a) : (single a r).coeff b = 0 := pi.single_eq_of_ne h r theorem single_coeff : (single a r).coeff b = if (b = a) then r else 0 := by { split_ifs with h; simp [h] } @[simp] lemma support_single_of_ne (h : r ≠ 0) : support (single a r) = {a} := pi.support_single_of_ne h lemma support_single_subset : support (single a r) ⊆ {a} := pi.support_single_subset lemma eq_of_mem_support_single {b : Γ} (h : b ∈ support (single a r)) : b = a := support_single_subset h @[simp] lemma single_eq_zero : (single a (0 : R)) = 0 := (single a).map_zero end zero section addition variable [linear_order Γ] section add_monoid variable [add_monoid R] instance : has_add (hahn_series Γ R) := { add := λ x y, { coeff := x.coeff + y.coeff, is_wf_support' := (x.is_wf_support.union y.is_wf_support).mono (function.support_add _ _) } } instance : add_monoid (hahn_series Γ R) := { zero := 0, add := (+), add_assoc := λ x y z, by { ext, apply add_assoc }, zero_add := λ x, by { ext, apply zero_add }, add_zero := λ x, by { ext, apply add_zero } } @[simp] lemma add_coeff' {x y : hahn_series Γ R} : (x + y).coeff = x.coeff + y.coeff := rfl lemma add_coeff {x y : hahn_series Γ R} {a : Γ} : (x + y).coeff a = x.coeff a + y.coeff a := rfl /-- `single` as an additive monoid/group homomorphism -/ def single.add_monoid_hom (a : Γ) : R →+ (hahn_series Γ R) := { map_add' := λ x y, by { ext b, by_cases h : b = a; simp [h] }, ..single a } @[simp] lemma single.add_monoid_hom_apply {a : Γ} {r : R} : single.add_monoid_hom a r = single a r := rfl end add_monoid instance [add_comm_monoid R] : add_comm_monoid (hahn_series Γ R) := { add_comm := λ x y, by { ext, apply add_comm } .. hahn_series.add_monoid } instance [add_group R] : add_group (hahn_series Γ R) := { neg := λ x, { coeff := λ a, - x.coeff a, is_wf_support' := by { rw function.support_neg, exact x.is_wf_support }, }, add_left_neg := λ x, by { ext, apply add_left_neg }, .. hahn_series.add_monoid } @[simp] lemma neg_coeff' [add_group R] {x : hahn_series Γ R} : (- x).coeff = - x.coeff := rfl lemma neg_coeff [add_group R] {x : hahn_series Γ R} {a : Γ} : (- x).coeff a = - x.coeff a := rfl @[simp] lemma sub_coeff' [add_group R] {x y : hahn_series Γ R} : (x - y).coeff = x.coeff - y.coeff := by { ext, simp [sub_eq_add_neg] } lemma sub_coeff [add_group R] {x y : hahn_series Γ R} {a : Γ} : (x - y).coeff a = x.coeff a - y.coeff a := by simp instance [add_comm_group R] : add_comm_group (hahn_series Γ R) := { .. hahn_series.add_comm_monoid, .. hahn_series.add_group } end addition section distrib_mul_action variables [linear_order Γ] {V : Type*} [monoid R] [add_monoid V] [distrib_mul_action R V] instance : has_scalar R (hahn_series Γ V) := ⟨λ r x, { coeff := r • x.coeff, is_wf_support' := x.is_wf_support.mono (function.support_smul_subset_right r x.coeff) }⟩ @[simp] lemma smul_coeff {r : R} {x : hahn_series Γ V} {a : Γ} : (r • x).coeff a = r • (x.coeff a) := rfl instance : distrib_mul_action R (hahn_series Γ V) := { smul := (•), one_smul := λ _, by { ext, simp }, smul_zero := λ _, by { ext, simp }, smul_add := λ _ _ _, by { ext, simp [smul_add] }, mul_smul := λ _ _ _, by { ext, simp [mul_smul] } } variables {S : Type*} [monoid S] [distrib_mul_action S V] instance [has_scalar R S] [is_scalar_tower R S V] : is_scalar_tower R S (hahn_series Γ V) := ⟨λ r s a, by { ext, simp }⟩ instance [smul_comm_class R S V] : smul_comm_class R S (hahn_series Γ V) := ⟨λ r s a, by { ext, simp [smul_comm] }⟩ end distrib_mul_action section semimodule variables [linear_order Γ] [semiring R] {V : Type*} [add_comm_monoid V] [semimodule R V] instance : semimodule R (hahn_series Γ V) := { zero_smul := λ _, by { ext, simp }, add_smul := λ _ _ _, by { ext, simp [add_smul] }, .. hahn_series.distrib_mul_action } /-- `single` as a linear map -/ def single.linear_map (a : Γ) : R →ₗ[R] (hahn_series Γ R) := { map_smul' := λ r s, by { ext b, by_cases h : b = a; simp [h] }, ..single.add_monoid_hom a } @[simp] lemma single.linear_map_apply {a : Γ} {r : R} : single.linear_map a r = single a r := rfl end semimodule section multiplication variable [linear_ordered_cancel_add_comm_monoid Γ] instance [has_zero R] [has_one R] : has_one (hahn_series Γ R) := ⟨single 0 1⟩ @[simp] lemma one_coeff [has_zero R] [has_one R] {a : Γ} : (1 : hahn_series Γ R).coeff a = if a = 0 then 1 else 0 := single_coeff @[simp] lemma single_zero_one [has_zero R] [has_one R] : (single 0 (1 : R)) = 1 := rfl instance [semiring R] : has_mul (hahn_series Γ R) := { mul := λ x y, { coeff := λ a, ∑ ij in (finset.add_antidiagonal x.is_wf_support y.is_wf_support a), x.coeff ij.fst * y.coeff ij.snd, is_wf_support' := begin have h : {a : Γ | ∑ (ij : Γ × Γ) in finset.add_antidiagonal x.is_wf_support y.is_wf_support a, x.coeff ij.fst * y.coeff ij.snd ≠ 0} ⊆ {a : Γ | (finset.add_antidiagonal x.is_wf_support y.is_wf_support a).nonempty}, { intros a ha, contrapose! ha, simp [finset.not_nonempty_iff_eq_empty.1 ha] }, exact finset.is_wf_support_add_antidiagonal.mono h, end, }, } @[simp] lemma mul_coeff [semiring R] {x y : hahn_series Γ R} {a : Γ} : (x * y).coeff a = ∑ ij in (finset.add_antidiagonal x.is_wf_support y.is_wf_support a), x.coeff ij.fst * y.coeff ij.snd := rfl lemma mul_coeff_right' [semiring R] {x y : hahn_series Γ R} {a : Γ} {s : set Γ} (hs : s.is_wf) (hys : y.support ⊆ s) : (x * y).coeff a = ∑ ij in (finset.add_antidiagonal x.is_wf_support hs a), x.coeff ij.fst * y.coeff ij.snd := begin rw mul_coeff, apply finset.sum_subset_zero_on_sdiff (finset.add_antidiagonal_mono_right hys) _ (λ _ _, rfl), intros b hb, simp only [not_and, not_not, finset.mem_sdiff, finset.mem_add_antidiagonal, ne.def, set.mem_set_of_eq, mem_support] at hb, rw [(hb.2 hb.1.1 hb.1.2.1), mul_zero] end lemma mul_coeff_left' [semiring R] {x y : hahn_series Γ R} {a : Γ} {s : set Γ} (hs : s.is_wf) (hxs : x.support ⊆ s) : (x * y).coeff a = ∑ ij in (finset.add_antidiagonal hs y.is_wf_support a), x.coeff ij.fst * y.coeff ij.snd := begin rw mul_coeff, apply finset.sum_subset_zero_on_sdiff (finset.add_antidiagonal_mono_left hxs) _ (λ _ _, rfl), intros b hb, simp only [not_and, not_not, finset.mem_sdiff, finset.mem_add_antidiagonal, ne.def, set.mem_set_of_eq, mem_support] at hb, rw [not_not.1 (λ con, hb.1.2.2 (hb.2 hb.1.1 con)), zero_mul], end instance [semiring R] : distrib (hahn_series Γ R) := { left_distrib := λ x y z, begin ext a, have hwf := (y.is_wf_support.union z.is_wf_support), rw [mul_coeff_right' hwf, add_coeff, mul_coeff_right' hwf (set.subset_union_right _ _), mul_coeff_right' hwf (set.subset_union_left _ _)], { simp only [add_coeff, mul_add, finset.sum_add_distrib] }, { intro b, simp only [add_coeff, ne.def, set.mem_union_eq, set.mem_set_of_eq, mem_support], contrapose!, intro h, rw [h.1, h.2, add_zero], } end, right_distrib := λ x y z, begin ext a, have hwf := (x.is_wf_support.union y.is_wf_support), rw [mul_coeff_left' hwf, add_coeff, mul_coeff_left' hwf (set.subset_union_right _ _), mul_coeff_left' hwf (set.subset_union_left _ _)], { simp only [add_coeff, add_mul, finset.sum_add_distrib] }, { intro b, simp only [add_coeff, ne.def, set.mem_union_eq, set.mem_set_of_eq, mem_support], contrapose!, intro h, rw [h.1, h.2, add_zero], }, end, .. hahn_series.has_mul, .. hahn_series.has_add } lemma single_mul_coeff_add [semiring R] {r : R} {x : hahn_series Γ R} {a : Γ} {b : Γ} : ((single b r) * x).coeff (a + b) = r * x.coeff a := begin by_cases hr : r = 0, { simp [hr] }, simp only [hr, smul_coeff, mul_coeff, support_single_of_ne, ne.def, not_false_iff, smul_eq_mul], by_cases hx : x.coeff a = 0, { simp only [hx, mul_zero], rw [finset.sum_congr _ (λ _ _, rfl), finset.sum_empty], ext ⟨a1, a2⟩, simp only [finset.not_mem_empty, not_and, set.mem_singleton_iff, not_not, finset.mem_add_antidiagonal, set.mem_set_of_eq, iff_false], rintro h1 rfl h2, rw add_comm at h1, rw ← add_right_cancel h1 at hx, exact h2 hx, }, transitivity ∑ (ij : Γ × Γ) in {(b, a)}, (single b r).coeff ij.fst * x.coeff ij.snd, { apply finset.sum_congr _ (λ _ _, rfl), ext ⟨a1, a2⟩, simp only [set.mem_singleton_iff, prod.mk.inj_iff, finset.mem_add_antidiagonal, finset.mem_singleton, set.mem_set_of_eq], split, { rintro ⟨h1, rfl, h2⟩, rw add_comm at h1, refine ⟨rfl, add_right_cancel h1⟩ }, { rintro ⟨rfl, rfl⟩, refine ⟨add_comm _ _, _⟩, simp [hx] } }, { simp } end lemma mul_single_coeff_add [semiring R] {r : R} {x : hahn_series Γ R} {a : Γ} {b : Γ} : (x * (single b r)).coeff (a + b) = x.coeff a * r := begin by_cases hr : r = 0, { simp [hr] }, simp only [hr, smul_coeff, mul_coeff, support_single_of_ne, ne.def, not_false_iff, smul_eq_mul], by_cases hx : x.coeff a = 0, { simp only [hx, zero_mul], rw [finset.sum_congr _ (λ _ _, rfl), finset.sum_empty], ext ⟨a1, a2⟩, simp only [finset.not_mem_empty, not_and, set.mem_singleton_iff, not_not, finset.mem_add_antidiagonal, set.mem_set_of_eq, iff_false], rintro h1 h2 rfl, rw ← add_right_cancel h1 at hx, exact h2 hx, }, transitivity ∑ (ij : Γ × Γ) in {(a,b)}, x.coeff ij.fst * (single b r).coeff ij.snd, { apply finset.sum_congr _ (λ _ _, rfl), ext ⟨a1, a2⟩, simp only [set.mem_singleton_iff, prod.mk.inj_iff, finset.mem_add_antidiagonal, finset.mem_singleton, set.mem_set_of_eq], split, { rintro ⟨h1, h2, rfl⟩, refine ⟨add_right_cancel h1, rfl⟩ }, { rintro ⟨rfl, rfl⟩, simp [hx] } }, { simp } end @[simp] lemma mul_single_zero_coeff [semiring R] {r : R} {x : hahn_series Γ R} {a : Γ} : (x * (single 0 r)).coeff a = x.coeff a * r := by rw [← add_zero a, mul_single_coeff_add, add_zero] lemma single_zero_mul_coeff [semiring R] {r : R} {x : hahn_series Γ R} {a : Γ} : ((single 0 r) * x).coeff a = r * x.coeff a := by rw [← add_zero a, single_mul_coeff_add, add_zero] @[simp] lemma single_zero_mul_eq_smul [semiring R] {r : R} {x : hahn_series Γ R} : (single 0 r) * x = r • x := by { ext, exact single_zero_mul_coeff } theorem support_mul_subset_add_support [semiring R] {x y : hahn_series Γ R} : support (x * y) ⊆ support x + support y := begin apply set.subset.trans (λ x hx, _) finset.support_add_antidiagonal_subset_add, { exact x.is_wf_support }, { exact y.is_wf_support }, contrapose! hx, simp only [finset.not_nonempty_iff_eq_empty, ne.def, set.mem_set_of_eq] at hx, simp [hx], end private lemma mul_assoc' [semiring R] (x y z : hahn_series Γ R) : x * y * z = x * (y * z) := begin ext b, rw [mul_coeff_left' (x.is_wf_support.add y.is_wf_support) support_mul_subset_add_support, mul_coeff_right' (y.is_wf_support.add z.is_wf_support) support_mul_subset_add_support], simp only [mul_coeff, add_coeff, finset.sum_mul, finset.mul_sum, finset.sum_sigma'], refine finset.sum_bij_ne_zero (λ a has ha0, ⟨⟨a.2.1, a.2.2 + a.1.2⟩, ⟨a.2.2, a.1.2⟩⟩) _ _ _ _, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H1 H2, simp only [true_and, set.image2_add, eq_self_iff_true, finset.mem_add_antidiagonal, ne.def, set.image_prod, finset.mem_sigma, set.mem_set_of_eq] at H1 H2 ⊢, obtain ⟨⟨rfl, ⟨H3, nz⟩⟩, ⟨rfl, nx, ny⟩⟩ := H1, refine ⟨⟨(add_assoc _ _ _).symm, nx, set.add_mem_add ny nz⟩, ny, nz⟩ }, { rintros ⟨⟨i1,j1⟩, ⟨k1,l1⟩⟩ ⟨⟨i2,j2⟩, ⟨k2,l2⟩⟩ H1 H2 H3 H4 H5, simp only [set.image2_add, prod.mk.inj_iff, finset.mem_add_antidiagonal, ne.def, set.image_prod, finset.mem_sigma, set.mem_set_of_eq, heq_iff_eq] at H1 H3 H5, obtain ⟨⟨rfl, H⟩, rfl, rfl⟩ := H5, simp only [and_true, prod.mk.inj_iff, eq_self_iff_true, heq_iff_eq], exact add_right_cancel (H1.1.1.trans H3.1.1.symm) }, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H1 H2, simp only [exists_prop, set.image2_add, prod.mk.inj_iff, finset.mem_add_antidiagonal, sigma.exists, ne.def, set.image_prod, finset.mem_sigma, set.mem_set_of_eq, heq_iff_eq, prod.exists] at H1 H2 ⊢, obtain ⟨⟨rfl, nx, H⟩, rfl, ny, nz⟩ := H1, exact ⟨i + k, l, i, k, ⟨⟨add_assoc _ _ _, set.add_mem_add nx ny, nz⟩, rfl, nx, ny⟩, λ con, H2 ((mul_assoc _ _ _).symm.trans con), ⟨rfl, rfl⟩, rfl, rfl⟩ }, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H1 H2, simp [mul_assoc], } end instance [semiring R] : semiring (hahn_series Γ R) := { zero := 0, one := 1, add := (+), mul := (*), zero_mul := λ _, by { ext, simp }, mul_zero := λ _, by { ext, simp }, one_mul := λ x, single_zero_mul_eq_smul.trans (one_smul _ _), mul_one := λ x, by { ext, exact mul_single_zero_coeff.trans (mul_one _) }, mul_assoc := mul_assoc', .. hahn_series.add_comm_monoid, .. hahn_series.distrib } instance [comm_semiring R] : comm_semiring (hahn_series Γ R) := { mul_comm := λ x y, begin ext, simp_rw [mul_coeff, mul_comm], refine finset.sum_bij (λ a ha, ⟨a.2, a.1⟩) _ (λ a ha, by simp) _ _, { intros a ha, simp only [finset.mem_add_antidiagonal, ne.def, set.mem_set_of_eq] at ha ⊢, obtain ⟨h1, h2, h3⟩ := ha, refine ⟨_, h3, h2⟩, rw [add_comm, h1], }, { rintros ⟨a1, a2⟩ ⟨b1, b2⟩ ha hb hab, rw prod.ext_iff at *, refine ⟨hab.2, hab.1⟩, }, { intros a ha, refine ⟨a.swap, _, by simp⟩, simp only [prod.fst_swap, finset.mem_add_antidiagonal, prod.snd_swap, ne.def, set.mem_set_of_eq] at ha ⊢, exact ⟨(add_comm _ _).trans ha.1, ha.2.2, ha.2.1⟩ } end, .. hahn_series.semiring } instance [ring R] : ring (hahn_series Γ R) := { .. hahn_series.semiring, .. hahn_series.add_comm_group } instance [comm_ring R] : comm_ring (hahn_series Γ R) := { .. hahn_series.comm_semiring, .. hahn_series.ring } section semiring variables [semiring R] @[simp] lemma single_mul_single {a b : Γ} {r s : R} : single a r * single b s = single (a + b) (r * s) := begin ext x, by_cases h : x = a + b, { rw [h, mul_single_coeff_add], simp }, { rw [single_coeff_of_ne h, mul_coeff, finset.sum_eq_zero], rintros ⟨y1, y2⟩ hy, obtain ⟨rfl, hy1, hy2⟩ := finset.mem_add_antidiagonal.1 hy, rw [eq_of_mem_support_single hy1, eq_of_mem_support_single hy2] at h, exact (h rfl).elim } end /-- `C a` is the constant Hahn Series `a`. `C` is provided as a ring homomorphism. -/ def C : R →+* (hahn_series Γ R) := { to_fun := single 0, map_zero' := single_eq_zero, map_one' := rfl, map_add' := λ x y, by { ext a, by_cases h : a = 0; simp [h] }, map_mul' := λ x y, by rw [single_mul_single, zero_add] } @[simp] lemma C_apply (r : R) : C r = single (0 : Γ) r := rfl @[simp] lemma C_zero : C (0 : R) = (0 : hahn_series Γ R) := C.map_zero @[simp] lemma C_one : C (1 : R) = (1 : hahn_series Γ R) := C.map_one lemma C_mul_eq_smul {r : R} {x : hahn_series Γ R} : C r * x = r • x := single_zero_mul_eq_smul end semiring section algebra variables [comm_semiring R] {A : Type*} [semiring A] [algebra R A] instance : algebra R (hahn_series Γ A) := { to_ring_hom := C.comp (algebra_map R A), smul_def' := λ r x, by { ext, simp }, commutes' := λ r x, by { ext, simp only [smul_coeff, single_zero_mul_eq_smul, ring_hom.coe_comp, ring_hom.to_fun_eq_coe, C_apply, function.comp_app, algebra_map_smul, mul_single_zero_coeff], rw [← algebra.commutes, algebra.smul_def], }, } theorem C_eq_algebra_map : C = (algebra_map R (hahn_series Γ R)) := rfl theorem algebra_map_apply {r : R} : algebra_map R (hahn_series Γ A) r = C (algebra_map R A r) := rfl instance [nontrivial Γ] [nontrivial R] : nontrivial (subalgebra R (hahn_series Γ R)) := ⟨⟨⊥, ⊤, begin rw [ne.def, subalgebra.ext_iff, not_forall], obtain ⟨a, ha⟩ := exists_ne (0 : Γ), refine ⟨single a 1, _⟩, simp only [algebra.mem_bot, not_exists, set.mem_range, iff_true, algebra.mem_top], intros x, rw [ext_iff, function.funext_iff, not_forall], refine ⟨a, _⟩, rw [single_coeff_same, algebra_map_apply, C_apply, single_coeff_of_ne ha], exact zero_ne_one end⟩⟩ end algebra end multiplication section semiring variables [semiring R] /-- The ring `hahn_series ℕ R` is isomorphic to `power_series R`. -/ def to_power_series : (hahn_series ℕ R) ≃+* power_series R := { to_fun := λ f, power_series.mk f.coeff, inv_fun := λ f, ⟨λ n, power_series.coeff R n f, nat.lt_wf.is_wf _⟩, left_inv := λ f, by { ext, simp }, right_inv := λ f, by { ext, simp }, map_add' := λ f g, by { ext, simp }, map_mul' := λ f g, begin ext n, simp only [power_series.coeff_mul, power_series.coeff_mk, mul_coeff, is_wf_support], classical, refine finset.sum_filter_ne_zero.symm.trans ((finset.sum_congr _ (λ _ _, rfl)).trans finset.sum_filter_ne_zero), ext m, simp only [finset.nat.mem_antidiagonal, and.congr_left_iff, finset.mem_add_antidiagonal, ne.def, and_iff_left_iff_imp, finset.mem_filter, mem_support], intros h1 h2, contrapose h1, rw ← decidable.or_iff_not_and_not at h1, cases h1; simp [h1] end } @[simp] lemma coeff_to_power_series {f : hahn_series ℕ R} {n : ℕ} : power_series.coeff R n f.to_power_series = f.coeff n := power_series.coeff_mk _ _ @[simp] lemma coeff_to_power_series_symm {f : power_series R} {n : ℕ} : (hahn_series.to_power_series.symm f).coeff n = power_series.coeff R n f := rfl end semiring section algebra variables (R) [comm_semiring R] {A : Type*} [semiring A] [algebra R A] /-- The `R`-algebra `hahn_series ℕ A` is isomorphic to `power_series A`. -/ def to_power_series_alg : (hahn_series ℕ A) ≃ₐ[R] power_series A := { commutes' := λ r, begin ext n, simp only [algebra_map_apply, power_series.algebra_map_apply, ring_equiv.to_fun_eq_coe, C_apply, coeff_to_power_series], cases n, { simp only [power_series.coeff_zero_eq_constant_coeff, single_coeff_same], refl }, { simp only [n.succ_ne_zero, ne.def, not_false_iff, single_coeff_of_ne], rw [power_series.coeff_C, if_neg n.succ_ne_zero] } end, .. to_power_series } @[simp] lemma to_power_series_alg_apply {f : hahn_series ℕ A} : hahn_series.to_power_series_alg R f = f.to_power_series := rfl @[simp] lemma to_power_series_alg_symm_apply {f : power_series A} : (hahn_series.to_power_series_alg R).symm f = hahn_series.to_power_series.symm f := rfl end algebra end hahn_series
a099e3ddc57371c766b14805ada036b6e08b2466
d436468d80b739ba7e06843c4d0d2070e43448e5
/src/ring_theory/maps.lean
2ccb657793b57c65cd76131cffa9620561957e7e
[ "Apache-2.0" ]
permissive
roro47/mathlib
761fdc002aef92f77818f3fef06bf6ec6fc1a28e
80aa7d52537571a2ca62a3fdf71c9533a09422cf
refs/heads/master
1,599,656,410,625
1,573,649,488,000
1,573,649,488,000
221,452,951
0
0
Apache-2.0
1,573,647,693,000
1,573,647,692,000
null
UTF-8
Lean
false
false
5,103
lean
/- Copyright (c) 2018 Andreas Swerdlow. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andreas Swerdlow, Kenny Lau -/ import data.equiv.algebra /-! # Ring antihomomorphisms, isomorphisms, antiisomorphisms and involutions This file defines ring antihomomorphisms, antiisomorphism and involutions and proves basic properties of them. ## Notations All types defined in this file are given a coercion to the underlying function. ## References * https://en.wikipedia.org/wiki/Antihomomorphism * https://en.wikipedia.org/wiki/Involution_(mathematics)#Ring_theory ## Tags Ring isomorphism, automorphism, antihomomorphism, antiisomorphism, antiautomorphism, involution -/ variables {R : Type*} {F : Type*} /- The Proposition that a function from a ring to a ring is an antihomomorphism -/ class is_ring_anti_hom [ring R] [ring F] (f : R → F) : Prop := (map_one : f 1 = 1) (map_mul : ∀ {x y : R}, f (x * y) = f y * f x) (map_add : ∀ {x y : R}, f (x + y) = f x + f y) namespace is_ring_anti_hom variables [ring R] [ring F] (f : R → F) [is_ring_anti_hom f] instance : is_add_group_hom f := { to_is_add_hom := ⟨λ x y, is_ring_anti_hom.map_add f⟩ } lemma map_zero : f 0 = 0 := is_add_group_hom.map_zero f lemma map_neg {x} : f (-x) = -f x := is_add_group_hom.map_neg f x lemma map_sub {x y} : f (x - y) = f x - f y := is_add_group_hom.map_sub f x y end is_ring_anti_hom variables (R F) namespace ring_equiv open ring_equiv variables {R F} [ring R] [ring F] (Hs : R ≃+* F) (x y : R) lemma bijective : function.bijective Hs := Hs.to_equiv.bijective lemma map_zero_iff {x : R} : Hs x = 0 ↔ x = 0 := ⟨λ H, Hs.bijective.1 $ H.symm ▸ Hs.map_zero.symm, λ H, H.symm ▸ Hs.map_zero⟩ end ring_equiv /-- A ring antiisomorphism -/ structure ring_anti_equiv [ring R] [ring F] extends R ≃ F := [anti_hom : is_ring_anti_hom to_fun] namespace ring_anti_equiv variables {R F} [ring R] [ring F] (Hs : ring_anti_equiv R F) (x y : R) instance : has_coe_to_fun (ring_anti_equiv R F) := ⟨_, λ Hs, Hs.to_fun⟩ instance : is_ring_anti_hom Hs := Hs.anti_hom lemma map_add : Hs (x + y) = Hs x + Hs y := is_ring_anti_hom.map_add Hs lemma map_zero : Hs 0 = 0 := is_ring_anti_hom.map_zero Hs lemma map_neg : Hs (-x) = -Hs x := is_ring_anti_hom.map_neg Hs lemma map_sub : Hs (x - y) = Hs x - Hs y := is_ring_anti_hom.map_sub Hs lemma map_mul : Hs (x * y) = Hs y * Hs x := is_ring_anti_hom.map_mul Hs lemma map_one : Hs 1 = 1 := is_ring_anti_hom.map_one Hs lemma map_neg_one : Hs (-1) = -1 := Hs.map_one ▸ Hs.map_neg 1 lemma bijective : function.bijective Hs := Hs.to_equiv.bijective lemma map_zero_iff {x : R} : Hs x = 0 ↔ x = 0 := ⟨λ H, Hs.bijective.1 $ H.symm ▸ Hs.map_zero.symm, λ H, H.symm ▸ Hs.map_zero⟩ end ring_anti_equiv /-- A ring involution -/ structure ring_invo [ring R] := (to_fun : R → R) [anti_hom : is_ring_anti_hom to_fun] (to_fun_to_fun : ∀ x, to_fun (to_fun x) = x) open ring_invo namespace ring_invo variables {R} [ring R] (Hi : ring_invo R) (x y : R) instance : has_coe_to_fun (ring_invo R) := ⟨_, λ Hi, Hi.to_fun⟩ instance : is_ring_anti_hom Hi := Hi.anti_hom def to_ring_anti_equiv : ring_anti_equiv R R := { inv_fun := Hi, left_inv := Hi.to_fun_to_fun, right_inv := Hi.to_fun_to_fun, .. Hi } lemma map_add : Hi (x + y) = Hi x + Hi y := Hi.to_ring_anti_equiv.map_add x y lemma map_zero : Hi 0 = 0 := Hi.to_ring_anti_equiv.map_zero lemma map_neg : Hi (-x) = -Hi x := Hi.to_ring_anti_equiv.map_neg x lemma map_sub : Hi (x - y) = Hi x - Hi y := Hi.to_ring_anti_equiv.map_sub x y lemma map_mul : Hi (x * y) = Hi y * Hi x := Hi.to_ring_anti_equiv.map_mul x y lemma map_one : Hi 1 = 1 := Hi.to_ring_anti_equiv.map_one lemma map_neg_one : Hi (-1) = -1 := Hi.to_ring_anti_equiv.map_neg_one lemma bijective : function.bijective Hi := Hi.to_ring_anti_equiv.bijective lemma map_zero_iff {x : R} : Hi x = 0 ↔ x = 0 := Hi.to_ring_anti_equiv.map_zero_iff end ring_invo section comm_ring variables (R F) [comm_ring R] [comm_ring F] protected def ring_invo.id : ring_invo R := { anti_hom := ⟨rfl, mul_comm, λ _ _, rfl⟩, to_fun_to_fun := λ _, rfl, .. equiv.refl R } protected def ring_anti_equiv.refl : ring_anti_equiv R R := (ring_invo.id R).to_ring_anti_equiv variables {R F} theorem comm_ring.hom_to_anti_hom (f : R → F) [is_ring_hom f] : is_ring_anti_hom f := { map_add := λ _ _, is_ring_hom.map_add f, map_mul := λ _ _, by rw [is_ring_hom.map_mul f, mul_comm], map_one := is_ring_hom.map_one f } theorem comm_ring.anti_hom_to_hom (f : R → F) [is_ring_anti_hom f] : is_ring_hom f := { map_add := λ _ _, is_ring_anti_hom.map_add f, map_mul := λ _ _, by rw [is_ring_anti_hom.map_mul f, mul_comm], map_one := is_ring_anti_hom.map_one f } def comm_ring.equiv_to_anti_equiv (Hs : R ≃+* F) : ring_anti_equiv R F := { anti_hom := comm_ring.hom_to_anti_hom Hs, .. Hs } def comm_ring.anti_equiv_to_equiv (Hs : ring_anti_equiv R F) : R ≃+* F := @ring_equiv.of' _ _ _ _ Hs.to_equiv (comm_ring.anti_hom_to_hom Hs) end comm_ring
ad9d1dc518102d7f8ef4a0372f1e07f237a8d23d
b2fe74b11b57d362c13326bc5651244f111fa6f4
/src/dynamics/circle/rotation_number/translation_number.lean
7ba9233bed8d210a582539d65045886c91aced56
[ "Apache-2.0" ]
permissive
midfield/mathlib
c4db5fa898b5ac8f2f80ae0d00c95eb6f745f4c7
775edc615ecec631d65b6180dbcc7bc26c3abc26
refs/heads/master
1,675,330,551,921
1,608,304,514,000
1,608,304,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
39,629
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Yury G. Kudryashov -/ import analysis.specific_limits import order.iterate import order.semiconj_Sup import algebra.iterate_hom /-! # 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) 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, ⟨mono f, λ h, by simpa using mono ↑(f⁻¹) h⟩ }, 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, is_unit_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 conv_rhs { rw [← fract_add_floor x, f.map_add_int, add_sub_comm, sub_self, add_zero] } /-! ### 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 (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, surjective_of_continuous h 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, pow_two, 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 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 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
f03fffef19c0c1718ef158db59649239ecad27da
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Lean/Attributes.lean
d0f3cc911bd6ab13d52c400c6e95f7e418c8a9ac
[ "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
19,641
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.Syntax import Lean.CoreM import Lean.ResolveName namespace Lean inductive AttributeApplicationTime where | afterTypeChecking | afterCompilation | beforeElaboration deriving Inhabited, BEq abbrev AttrM := CoreM instance : MonadLift ImportM AttrM where monadLift x := do liftM (m := IO) (x { env := (← getEnv), opts := (← getOptions) }) structure AttributeImplCore where name : Name descr : String applicationTime := AttributeApplicationTime.afterTypeChecking deriving Inhabited inductive AttributeKind | «global» | «local» | «scoped» deriving BEq instance : ToString AttributeKind where toString | AttributeKind.global => "global" | AttributeKind.local => "local" | AttributeKind.scoped => "scoped" structure AttributeImpl extends AttributeImplCore where add (decl : Name) (stx : Syntax) (kind : AttributeKind) : AttrM Unit erase (decl : Name) : AttrM Unit := throwError "attribute cannot be erased" deriving Inhabited open Std (PersistentHashMap) builtin_initialize attributeMapRef : IO.Ref (PersistentHashMap Name AttributeImpl) ← IO.mkRef {} /- Low level attribute registration function. -/ def registerBuiltinAttribute (attr : AttributeImpl) : IO Unit := do let m ← attributeMapRef.get if m.contains attr.name then throw (IO.userError ("invalid builtin attribute declaration, '" ++ toString attr.name ++ "' has already been used")) unless (← initializing) do throw (IO.userError "failed to register attribute, attributes can only be registered during initialization") attributeMapRef.modify fun m => m.insert attr.name attr /- Helper methods for decoding the parameters of builtin attributes that are defined before `Lean.Parser`. We have the following ones: ``` @[builtinAttrParser] def simple := leading_parser ident >> optional ident >> optional priorityParser /- We can't use `simple` for `class`, `instance`, `export` and `macro` because they are keywords. -/ @[builtinAttrParser] def «class» := leading_parser "class" @[builtinAttrParser] def «instance» := leading_parser "instance" >> optional priorityParser @[builtinAttrParser] def «macro» := leading_parser "macro " >> ident ``` Note that we need the parsers for `class`, `instance`, and `macros` because they are keywords. -/ def Attribute.Builtin.ensureNoArgs (stx : Syntax) : AttrM Unit := do if stx.getKind == `Lean.Parser.Attr.simple && stx[1].isNone && stx[2].isNone then return () else if stx.getKind == `Lean.Parser.Attr.«class» then return () else match stx with | Syntax.missing => return () -- In the elaborator, we use `Syntax.missing` when creating attribute views for simple attributes such as `class and `inline | _ => throwErrorAt stx "unexpected attribute argument" def Attribute.Builtin.getIdent? (stx : Syntax) : AttrM (Option Syntax) := do if stx.getKind == `Lean.Parser.Attr.simple then if !stx[1].isNone && stx[1][0].isIdent then return stx[1][0] else return none /- We handle `macro` here because it is handled by the generic `KeyedDeclsAttribute -/ else if stx.getKind == `Lean.Parser.Attr.«macro» || stx.getKind == `Lean.Parser.Attr.«export» then return stx[1] else throwErrorAt stx "unexpected attribute argument" def Attribute.Builtin.getIdent (stx : Syntax) : AttrM Syntax := do match (← getIdent? stx) with | some id => return id | none => throwErrorAt stx "unexpected attribute argument, identifier expected" def Attribute.Builtin.getId? (stx : Syntax) : AttrM (Option Name) := do let ident? ← getIdent? stx return Syntax.getId <$> ident? def Attribute.Builtin.getId (stx : Syntax) : AttrM Name := do return (← getIdent stx).getId def getAttrParamOptPrio (optPrioStx : Syntax) : AttrM Nat := if optPrioStx.isNone then return eval_prio default else match optPrioStx[0].isNatLit? with | some prio => return prio | none => throwErrorAt optPrioStx "priority expected" def Attribute.Builtin.getPrio (stx : Syntax) : AttrM Nat := do if stx.getKind == `Lean.Parser.Attr.simple then getAttrParamOptPrio stx[1] else throwErrorAt stx "unexpected attribute argument, optional priority expected" /-- Tag attributes are simple and efficient. They are useful for marking declarations in the modules where they were defined. The startup cost for this kind of attribute is very small since `addImportedFn` is a constant function. They provide the predicate `tagAttr.hasTag env decl` which returns true iff declaration `decl` is tagged in the environment `env`. -/ structure TagAttribute where attr : AttributeImpl ext : PersistentEnvExtension Name Name NameSet deriving Inhabited def registerTagAttribute (name : Name) (descr : String) (validate : Name → AttrM Unit := fun _ => pure ()) : IO TagAttribute := do let ext : PersistentEnvExtension Name Name NameSet ← registerPersistentEnvExtension { name := name mkInitial := pure {} addImportedFn := fun _ _ => pure {} addEntryFn := fun (s : NameSet) n => s.insert n exportEntriesFn := fun es => let r : Array Name := es.fold (fun a e => a.push e) #[] r.qsort Name.quickLt statsFn := fun s => "tag attribute" ++ Format.line ++ "number of local entries: " ++ format s.size } let attrImpl : AttributeImpl := { name := name descr := descr add := fun decl stx kind => do Attribute.Builtin.ensureNoArgs stx unless kind == AttributeKind.global do throwError "invalid attribute '{name}', must be global" let env ← getEnv unless (env.getModuleIdxFor? decl).isNone do throwError "invalid attribute '{name}', declaration is in an imported module" validate decl let env ← getEnv setEnv $ ext.addEntry env decl } registerBuiltinAttribute attrImpl return { attr := attrImpl, ext := ext } namespace TagAttribute def hasTag (attr : TagAttribute) (env : Environment) (decl : Name) : Bool := match env.getModuleIdxFor? decl with | some modIdx => (attr.ext.getModuleEntries env modIdx).binSearchContains decl Name.quickLt | none => (attr.ext.getState env).contains decl end TagAttribute /-- A `TagAttribute` variant where we can attach parameters to attributes. It is slightly more expensive and consumes a little bit more memory than `TagAttribute`. They provide the function `pAttr.getParam env decl` which returns `some p` iff declaration `decl` contains the attribute `pAttr` with parameter `p`. -/ structure ParametricAttribute (α : Type) where attr : AttributeImpl ext : PersistentEnvExtension (Name × α) (Name × α) (NameMap α) deriving Inhabited structure ParametricAttributeImpl (α : Type) extends AttributeImplCore where getParam : Name → Syntax → AttrM α afterSet : Name → α → AttrM Unit := fun env _ _ => pure () afterImport : Array (Array (Name × α)) → ImportM Unit := fun _ => pure () def registerParametricAttribute {α : Type} [Inhabited α] (impl : ParametricAttributeImpl α) : IO (ParametricAttribute α) := do let ext : PersistentEnvExtension (Name × α) (Name × α) (NameMap α) ← registerPersistentEnvExtension { name := impl.name mkInitial := pure {} addImportedFn := fun s => impl.afterImport s *> pure {} addEntryFn := fun (s : NameMap α) (p : Name × α) => s.insert p.1 p.2 exportEntriesFn := fun m => let r : Array (Name × α) := m.fold (fun a n p => a.push (n, p)) #[] r.qsort (fun a b => Name.quickLt a.1 b.1) statsFn := fun s => "parametric attribute" ++ Format.line ++ "number of local entries: " ++ format s.size } let attrImpl : AttributeImpl := { name := impl.name descr := impl.descr add := fun decl stx kind => do unless kind == AttributeKind.global do throwError "invalid attribute '{impl.name}', must be global" let env ← getEnv unless (env.getModuleIdxFor? decl).isNone do throwError "invalid attribute '{impl.name}', declaration is in an imported module" let val ← impl.getParam decl stx let env' := ext.addEntry env (decl, val) setEnv env' try impl.afterSet decl val catch _ => setEnv env } registerBuiltinAttribute attrImpl pure { attr := attrImpl, ext := ext } namespace ParametricAttribute def getParam {α : Type} [Inhabited α] (attr : ParametricAttribute α) (env : Environment) (decl : Name) : Option α := match env.getModuleIdxFor? decl with | some modIdx => match (attr.ext.getModuleEntries env modIdx).binSearch (decl, arbitrary) (fun a b => Name.quickLt a.1 b.1) with | some (_, val) => some val | none => none | none => (attr.ext.getState env).find? decl def setParam {α : Type} (attr : ParametricAttribute α) (env : Environment) (decl : Name) (param : α) : Except String Environment := if (env.getModuleIdxFor? decl).isSome then Except.error ("invalid '" ++ toString attr.attr.name ++ "'.setParam, declaration is in an imported module") else if ((attr.ext.getState env).find? decl).isSome then Except.error ("invalid '" ++ toString attr.attr.name ++ "'.setParam, attribute has already been set") else Except.ok (attr.ext.addEntry env (decl, param)) end ParametricAttribute /- Given a list `[a₁, ..., a_n]` of elements of type `α`, `EnumAttributes` provides an attribute `Attr_i` for associating a value `a_i` with an declaration. `α` is usually an enumeration type. Note that whenever we register an `EnumAttributes`, we create `n` attributes, but only one environment extension. -/ structure EnumAttributes (α : Type) where attrs : List AttributeImpl ext : PersistentEnvExtension (Name × α) (Name × α) (NameMap α) deriving Inhabited def registerEnumAttributes {α : Type} [Inhabited α] (extName : Name) (attrDescrs : List (Name × String × α)) (validate : Name → α → AttrM Unit := fun _ _ => pure ()) (applicationTime := AttributeApplicationTime.afterTypeChecking) : IO (EnumAttributes α) := do let ext : PersistentEnvExtension (Name × α) (Name × α) (NameMap α) ← registerPersistentEnvExtension { name := extName mkInitial := pure {} addImportedFn := fun _ _ => pure {} addEntryFn := fun (s : NameMap α) (p : Name × α) => s.insert p.1 p.2 exportEntriesFn := fun m => let r : Array (Name × α) := m.fold (fun a n p => a.push (n, p)) #[] r.qsort (fun a b => Name.quickLt a.1 b.1) statsFn := fun s => "enumeration attribute extension" ++ Format.line ++ "number of local entries: " ++ format s.size } let attrs := attrDescrs.map fun (name, descr, val) => { name := name descr := descr add := fun decl stx kind => do Attribute.Builtin.ensureNoArgs stx unless kind == AttributeKind.global do throwError "invalid attribute '{name}', must be global" let env ← getEnv unless (env.getModuleIdxFor? decl).isNone do throwError "invalid attribute '{name}', declaration is in an imported module" validate decl val setEnv $ ext.addEntry env (decl, val) applicationTime := applicationTime : AttributeImpl } attrs.forM registerBuiltinAttribute pure { ext := ext, attrs := attrs } namespace EnumAttributes def getValue {α : Type} [Inhabited α] (attr : EnumAttributes α) (env : Environment) (decl : Name) : Option α := match env.getModuleIdxFor? decl with | some modIdx => match (attr.ext.getModuleEntries env modIdx).binSearch (decl, arbitrary) (fun a b => Name.quickLt a.1 b.1) with | some (_, val) => some val | none => none | none => (attr.ext.getState env).find? decl def setValue {α : Type} (attrs : EnumAttributes α) (env : Environment) (decl : Name) (val : α) : Except String Environment := if (env.getModuleIdxFor? decl).isSome then Except.error ("invalid '" ++ toString attrs.ext.name ++ "'.setValue, declaration is in an imported module") else if ((attrs.ext.getState env).find? decl).isSome then Except.error ("invalid '" ++ toString attrs.ext.name ++ "'.setValue, attribute has already been set") else Except.ok (attrs.ext.addEntry env (decl, val)) end EnumAttributes /- Attribute extension and builders. We use builders to implement attribute factories for parser categories. -/ abbrev AttributeImplBuilder := List DataValue → Except String AttributeImpl abbrev AttributeImplBuilderTable := Std.HashMap Name AttributeImplBuilder builtin_initialize attributeImplBuilderTableRef : IO.Ref AttributeImplBuilderTable ← IO.mkRef {} def registerAttributeImplBuilder (builderId : Name) (builder : AttributeImplBuilder) : IO Unit := do let table ← attributeImplBuilderTableRef.get if table.contains builderId then throw (IO.userError ("attribute implementation builder '" ++ toString builderId ++ "' has already been declared")) attributeImplBuilderTableRef.modify fun table => table.insert builderId builder def mkAttributeImplOfBuilder (builderId : Name) (args : List DataValue) : IO AttributeImpl := do let table ← attributeImplBuilderTableRef.get match table.find? builderId with | none => throw (IO.userError ("unknown attribute implementation builder '" ++ toString builderId ++ "'")) | some builder => IO.ofExcept $ builder args inductive AttributeExtensionOLeanEntry where | decl (declName : Name) -- `declName` has type `AttributeImpl` | builder (builderId : Name) (args : List DataValue) structure AttributeExtensionState where newEntries : List AttributeExtensionOLeanEntry := [] map : PersistentHashMap Name AttributeImpl deriving Inhabited abbrev AttributeExtension := PersistentEnvExtension AttributeExtensionOLeanEntry (AttributeExtensionOLeanEntry × AttributeImpl) AttributeExtensionState private def AttributeExtension.mkInitial : IO AttributeExtensionState := do let map ← attributeMapRef.get pure { map := map } unsafe def mkAttributeImplOfConstantUnsafe (env : Environment) (opts : Options) (declName : Name) : Except String AttributeImpl := match env.find? declName with | none => throw ("unknow constant '" ++ toString declName ++ "'") | some info => match info.type with | Expr.const `Lean.AttributeImpl _ _ => env.evalConst AttributeImpl opts declName | _ => throw ("unexpected attribute implementation type at '" ++ toString declName ++ "' (`AttributeImpl` expected") @[implementedBy mkAttributeImplOfConstantUnsafe] constant mkAttributeImplOfConstant (env : Environment) (opts : Options) (declName : Name) : Except String AttributeImpl def mkAttributeImplOfEntry (env : Environment) (opts : Options) (e : AttributeExtensionOLeanEntry) : IO AttributeImpl := match e with | AttributeExtensionOLeanEntry.decl declName => IO.ofExcept $ mkAttributeImplOfConstant env opts declName | AttributeExtensionOLeanEntry.builder builderId args => mkAttributeImplOfBuilder builderId args private def AttributeExtension.addImported (es : Array (Array AttributeExtensionOLeanEntry)) : ImportM AttributeExtensionState := do let ctx ← read let map ← attributeMapRef.get let map ← es.foldlM (fun map entries => entries.foldlM (fun (map : PersistentHashMap Name AttributeImpl) entry => do let attrImpl ← liftM $ mkAttributeImplOfEntry ctx.env ctx.opts entry pure $ map.insert attrImpl.name attrImpl) map) map pure { map := map } private def addAttrEntry (s : AttributeExtensionState) (e : AttributeExtensionOLeanEntry × AttributeImpl) : AttributeExtensionState := { s with map := s.map.insert e.2.name e.2, newEntries := e.1 :: s.newEntries } builtin_initialize attributeExtension : AttributeExtension ← registerPersistentEnvExtension { name := `attrExt mkInitial := AttributeExtension.mkInitial addImportedFn := AttributeExtension.addImported addEntryFn := addAttrEntry exportEntriesFn := fun s => s.newEntries.reverse.toArray statsFn := fun s => format "number of local entries: " ++ format s.newEntries.length } /- Return true iff `n` is the name of a registered attribute. -/ @[export lean_is_attribute] def isBuiltinAttribute (n : Name) : IO Bool := do let m ← attributeMapRef.get; pure (m.contains n) /- Return the name of all registered attributes. -/ def getBuiltinAttributeNames : IO (List Name) := do let m ← attributeMapRef.get; pure $ m.foldl (fun r n _ => n::r) [] def getBuiltinAttributeImpl (attrName : Name) : IO AttributeImpl := do let m ← attributeMapRef.get match m.find? attrName with | some attr => pure attr | none => throw (IO.userError ("unknown attribute '" ++ toString attrName ++ "'")) @[export lean_attribute_application_time] def getBuiltinAttributeApplicationTime (n : Name) : IO AttributeApplicationTime := do let attr ← getBuiltinAttributeImpl n pure attr.applicationTime def isAttribute (env : Environment) (attrName : Name) : Bool := (attributeExtension.getState env).map.contains attrName def getAttributeNames (env : Environment) : List Name := let m := (attributeExtension.getState env).map m.foldl (fun r n _ => n::r) [] def getAttributeImpl (env : Environment) (attrName : Name) : Except String AttributeImpl := let m := (attributeExtension.getState env).map match m.find? attrName with | some attr => pure attr | none => throw ("unknown attribute '" ++ toString attrName ++ "'") def registerAttributeOfDecl (env : Environment) (opts : Options) (attrDeclName : Name) : Except String Environment := do let attrImpl ← mkAttributeImplOfConstant env opts attrDeclName if isAttribute env attrImpl.name then throw ("invalid builtin attribute declaration, '" ++ toString attrImpl.name ++ "' has already been used") else return attributeExtension.addEntry env (AttributeExtensionOLeanEntry.decl attrDeclName, attrImpl) def registerAttributeOfBuilder (env : Environment) (builderId : Name) (args : List DataValue) : IO Environment := do let attrImpl ← mkAttributeImplOfBuilder builderId args if isAttribute env attrImpl.name then throw (IO.userError ("invalid builtin attribute declaration, '" ++ toString attrImpl.name ++ "' has already been used")) else return attributeExtension.addEntry env (AttributeExtensionOLeanEntry.builder builderId args, attrImpl) def Attribute.add (declName : Name) (attrName : Name) (stx : Syntax) (kind := AttributeKind.global) : AttrM Unit := do let attr ← ofExcept <| getAttributeImpl (← getEnv) attrName attr.add declName stx kind def Attribute.erase (declName : Name) (attrName : Name) : AttrM Unit := do let attr ← ofExcept <| getAttributeImpl (← getEnv) attrName attr.erase declName /-- `updateEnvAttributes` implementation -/ @[export lean_update_env_attributes] def updateEnvAttributesImpl (env : Environment) : IO Environment := do let map ← attributeMapRef.get let s ← attributeExtension.getState env let s := map.foldl (init := s) fun s attrName attrImpl => if s.map.contains attrName then s else { s with map := s.map.insert attrName attrImpl } return attributeExtension.setState env s /-- `getNumBuiltinAttributes` implementation -/ @[export lean_get_num_attributes] def getNumBuiltiAttributesImpl : IO Nat := return (← attributeMapRef.get).size end Lean
a6c62d4cdd3846bcb7a4ffabaa017d0ea06b58fe
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/pi/lex.lean
a6f2d78919bc6ca8671a22fd041bc5ee3cb29aef
[ "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
8,756
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 order.well_founded import algebra.group.pi import algebra.order.group.defs /-! # Lexicographic order on Pi types > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines the lexicographic order for Pi types. `a` is less than `b` if `a i = b i` for all `i` up to some point `k`, and `a k < b k`. ## Notation * `Πₗ i, α i`: Pi type equipped with the lexicographic order. Type synonym of `Π i, α i`. ## See also Related files are: * `data.finset.colex`: Colexicographic order on finite sets. * `data.list.lex`: Lexicographic order on lists. * `data.sigma.order`: Lexicographic order on `Σₗ i, α i`. * `data.psigma.order`: Lexicographic order on `Σₗ' i, α i`. * `data.prod.lex`: Lexicographic order on `α × β`. -/ variables {ι : Type*} {β : ι → Type*} (r : ι → ι → Prop) (s : Π {i}, β i → β i → Prop) namespace pi instance {α : Type*} : Π [inhabited α], inhabited (lex α) := id /-- The lexicographic relation on `Π i : ι, β i`, where `ι` is ordered by `r`, and each `β i` is ordered by `s`. -/ protected def lex (x y : Π i, β i) : Prop := ∃ i, (∀ j, r j i → x j = y j) ∧ s (x i) (y i) /- This unfortunately results in a type that isn't delta-reduced, so we keep the notation out of the basic API, just in case -/ notation `Πₗ` binders `, ` r:(scoped p, lex (Π i, p i)) := r @[simp] lemma to_lex_apply (x : Π i, β i) (i : ι) : to_lex x i = x i := rfl @[simp] lemma of_lex_apply (x : lex (Π i, β i)) (i : ι) : of_lex x i = x i := rfl lemma lex_lt_of_lt_of_preorder [Π i, preorder (β i)] {r} (hwf : well_founded r) {x y : Π i, β i} (hlt : x < y) : ∃ i, (∀ j, r j i → x j ≤ y j ∧ y j ≤ x j) ∧ x i < y i := let h' := pi.lt_def.1 hlt, ⟨i, hi, hl⟩ := hwf.has_min _ h'.2 in ⟨i, λ j hj, ⟨h'.1 j, not_not.1 $ λ h, hl j (lt_of_le_not_le (h'.1 j) h) hj⟩, hi⟩ lemma lex_lt_of_lt [Π i, partial_order (β i)] {r} (hwf : well_founded r) {x y : Π i, β i} (hlt : x < y) : pi.lex r (λ i, (<)) x y := by { simp_rw [pi.lex, le_antisymm_iff], exact lex_lt_of_lt_of_preorder hwf hlt } lemma is_trichotomous_lex [∀ i, is_trichotomous (β i) s] (wf : well_founded r) : is_trichotomous (Π i, β i) (pi.lex r @s) := { trichotomous := λ a b, begin cases eq_or_ne a b with hab hab, { exact or.inr (or.inl hab) }, { rw function.ne_iff at hab, let i := wf.min _ hab, have hri : ∀ j, r j i → a j = b j, { intro j, rw ← not_imp_not, exact λ h', wf.not_lt_min _ _ h' }, have hne : a i ≠ b i, from wf.min_mem _ hab, cases trichotomous_of s (a i) (b i) with hi hi, exacts [or.inl ⟨i, hri, hi⟩, or.inr $ or.inr $ ⟨i, λ j hj, (hri j hj).symm, hi.resolve_left hne⟩] }, end } instance [has_lt ι] [Π a, has_lt (β a)] : has_lt (lex (Π i, β i)) := ⟨pi.lex (<) (λ _, (<))⟩ instance lex.is_strict_order [linear_order ι] [∀ a, partial_order (β a)] : is_strict_order (lex (Π i, β i)) (<) := { irrefl := λ a ⟨k, hk₁, hk₂⟩, lt_irrefl (a k) hk₂, trans := begin rintro a b c ⟨N₁, lt_N₁, a_lt_b⟩ ⟨N₂, lt_N₂, b_lt_c⟩, rcases lt_trichotomy N₁ N₂ with (H|rfl|H), exacts [⟨N₁, λ j hj, (lt_N₁ _ hj).trans (lt_N₂ _ $ hj.trans H), lt_N₂ _ H ▸ a_lt_b⟩, ⟨N₁, λ j hj, (lt_N₁ _ hj).trans (lt_N₂ _ hj), a_lt_b.trans b_lt_c⟩, ⟨N₂, λ j hj, (lt_N₁ _ (hj.trans H)).trans (lt_N₂ _ hj), (lt_N₁ _ H).symm ▸ b_lt_c⟩] end } instance [linear_order ι] [Π a, partial_order (β a)] : partial_order (lex (Π i, β i)) := partial_order_of_SO (<) /-- `Πₗ i, α i` is a linear order if the original order is well-founded. -/ noncomputable instance [linear_order ι] [is_well_order ι (<)] [∀ a, linear_order (β a)] : linear_order (lex (Π i, β i)) := @linear_order_of_STO (Πₗ i, β i) (<) { to_is_trichotomous := is_trichotomous_lex _ _ is_well_founded.wf } (classical.dec_rel _) section partial_order variables [linear_order ι] [is_well_order ι (<)] [Π i, partial_order (β i)] {x y : Π i, β i} {i : ι} {a b : β i} open function lemma to_lex_monotone : monotone (@to_lex (Π i, β i)) := λ a b h, or_iff_not_imp_left.2 $ λ hne, let ⟨i, hi, hl⟩ := is_well_founded.wf.has_min {i | a i ≠ b i} (function.ne_iff.1 hne) in ⟨i, λ j hj, by { contrapose! hl, exact ⟨j, hl, hj⟩ }, (h i).lt_of_ne hi⟩ lemma to_lex_strict_mono : strict_mono (@to_lex (Π i, β i)) := λ a b h, let ⟨i, hi, hl⟩ := is_well_founded.wf.has_min {i | a i ≠ b i} (function.ne_iff.1 h.ne) in ⟨i, λ j hj, by { contrapose! hl, exact ⟨j, hl, hj⟩ }, (h.le i).lt_of_ne hi⟩ @[simp] lemma lt_to_lex_update_self_iff : to_lex x < to_lex (update x i a) ↔ x i < a := begin refine ⟨_, λ h, to_lex_strict_mono $ lt_update_self_iff.2 h⟩, rintro ⟨j, hj, h⟩, dsimp at h, obtain rfl : j = i, { by_contra H, rw update_noteq H at h, exact h.false }, { rwa update_same at h } end @[simp] lemma to_lex_update_lt_self_iff : to_lex (update x i a) < to_lex x ↔ a < x i := begin refine ⟨_, λ h, to_lex_strict_mono $ update_lt_self_iff.2 h⟩, rintro ⟨j, hj, h⟩, dsimp at h, obtain rfl : j = i, { by_contra H, rw update_noteq H at h, exact h.false }, { rwa update_same at h } end @[simp] lemma le_to_lex_update_self_iff : to_lex x ≤ to_lex (update x i a) ↔ x i ≤ a := by simp_rw [le_iff_lt_or_eq, lt_to_lex_update_self_iff, to_lex_inj, eq_update_self_iff] @[simp] lemma to_lex_update_le_self_iff : to_lex (update x i a) ≤ to_lex x ↔ a ≤ x i := by simp_rw [le_iff_lt_or_eq, to_lex_update_lt_self_iff, to_lex_inj, update_eq_self_iff] end partial_order instance [linear_order ι] [is_well_order ι (<)] [Π a, partial_order (β a)] [Π a, order_bot (β a)] : order_bot (lex (Π a, β a)) := { bot := to_lex ⊥, bot_le := λ f, to_lex_monotone bot_le } instance [linear_order ι] [is_well_order ι (<)] [Π a, partial_order (β a)] [Π a, order_top (β a)] : order_top (lex (Π a, β a)) := { top := to_lex ⊤, le_top := λ f, to_lex_monotone le_top } instance [linear_order ι] [is_well_order ι (<)] [Π a, partial_order (β a)] [Π a, bounded_order (β a)] : bounded_order (lex (Π a, β a)) := { .. pi.lex.order_bot, .. pi.lex.order_top } instance [preorder ι] [Π i, has_lt (β i)] [Π i, densely_ordered (β i)] : densely_ordered (lex (Π i, β i)) := ⟨begin rintro _ _ ⟨i, h, hi⟩, obtain ⟨a, ha₁, ha₂⟩ := exists_between hi, classical, refine ⟨a₂.update _ a, ⟨i, λ j hj, _, _⟩, i, λ j hj, _, _⟩, rw h j hj, iterate 2 { { rw a₂.update_noteq hj.ne a }, { rwa a₂.update_same i a } }, end⟩ lemma lex.no_max_order' [preorder ι] [Π i, has_lt (β i)] (i : ι) [no_max_order (β i)] : no_max_order (lex (Π i, β i)) := ⟨λ a, begin classical, obtain ⟨b, hb⟩ := exists_gt (a i), exact ⟨a.update i b, i, λ j hj, (a.update_noteq hj.ne b).symm, by rwa a.update_same i b⟩ end⟩ instance [linear_order ι] [is_well_order ι (<)] [nonempty ι] [Π i, partial_order (β i)] [Π i, no_max_order (β i)] : no_max_order (lex (Π i, β i)) := ⟨λ a, let ⟨b, hb⟩ := exists_gt (of_lex a) in ⟨_, to_lex_strict_mono hb⟩⟩ instance [linear_order ι] [is_well_order ι (<)] [nonempty ι] [Π i, partial_order (β i)] [Π i, no_min_order (β i)] : no_min_order (lex (Π i, β i)) := ⟨λ a, let ⟨b, hb⟩ := exists_lt (of_lex a) in ⟨_, to_lex_strict_mono hb⟩⟩ --we might want the analog of `pi.ordered_cancel_comm_monoid` as well in the future @[to_additive] instance lex.ordered_comm_group [linear_order ι] [∀ a, ordered_comm_group (β a)] : ordered_comm_group (lex (Π i, β i)) := { mul_le_mul_left := λ x y hxy z, hxy.elim (λ hxyz, hxyz ▸ le_rfl) (λ ⟨i, hi⟩, or.inr ⟨i, λ j hji, show z j * x j = z j * y j, by rw hi.1 j hji, mul_lt_mul_left' hi.2 _⟩), ..pi.lex.partial_order, ..pi.comm_group } /-- If we swap two strictly decreasing values in a function, then the result is lexicographically smaller than the original function. -/ lemma lex_desc {α} [preorder ι] [decidable_eq ι] [preorder α] {f : ι → α} {i j : ι} (h₁ : i < j) (h₂ : f j < f i) : to_lex (f ∘ equiv.swap i j) < to_lex f := ⟨i, λ k hik, congr_arg f (equiv.swap_apply_of_ne_of_ne hik.ne (hik.trans h₁).ne), by simpa only [pi.to_lex_apply, function.comp_app, equiv.swap_apply_left] using h₂⟩ end pi
bf6fd87e97ecd230e7bd6a6c588cb43f48e6f5d9
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/library/data/int/order.lean
e88f5c4a8c850c58256a6cee49b66e51a16cfd1a
[ "Apache-2.0" ]
permissive
YHVHvx/lean
732bf0fb7a298cd7fe0f15d82f8e248c11db49e9
038369533e0136dd395dc252084d3c1853accbf2
refs/heads/master
1,610,701,080,210
1,449,128,595,000
1,449,128,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
17,799
lean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Jeremy Avigad The order relation on the integers. We show that int is an instance of linear_comm_ordered_ring and transfer the results. -/ import .basic algebra.ordered_ring open nat open algebra open decidable open int eq.ops namespace int private definition nonneg (a : ℤ) : Prop := int.cases_on a (take n, true) (take n, false) protected definition le (a b : ℤ) : Prop := nonneg (b - a) definition int_has_le [instance] [reducible] [priority int.prio]: has_le int := has_le.mk int.le protected definition lt (a b : ℤ) : Prop := (a + 1) ≤ b definition int_has_lt [instance] [reducible] [priority int.prio]: has_lt int := has_lt.mk int.lt local attribute nonneg [reducible] private definition decidable_nonneg [instance] (a : ℤ) : decidable (nonneg a) := int.cases_on a _ _ definition decidable_le [instance] (a b : ℤ) : decidable (a ≤ b) := decidable_nonneg _ definition decidable_lt [instance] (a b : ℤ) : decidable (a < b) := decidable_nonneg _ private theorem nonneg.elim {a : ℤ} : nonneg a → ∃n : ℕ, a = n := int.cases_on a (take n H, exists.intro n rfl) (take n', false.elim) private theorem nonneg_or_nonneg_neg (a : ℤ) : nonneg a ∨ nonneg (-a) := int.cases_on a (take n, or.inl trivial) (take n, or.inr trivial) theorem le.intro {a b : ℤ} {n : ℕ} (H : a + n = b) : a ≤ b := have n = b - a, from eq_add_neg_of_add_eq (begin rewrite [add.comm, H] end), -- !add.comm ▸ H), show nonneg (b - a), from this ▸ trivial theorem le.elim {a b : ℤ} (H : a ≤ b) : ∃n : ℕ, a + n = b := obtain (n : ℕ) (H1 : b - a = n), from nonneg.elim H, exists.intro n (!add.comm ▸ iff.mpr !add_eq_iff_eq_add_neg (H1⁻¹)) protected theorem le_total (a b : ℤ) : a ≤ b ∨ b ≤ a := or.imp_right (assume H : nonneg (-(b - a)), have -(b - a) = a - b, from !neg_sub, show nonneg (a - b), from this ▸ H) (nonneg_or_nonneg_neg (b - a)) theorem of_nat_le_of_nat_of_le {m n : ℕ} (H : #nat m ≤ n) : of_nat m ≤ of_nat n := obtain (k : ℕ) (Hk : m + k = n), from nat.le.elim H, le.intro (Hk ▸ (of_nat_add m k)⁻¹) theorem le_of_of_nat_le_of_nat {m n : ℕ} (H : of_nat m ≤ of_nat n) : (#nat m ≤ n) := obtain (k : ℕ) (Hk : of_nat m + of_nat k = of_nat n), from le.elim H, have m + k = n, from of_nat.inj (of_nat_add m k ⬝ Hk), nat.le.intro this theorem of_nat_le_of_nat_iff (m n : ℕ) : of_nat m ≤ of_nat n ↔ m ≤ n := iff.intro le_of_of_nat_le_of_nat of_nat_le_of_nat_of_le theorem lt_add_succ (a : ℤ) (n : ℕ) : a < a + succ n := le.intro (show a + 1 + n = a + succ n, from calc a + 1 + n = a + (1 + n) : add.assoc ... = a + (n + 1) : by rewrite (int.add_comm 1 n) ... = a + succ n : rfl) theorem lt.intro {a b : ℤ} {n : ℕ} (H : a + succ n = b) : a < b := H ▸ lt_add_succ a n theorem lt.elim {a b : ℤ} (H : a < b) : ∃n : ℕ, a + succ n = b := obtain (n : ℕ) (Hn : a + 1 + n = b), from le.elim H, have a + succ n = b, from calc a + succ n = a + 1 + n : by rewrite [add.assoc, int.add_comm 1 n] ... = b : Hn, exists.intro n this theorem of_nat_lt_of_nat_iff (n m : ℕ) : of_nat n < of_nat m ↔ n < m := calc of_nat n < of_nat m ↔ of_nat n + 1 ≤ of_nat m : iff.refl ... ↔ of_nat (nat.succ n) ≤ of_nat m : of_nat_succ n ▸ !iff.refl ... ↔ nat.succ n ≤ m : of_nat_le_of_nat_iff ... ↔ n < m : iff.symm (lt_iff_succ_le _ _) theorem lt_of_of_nat_lt_of_nat {m n : ℕ} (H : of_nat m < of_nat n) : #nat m < n := iff.mp !of_nat_lt_of_nat_iff H theorem of_nat_lt_of_nat_of_lt {m n : ℕ} (H : #nat m < n) : of_nat m < of_nat n := iff.mpr !of_nat_lt_of_nat_iff H /- show that the integers form an ordered additive group -/ protected theorem le_refl (a : ℤ) : a ≤ a := le.intro (add_zero a) protected theorem le_trans {a b c : ℤ} (H1 : a ≤ b) (H2 : b ≤ c) : a ≤ c := obtain (n : ℕ) (Hn : a + n = b), from le.elim H1, obtain (m : ℕ) (Hm : b + m = c), from le.elim H2, have a + of_nat (n + m) = c, from calc a + of_nat (n + m) = a + (of_nat n + m) : {of_nat_add n m} ... = a + n + m : (add.assoc a n m)⁻¹ ... = b + m : {Hn} ... = c : Hm, le.intro this protected theorem le_antisymm : ∀ {a b : ℤ}, a ≤ b → b ≤ a → a = b := take a b : ℤ, assume (H₁ : a ≤ b) (H₂ : b ≤ a), obtain (n : ℕ) (Hn : a + n = b), from le.elim H₁, obtain (m : ℕ) (Hm : b + m = a), from le.elim H₂, have a + of_nat (n + m) = a + 0, from calc a + of_nat (n + m) = a + (of_nat n + m) : by rewrite of_nat_add ... = a + n + m : by rewrite add.assoc ... = b + m : by rewrite Hn ... = a : by rewrite Hm ... = a + 0 : by rewrite add_zero, have of_nat (n + m) = of_nat 0, from add.left_cancel this, have n + m = 0, from of_nat.inj this, assert n = 0, from nat.eq_zero_of_add_eq_zero_right this, show a = b, from calc a = a + 0 : add_zero ... = a + n : by rewrite this ... = b : Hn protected theorem lt_irrefl (a : ℤ) : ¬ a < a := (suppose a < a, obtain (n : ℕ) (Hn : a + succ n = a), from lt.elim this, have a + succ n = a + 0, from Hn ⬝ !add_zero⁻¹, !succ_ne_zero (of_nat.inj (add.left_cancel this))) protected theorem ne_of_lt {a b : ℤ} (H : a < b) : a ≠ b := (suppose a = b, absurd (this ▸ H) (int.lt_irrefl b)) theorem le_of_lt {a b : ℤ} (H : a < b) : a ≤ b := obtain (n : ℕ) (Hn : a + succ n = b), from lt.elim H, le.intro Hn protected theorem lt_iff_le_and_ne (a b : ℤ) : a < b ↔ (a ≤ b ∧ a ≠ b) := iff.intro (assume H, and.intro (le_of_lt H) (int.ne_of_lt H)) (assume H, have a ≤ b, from and.elim_left H, have a ≠ b, from and.elim_right H, obtain (n : ℕ) (Hn : a + n = b), from le.elim `a ≤ b`, have n ≠ 0, from (assume H' : n = 0, `a ≠ b` (!add_zero ▸ H' ▸ Hn)), obtain (k : ℕ) (Hk : n = nat.succ k), from nat.exists_eq_succ_of_ne_zero this, lt.intro (Hk ▸ Hn)) protected theorem le_iff_lt_or_eq (a b : ℤ) : a ≤ b ↔ (a < b ∨ a = b) := iff.intro (assume H, by_cases (suppose a = b, or.inr this) (suppose a ≠ b, obtain (n : ℕ) (Hn : a + n = b), from le.elim H, have n ≠ 0, from (assume H' : n = 0, `a ≠ b` (!add_zero ▸ H' ▸ Hn)), obtain (k : ℕ) (Hk : n = nat.succ k), from nat.exists_eq_succ_of_ne_zero this, or.inl (lt.intro (Hk ▸ Hn)))) (assume H, or.elim H (assume H1, le_of_lt H1) (assume H1, H1 ▸ !int.le_refl)) theorem lt_succ (a : ℤ) : a < a + 1 := int.le_refl (a + 1) protected theorem add_le_add_left {a b : ℤ} (H : a ≤ b) (c : ℤ) : c + a ≤ c + b := obtain (n : ℕ) (Hn : a + n = b), from le.elim H, have H2 : c + a + n = c + b, from calc c + a + n = c + (a + n) : add.assoc c a n ... = c + b : {Hn}, le.intro H2 protected theorem add_lt_add_left {a b : ℤ} (H : a < b) (c : ℤ) : c + a < c + b := let H' := le_of_lt H in (iff.mpr (int.lt_iff_le_and_ne _ _)) (and.intro (int.add_le_add_left H' _) (take Heq, let Heq' := add_left_cancel Heq in !int.lt_irrefl (Heq' ▸ H))) protected theorem mul_nonneg {a b : ℤ} (Ha : 0 ≤ a) (Hb : 0 ≤ b) : 0 ≤ a * b := obtain (n : ℕ) (Hn : 0 + n = a), from le.elim Ha, obtain (m : ℕ) (Hm : 0 + m = b), from le.elim Hb, le.intro (eq.symm (calc a * b = (0 + n) * b : by rewrite Hn ... = n * b : by rewrite zero_add ... = n * (0 + m) : by rewrite Hm ... = n * m : by rewrite zero_add ... = 0 + n * m : by rewrite zero_add)) protected theorem mul_pos {a b : ℤ} (Ha : 0 < a) (Hb : 0 < b) : 0 < a * b := obtain (n : ℕ) (Hn : 0 + nat.succ n = a), from lt.elim Ha, obtain (m : ℕ) (Hm : 0 + nat.succ m = b), from lt.elim Hb, lt.intro (eq.symm (calc a * b = (0 + nat.succ n) * b : by rewrite Hn ... = nat.succ n * b : by rewrite zero_add ... = nat.succ n * (0 + nat.succ m) : by rewrite Hm ... = nat.succ n * nat.succ m : by rewrite zero_add ... = of_nat (nat.succ n * nat.succ m) : by rewrite of_nat_mul ... = of_nat (nat.succ n * m + nat.succ n) : by rewrite nat.mul_succ ... = of_nat (nat.succ (nat.succ n * m + n)) : by rewrite nat.add_succ ... = 0 + nat.succ (nat.succ n * m + n) : by rewrite zero_add)) protected theorem zero_lt_one : (0 : ℤ) < 1 := trivial protected theorem not_le_of_gt {a b : ℤ} (H : a < b) : ¬ b ≤ a := assume Hba, let Heq := int.le_antisymm (le_of_lt H) Hba in !int.lt_irrefl (Heq ▸ H) protected theorem lt_of_lt_of_le {a b c : ℤ} (Hab : a < b) (Hbc : b ≤ c) : a < c := let Hab' := le_of_lt Hab in let Hac := int.le_trans Hab' Hbc in (iff.mpr !int.lt_iff_le_and_ne) (and.intro Hac (assume Heq, int.not_le_of_gt (Heq ▸ Hab) Hbc)) protected theorem lt_of_le_of_lt {a b c : ℤ} (Hab : a ≤ b) (Hbc : b < c) : a < c := let Hbc' := le_of_lt Hbc in let Hac := int.le_trans Hab Hbc' in (iff.mpr !int.lt_iff_le_and_ne) (and.intro Hac (assume Heq, int.not_le_of_gt (Heq⁻¹ ▸ Hbc) Hab)) protected definition linear_ordered_comm_ring [reducible] [trans_instance] : algebra.linear_ordered_comm_ring int := ⦃algebra.linear_ordered_comm_ring, int.integral_domain, le := int.le, le_refl := int.le_refl, le_trans := @int.le_trans, le_antisymm := @int.le_antisymm, lt := int.lt, le_of_lt := @int.le_of_lt, lt_irrefl := int.lt_irrefl, lt_of_lt_of_le := @int.lt_of_lt_of_le, lt_of_le_of_lt := @int.lt_of_le_of_lt, add_le_add_left := @int.add_le_add_left, mul_nonneg := @int.mul_nonneg, mul_pos := @int.mul_pos, le_iff_lt_or_eq := int.le_iff_lt_or_eq, le_total := int.le_total, zero_ne_one := int.zero_ne_one, zero_lt_one := int.zero_lt_one, add_lt_add_left := @int.add_lt_add_left⦄ protected definition decidable_linear_ordered_comm_ring [reducible] [instance] : algebra.decidable_linear_ordered_comm_ring int := ⦃algebra.decidable_linear_ordered_comm_ring, int.linear_ordered_comm_ring, decidable_lt := decidable_lt⦄ /- more facts specific to int -/ theorem of_nat_nonneg (n : ℕ) : 0 ≤ of_nat n := trivial theorem of_nat_pos {n : ℕ} (Hpos : #nat n > 0) : of_nat n > 0 := of_nat_lt_of_nat_of_lt Hpos theorem of_nat_succ_pos (n : nat) : of_nat (nat.succ n) > 0 := of_nat_pos !nat.succ_pos theorem exists_eq_of_nat {a : ℤ} (H : 0 ≤ a) : ∃n : ℕ, a = of_nat n := obtain (n : ℕ) (H1 : 0 + of_nat n = a), from le.elim H, exists.intro n (!zero_add ▸ (H1⁻¹)) theorem exists_eq_neg_of_nat {a : ℤ} (H : a ≤ 0) : ∃n : ℕ, a = -(of_nat n) := have -a ≥ 0, from iff.mpr !neg_nonneg_iff_nonpos H, obtain (n : ℕ) (Hn : -a = of_nat n), from exists_eq_of_nat this, exists.intro n (eq_neg_of_eq_neg (Hn⁻¹)) theorem of_nat_nat_abs_of_nonneg {a : ℤ} (H : a ≥ 0) : of_nat (nat_abs a) = a := obtain (n : ℕ) (Hn : a = of_nat n), from exists_eq_of_nat H, Hn⁻¹ ▸ congr_arg of_nat (nat_abs_of_nat n) theorem of_nat_nat_abs_of_nonpos {a : ℤ} (H : a ≤ 0) : of_nat (nat_abs a) = -a := have -a ≥ 0, from iff.mpr !neg_nonneg_iff_nonpos H, calc of_nat (nat_abs a) = of_nat (nat_abs (-a)) : nat_abs_neg ... = -a : of_nat_nat_abs_of_nonneg this theorem of_nat_nat_abs (b : ℤ) : nat_abs b = abs b := or.elim (le.total 0 b) (assume H : b ≥ 0, of_nat_nat_abs_of_nonneg H ⬝ (abs_of_nonneg H)⁻¹) (assume H : b ≤ 0, of_nat_nat_abs_of_nonpos H ⬝ (abs_of_nonpos H)⁻¹) theorem nat_abs_abs (a : ℤ) : nat_abs (abs a) = nat_abs a := abs.by_cases rfl !nat_abs_neg theorem lt_of_add_one_le {a b : ℤ} (H : a + 1 ≤ b) : a < b := obtain (n : nat) (H1 : a + 1 + n = b), from le.elim H, have a + succ n = b, by rewrite [-H1, add.assoc, add.comm 1], lt.intro this theorem add_one_le_of_lt {a b : ℤ} (H : a < b) : a + 1 ≤ b := obtain (n : nat) (H1 : a + succ n = b), from lt.elim H, have a + 1 + n = b, by rewrite [-H1, add.assoc, add.comm 1], le.intro this theorem lt_add_one_of_le {a b : ℤ} (H : a ≤ b) : a < b + 1 := lt_add_of_le_of_pos H trivial theorem le_of_lt_add_one {a b : ℤ} (H : a < b + 1) : a ≤ b := have H1 : a + 1 ≤ b + 1, from add_one_le_of_lt H, le_of_add_le_add_right H1 theorem sub_one_le_of_lt {a b : ℤ} (H : a ≤ b) : a - 1 < b := lt_of_add_one_le (begin rewrite algebra.sub_add_cancel, exact H end) theorem lt_of_sub_one_le {a b : ℤ} (H : a - 1 < b) : a ≤ b := !sub_add_cancel ▸ add_one_le_of_lt H theorem le_sub_one_of_lt {a b : ℤ} (H : a < b) : a ≤ b - 1 := le_of_lt_add_one begin rewrite algebra.sub_add_cancel, exact H end theorem lt_of_le_sub_one {a b : ℤ} (H : a ≤ b - 1) : a < b := !sub_add_cancel ▸ (lt_add_one_of_le H) theorem sign_of_succ (n : nat) : sign (nat.succ n) = 1 := sign_of_pos (of_nat_pos !nat.succ_pos) theorem exists_eq_neg_succ_of_nat {a : ℤ} : a < 0 → ∃m : ℕ, a = -[1+m] := int.cases_on a (take (m : nat) H, absurd (of_nat_nonneg m : 0 ≤ m) (not_le_of_gt H)) (take (m : nat) H, exists.intro m rfl) theorem eq_one_of_mul_eq_one_right {a b : ℤ} (H : a ≥ 0) (H' : a * b = 1) : a = 1 := have a * b > 0, by rewrite H'; apply trivial, have b > 0, from pos_of_mul_pos_left this H, have a > 0, from pos_of_mul_pos_right `a * b > 0` (le_of_lt `b > 0`), or.elim (le_or_gt a 1) (suppose a ≤ 1, show a = 1, from le.antisymm this (add_one_le_of_lt `a > 0`)) (suppose a > 1, assert a * b ≥ 2 * 1, from mul_le_mul (add_one_le_of_lt `a > 1`) (add_one_le_of_lt `b > 0`) trivial H, have false, by rewrite [H' at this]; exact this, false.elim this) theorem eq_one_of_mul_eq_one_left {a b : ℤ} (H : b ≥ 0) (H' : a * b = 1) : b = 1 := eq_one_of_mul_eq_one_right H (!mul.comm ▸ H') theorem eq_one_of_mul_eq_self_left {a b : ℤ} (Hpos : a ≠ 0) (H : b * a = a) : b = 1 := eq_of_mul_eq_mul_right Hpos (H ⬝ (one_mul a)⁻¹) theorem eq_one_of_mul_eq_self_right {a b : ℤ} (Hpos : b ≠ 0) (H : b * a = b) : a = 1 := eq_one_of_mul_eq_self_left Hpos (!mul.comm ▸ H) theorem eq_one_of_dvd_one {a : ℤ} (H : a ≥ 0) (H' : a ∣ 1) : a = 1 := dvd.elim H' (take b, suppose 1 = a * b, eq_one_of_mul_eq_one_right H this⁻¹) theorem exists_least_of_bdd {P : ℤ → Prop} [HP : decidable_pred P] (Hbdd : ∃ b : ℤ, ∀ z : ℤ, z ≤ b → ¬ P z) (Hinh : ∃ z : ℤ, P z) : ∃ lb : ℤ, P lb ∧ (∀ z : ℤ, z < lb → ¬ P z) := begin cases Hbdd with [b, Hb], cases Hinh with [elt, Helt], existsi b + of_nat (least (λ n, P (b + of_nat n)) (nat.succ (nat_abs (elt - b)))), have Heltb : elt > b, begin apply lt_of_not_ge, intro Hge, apply (Hb _ Hge) Helt end, have H' : P (b + of_nat (nat_abs (elt - b))), begin rewrite [of_nat_nat_abs_of_nonneg (int.le_of_lt (iff.mpr !sub_pos_iff_lt Heltb)), add.comm, algebra.sub_add_cancel], apply Helt end, apply and.intro, apply least_of_lt _ !lt_succ_self H', intros z Hz, cases em (z ≤ b) with [Hzb, Hzb], apply Hb _ Hzb, let Hzb' := lt_of_not_ge Hzb, let Hpos := iff.mpr !sub_pos_iff_lt Hzb', have Hzbk : z = b + of_nat (nat_abs (z - b)), by rewrite [of_nat_nat_abs_of_nonneg (int.le_of_lt Hpos), int.add_comm, algebra.sub_add_cancel], have Hk : nat_abs (z - b) < least (λ n, P (b + of_nat n)) (nat.succ (nat_abs (elt - b))), begin let Hz' := iff.mp !lt_add_iff_sub_lt_left Hz, rewrite [-of_nat_nat_abs_of_nonneg (int.le_of_lt Hpos) at Hz'], apply lt_of_of_nat_lt_of_nat Hz' end, let Hk' := algebra.not_le_of_gt Hk, rewrite Hzbk, apply λ p, mt (ge_least_of_lt _ p) Hk', apply nat.lt_trans Hk, apply least_lt _ !lt_succ_self H' end theorem exists_greatest_of_bdd {P : ℤ → Prop} [HP : decidable_pred P] (Hbdd : ∃ b : ℤ, ∀ z : ℤ, z ≥ b → ¬ P z) (Hinh : ∃ z : ℤ, P z) : ∃ ub : ℤ, P ub ∧ (∀ z : ℤ, z > ub → ¬ P z) := begin cases Hbdd with [b, Hb], cases Hinh with [elt, Helt], existsi b - of_nat (least (λ n, P (b - of_nat n)) (nat.succ (nat_abs (b - elt)))), have Heltb : elt < b, begin apply lt_of_not_ge, intro Hge, apply (Hb _ Hge) Helt end, have H' : P (b - of_nat (nat_abs (b - elt))), begin rewrite [of_nat_nat_abs_of_nonneg (int.le_of_lt (iff.mpr !sub_pos_iff_lt Heltb)), sub_sub_self], apply Helt end, apply and.intro, apply least_of_lt _ !lt_succ_self H', intros z Hz, cases em (z ≥ b) with [Hzb, Hzb], apply Hb _ Hzb, let Hzb' := lt_of_not_ge Hzb, let Hpos := iff.mpr !sub_pos_iff_lt Hzb', have Hzbk : z = b - of_nat (nat_abs (b - z)), by rewrite [of_nat_nat_abs_of_nonneg (int.le_of_lt Hpos), sub_sub_self], have Hk : nat_abs (b - z) < least (λ n, P (b - of_nat n)) (nat.succ (nat_abs (b - elt))), begin let Hz' := iff.mp !lt_add_iff_sub_lt_left (iff.mpr !lt_add_iff_sub_lt_right Hz), rewrite [-of_nat_nat_abs_of_nonneg (int.le_of_lt Hpos) at Hz'], apply lt_of_of_nat_lt_of_nat Hz' end, let Hk' := algebra.not_le_of_gt Hk, rewrite Hzbk, apply λ p, mt (ge_least_of_lt _ p) Hk', apply nat.lt_trans Hk, apply least_lt _ !lt_succ_self H' end end int
f97cad6e5d4a49b763c25bd5dcf7328e8d6443e0
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/probability/cond_count.lean
97ec5c4acea2ba728820ed4cbf54a4c09b52d08c
[ "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
8,351
lean
/- Copyright (c) 2022 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying, Bhavik Mehta -/ import probability.conditional_probability /-! # Classical probability The classical formulation of probability states that the probability of an event occurring in a finite probability space is the ratio of that event to all possible events. This notion can be expressed with measure theory using the counting measure. In particular, given the sets `s` and `t`, we define the probability of `t` occuring in `s` to be `|s|⁻¹ * |s ∩ t|`. With this definition, we recover the the probability over the entire sample space when `s = set.univ`. Classical probability is often used in combinatorics and we prove some useful lemmas in this file for that purpose. ## Main definition * `probability_theory.cond_count`: given a set `s`, `cond_count s` is the counting measure conditioned on `s`. This is a probability measure when `s` is finite and nonempty. ## Notes The original aim of this file is to provide a measure theoretic method of describing the probability an element of a set `s` satisfies some predicate `P`. Our current formulation still allow us to describe this by abusing the definitional equality of sets and predicates by simply writing `cond_count s P`. We should avoid this however as none of the lemmas are written for predicates. -/ noncomputable theory open_locale probability_theory open measure_theory measurable_space namespace probability_theory variables {Ω : Type*} [measurable_space Ω] /-- Given a set `s`, `cond_count s` is the counting measure conditioned on `s`. In particular, `cond_count s t` is the proportion of `s` that is contained in `t`. This is a probability measure when `s` is finite and nonempty and is given by `probability_theory.cond_count_is_probability_measure`. -/ def cond_count (s : set Ω) : measure Ω := measure.count[|s] @[simp] lemma cond_count_empty_meas : (cond_count ∅ : measure Ω) = 0 := by simp [cond_count] lemma cond_count_empty {s : set Ω} : cond_count s ∅ = 0 := by simp lemma finite_of_cond_count_ne_zero {s t : set Ω} (h : cond_count s t ≠ 0) : s.finite := begin by_contra hs', simpa [cond_count, cond, measure.count_apply_infinite hs'] using h, end variables [measurable_singleton_class Ω] lemma cond_count_is_probability_measure {s : set Ω} (hs : s.finite) (hs' : s.nonempty) : is_probability_measure (cond_count s) := { measure_univ := begin rw [cond_count, cond_apply _ hs.measurable_set, set.inter_univ, ennreal.inv_mul_cancel], { exact λ h, hs'.ne_empty $ measure.empty_of_count_eq_zero h }, { exact (measure.count_apply_lt_top.2 hs).ne } end } lemma cond_count_singleton (ω : Ω) (t : set Ω) [decidable (ω ∈ t)] : cond_count {ω} t = if ω ∈ t then 1 else 0 := begin rw [cond_count, cond_apply _ (measurable_set_singleton ω), measure.count_singleton, ennreal.inv_one, one_mul], split_ifs, { rw [(by simpa : ({ω} : set Ω) ∩ t = {ω}), measure.count_singleton] }, { rw [(by simpa : ({ω} : set Ω) ∩ t = ∅), measure.count_empty] }, end variables {s t u : set Ω} lemma cond_count_inter_self (hs : s.finite): cond_count s (s ∩ t) = cond_count s t := by rw [cond_count, cond_inter_self _ hs.measurable_set] lemma cond_count_self (hs : s.finite) (hs' : s.nonempty) : cond_count s s = 1 := begin rw [cond_count, cond_apply _ hs.measurable_set, set.inter_self, ennreal.inv_mul_cancel], { exact λ h, hs'.ne_empty $ measure.empty_of_count_eq_zero h }, { exact (measure.count_apply_lt_top.2 hs).ne } end lemma cond_count_eq_one_of (hs : s.finite) (hs' : s.nonempty) (ht : s ⊆ t) : cond_count s t = 1 := begin haveI := cond_count_is_probability_measure hs hs', refine eq_of_le_of_not_lt prob_le_one _, rw [not_lt, ← cond_count_self hs hs'], exact measure_mono ht, end lemma pred_true_of_cond_count_eq_one (h : cond_count s t = 1) : s ⊆ t := begin have hsf := finite_of_cond_count_ne_zero (by { rw h, exact one_ne_zero }), rw [cond_count, cond_apply _ hsf.measurable_set, mul_comm] at h, replace h := ennreal.eq_inv_of_mul_eq_one_left h, rw [inv_inv, measure.count_apply_finite _ hsf, measure.count_apply_finite _ (hsf.inter_of_left _), nat.cast_inj] at h, suffices : s ∩ t = s, { exact this ▸ λ x hx, hx.2 }, rw ← @set.finite.to_finset_inj _ _ _ (hsf.inter_of_left _) hsf, exact finset.eq_of_subset_of_card_le (set.finite.to_finset_mono.2 (s.inter_subset_left t)) h.symm.le end lemma cond_count_eq_zero_iff (hs : s.finite) : cond_count s t = 0 ↔ s ∩ t = ∅ := by simp [cond_count, cond_apply _ hs.measurable_set, measure.count_apply_eq_top, set.not_infinite.2 hs, measure.count_apply_finite _ (hs.inter_of_left _)] lemma cond_count_univ (hs : s.finite) (hs' : s.nonempty) : cond_count s set.univ = 1 := cond_count_eq_one_of hs hs' s.subset_univ lemma cond_count_inter (hs : s.finite) : cond_count s (t ∩ u) = cond_count (s ∩ t) u * cond_count s t := begin by_cases hst : s ∩ t = ∅, { rw [hst, cond_count_empty_meas, measure.coe_zero, pi.zero_apply, zero_mul, cond_count_eq_zero_iff hs, ← set.inter_assoc, hst, set.empty_inter] }, rw [cond_count, cond_count, cond_apply _ hs.measurable_set, cond_apply _ hs.measurable_set, cond_apply _ (hs.inter_of_left _).measurable_set, mul_comm _ (measure.count (s ∩ t)), ← mul_assoc, mul_comm _ (measure.count (s ∩ t)), ← mul_assoc, ennreal.mul_inv_cancel, one_mul, mul_comm, set.inter_assoc], { rwa ← measure.count_eq_zero_iff at hst }, { exact (measure.count_apply_lt_top.2 $ hs.inter_of_left _).ne } end lemma cond_count_inter' (hs : s.finite) : cond_count s (t ∩ u) = cond_count (s ∩ u) t * cond_count s u := begin rw ← set.inter_comm, exact cond_count_inter hs, end lemma cond_count_union (hs : s.finite) (htu : disjoint t u) : cond_count s (t ∪ u) = cond_count s t + cond_count s u := begin rw [cond_count, cond_apply _ hs.measurable_set, cond_apply _ hs.measurable_set, cond_apply _ hs.measurable_set, set.inter_union_distrib_left, measure_union, mul_add], exacts [htu.mono inf_le_right inf_le_right, (hs.inter_of_left _).measurable_set], end lemma cond_count_compl (t : set Ω) (hs : s.finite) (hs' : s.nonempty) : cond_count s t + cond_count s tᶜ = 1 := begin rw [← cond_count_union hs disjoint_compl_right, set.union_compl_self, (cond_count_is_probability_measure hs hs').measure_univ], end lemma cond_count_disjoint_union (hs : s.finite) (ht : t.finite) (hst : disjoint s t) : cond_count s u * cond_count (s ∪ t) s + cond_count t u * cond_count (s ∪ t) t = cond_count (s ∪ t) u := begin rcases s.eq_empty_or_nonempty with (rfl | hs'); rcases t.eq_empty_or_nonempty with (rfl | ht'), { simp }, { simp [cond_count_self ht ht'] }, { simp [cond_count_self hs hs'] }, rw [cond_count, cond_count, cond_count, cond_apply _ hs.measurable_set, cond_apply _ ht.measurable_set, cond_apply _ (hs.union ht).measurable_set, cond_apply _ (hs.union ht).measurable_set, cond_apply _ (hs.union ht).measurable_set], conv_lhs { rw [set.union_inter_cancel_left, set.union_inter_cancel_right, mul_comm (measure.count (s ∪ t))⁻¹, mul_comm (measure.count (s ∪ t))⁻¹, ← mul_assoc, ← mul_assoc, mul_comm _ (measure.count s), mul_comm _ (measure.count t), ← mul_assoc, ← mul_assoc] }, rw [ennreal.mul_inv_cancel, ennreal.mul_inv_cancel, one_mul, one_mul, ← add_mul, ← measure_union, set.union_inter_distrib_right, mul_comm], exacts [hst.mono inf_le_left inf_le_left, (ht.inter_of_left _).measurable_set, measure.count_ne_zero ht', (measure.count_apply_lt_top.2 ht).ne, measure.count_ne_zero hs', (measure.count_apply_lt_top.2 hs).ne], end /-- A version of the law of total probability for counting probabilites. -/ lemma cond_count_add_compl_eq (u t : set Ω) (hs : s.finite) : cond_count (s ∩ u) t * cond_count s u + cond_count (s ∩ uᶜ) t * cond_count s uᶜ = cond_count s t := begin conv_rhs { rw [(by simp : s = s ∩ u ∪ s ∩ uᶜ), ← cond_count_disjoint_union (hs.inter_of_left _) (hs.inter_of_left _) (disjoint_compl_right.mono inf_le_right inf_le_right)] }, simp [cond_count_inter_self hs], end end probability_theory
eb41fad4ae674505c58a8845c8c381f84bcccd32
3dd1b66af77106badae6edb1c4dea91a146ead30
/tests/lean/run/tactic22.lean
a6623c176256cbb53f15d10e1d5fe5875d02b7e4
[ "Apache-2.0" ]
permissive
silky/lean
79c20c15c93feef47bb659a2cc139b26f3614642
df8b88dca2f8da1a422cb618cd476ef5be730546
refs/heads/master
1,610,737,587,697
1,406,574,534,000
1,406,574,534,000
22,362,176
1
0
null
null
null
null
UTF-8
Lean
false
false
181
lean
import standard using tactic theorem T (a b c d : Prop) (Ha : a) (Hb : b) (Hc : c) (Hd : d) : a ∧ b ∧ c ∧ d := by fixpoint (λ f, [apply @and_intro; f | assumption; f | id])
ff38a596c95f499b6d93ab9cb6e2d54a51b3904f
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/revert_err.lean
981a83348baed569fa7a4b12dc254188b625d3f2
[ "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
136
lean
open tactic example (a b : Prop) : true := by do to_expr ```(a ∧ b) >>= revert example {α : Type} {a : α} : true := by revert a a
a3db70f655453408d43b98ebd2d1a5d9871cf031
0c1546a496eccfb56620165cad015f88d56190c5
/library/init/meta/async_tactic.lean
31f486d4d0b46b27411181074348ec2338ea96b3
[ "Apache-2.0" ]
permissive
Solertis/lean
491e0939957486f664498fbfb02546e042699958
84188c5aa1673fdf37a082b2de8562dddf53df3f
refs/heads/master
1,610,174,257,606
1,486,263,620,000
1,486,263,620,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,952
lean
prelude import init.meta.tactic import init.meta.interactive namespace tactic private meta def run_or_fail {α} (s : tactic_state) (tac : tactic α) : α := match tac s with | (tactic_result.success a s) := a | (tactic_result.exception .α fmt _ s') := undefined_core $ to_string $ fmt () ++ format.line ++ to_fmt s' end meta def run_async {α : Type} (tac : tactic α) : tactic (task α) := do s ← read, return $ task.delay $ λ _, match tac s with | (tactic_result.success a s) := a | (tactic_result.exception .α fmt _ s') := undefined_core $ to_string $ fmt () ++ format.line ++ to_fmt s' end private meta def get_undeclared_const (env : environment) (base : name) : ℕ → name | i := let n := base <.> ("_aux_" ++ to_string i) in if ¬env^.contains n then n else get_undeclared_const (i+1) meta def new_aux_decl_name : tactic name := do env ← get_env, n ← decl_name, return $ get_undeclared_const env n 1 meta def prove_goal_async (tac : tactic unit) : tactic unit := do ctx ← local_context, revert_lst ctx, tgt ← target, tgt ← instantiate_mvars tgt, env ← get_env, tgt ← return $ env^.unfold_untrusted_macros tgt, when tgt^.has_meta_var (fail $ "goal contains metavariables"), params ← return tgt^.collect_univ_params, lemma_name ← new_aux_decl_name, proof ← run_async (do goal_meta ← mk_meta_var tgt, set_goals [goal_meta], monad.for' ctx (λc, intro c^.local_pp_name), tac, proof ← instantiate_mvars goal_meta, proof ← return $ env^.unfold_untrusted_macros proof, when proof^.has_meta_var $ fail "async proof failed: contains metavariables", return proof), add_decl $ declaration.thm lemma_name params tgt proof, exact (expr.const lemma_name (params^.for level.param)) namespace interactive open interactive.types /-- Proves the first goal asynchronously as a separate lemma. -/ meta def async (tac : itactic) : tactic unit := prove_goal_async tac end interactive end tactic
3256dd9f39d4335f5e9d14b74b6e611735cc24d6
037dba89703a79cd4a4aec5e959818147f97635d
/src/2022/functions/sheet1.lean
10210e39c127c790db5ccb30a2b775dec1849652
[]
no_license
ImperialCollegeLondon/M40001_lean
3a6a09298da395ab51bc220a535035d45bbe919b
62a76fa92654c855af2b2fc2bef8e60acd16ccec
refs/heads/master
1,666,750,403,259
1,665,771,117,000
1,665,771,117,000
209,141,835
115
12
null
1,640,270,596,000
1,568,749,174,000
Lean
UTF-8
Lean
false
false
3,506
lean
/- Copyright (c) 2022 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author : Kevin Buzzard -/ import tactic -- imports all the Lean tactics /-! # Functions in Lean. In this sheet we'll learn how to manipulate the concepts of injectivity and surjectivity in Lean. The notation for functions is the usual one in mathematics: if `X` and `Y` are types, then `f : X → Y` denotes a function from `X` to `Y`. In fact what is going on here is that `X → Y` denotes the type of all functions from `X` to `Y`, and `f : X → Y` means that `f` is a term of type `X → Y`, i.e., a function from `X` to `Y`. One thing worth mentioning is that the simplest kind of function evaluation, where you have `x : X` and `f : X → Y`, doesn't need brackets: you can just write `f x` instead of `f(x)`. You only need it when evaluating a function at a more complex object; for example if we also had `g : Y → Z` then we can't write `g f x` for `g(f(x))`, we have to write `g(f x)` otherwise `g` would eat `f` and get confused. Without brackets, a function just eats the next term greedily. ## The API we'll be using Lean has the predicates `function.injective` and `function.surjective` on functions. In other words, if `f : X → Y` is a function, then `function.injective f` and `function.surjective f` are true-false statements. -/ -- Typing `function.` gets old quite quickly, so let's open the function namespace open function -- Now we can just write `injective f` and `surjective f`. -- Our functions will go between these sets, or Types as Lean calls them variables (X Y Z : Type) -- Let's prove some theorems, each of which are true by definition. theorem injective_def (f : X → Y) : injective f ↔ ∀ (a b : X), f a = f b → a = b := begin refl -- this proof works, because `injective f` -- means ∀ a b, f a = f b → a = b *by definition* -- so the proof is "it's reflexivity of `↔`" end -- similarly this is the *definition* of `surjective f` theorem surjective_def (f : X → Y) : surjective f ↔ ∀ b : Y, ∃ a : X, f a = b := begin refl end -- similarly the *definition* of `id x` is `x` theorem id_eval (x : X) : id x = x := begin refl end -- Function composition is `∘` in Lean (find out how to type it by putting your cursor on it). -- The *definition* of (g ∘ f) (x) is g(f(x)). theorem comp_eval (f : X → Y) (g : Y → Z) (x : X) : (g ∘ f) x = g (f x) := begin refl end -- Why did we just prove all those theorems with a proof -- saying "it's true by definition"? Because now, if we want, -- we can `rw` the theorems to replace things by their definitions. example : injective (id : X → X) := begin -- you can start with `rw injective_def` if you like, -- and later you can `rw id_eval`, although `rw` doesn't -- work under binders like `∀`, so use `intro` first. sorry end example : surjective (id : X → X) := begin sorry end example (f : X → Y) (g : Y → Z) (hf : injective f) (hg : injective g) : injective (g ∘ f) := begin sorry end example (f : X → Y) (g : Y → Z) (hf : surjective f) (hg : surjective g) : surjective (g ∘ f) := begin sorry, end -- This is a question on the IUM function problem sheet example (f : X → Y) (g : Y → Z) : injective (g ∘ f) → injective f := begin sorry end -- This is another one example (f : X → Y) (g : Y → Z) : surjective (g ∘ f) → surjective g := begin sorry end
89f5111649751ed8fc26aa2c420dcccd8f1256bb
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/data/nat/fib.lean
0694d631ed87d1be964a812dc60f539848a69548
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
3,326
lean
/- Copyright (c) 2019 Kevin Kappelmann. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Kappelmann -/ import data.stream.basic import tactic.norm_num import tactic.monotonicity /-! # The Fibonacci Sequence ## Summary Definition of the Fibonacci sequence `F₀ = 0, F₁ = 1, Fₙ₊₂ = Fₙ + Fₙ₊₁`. ## Main Definitions - `fib` returns the stream of Fibonacci numbers. ## Main Statements - `fib_succ_succ` shows that `fib` indeed satisfies the Fibonacci recurrence `Fₙ₊₂ = Fₙ + Fₙ₊₁.`. ## Implementation Notes For efficiency purposes, the sequence is defined using `stream.iterate`. ## Tags fib, fibonacci -/ namespace nat /-- Auxiliary stream creating Fibonacci pairs `⟨Fₙ, Fₙ₊₁⟩`. -/ private def fib_aux_stream : stream (ℕ × ℕ) := stream.iterate (λ p, ⟨p.snd, p.fst + p.snd⟩) ⟨0, 1⟩ /-- Implementation of the fibonacci sequence satisfying `fib 0 = 0, fib 1 = 1, fib (n + 2) = fib n + fib (n + 1)`. *Note:* We use a stream iterator for better performance when compared to the naive recursive implementation. -/ def fib (n : ℕ) : ℕ := (fib_aux_stream n).fst @[simp] lemma fib_zero : fib 0 = 0 := rfl @[simp] lemma fib_one : fib 1 = 1 := rfl private lemma fib_recurrence_aux {n : ℕ} : (fib_aux_stream (n + 1)).fst = (fib_aux_stream n).snd := begin change (stream.nth (n + 1) $ stream.iterate _ (0, 1)).fst = _, rw [stream.nth_succ_iterate, stream.map_iterate, stream.nth_map, fib_aux_stream] end /-- Shows that `fib` indeed satisfies the Fibonacci recurrence `Fₙ₊₂ = Fₙ + Fₙ₊₁.` -/ lemma fib_succ_succ {n : ℕ} : fib (n + 2) = fib n + fib (n + 1) := begin rw [fib, fib_recurrence_aux], change (stream.nth (n + 1) $ stream.iterate (λ p, _) (0, 1)).snd = _, rw [stream.nth_succ_iterate, stream.map_iterate, stream.nth_map], suffices : (fib_aux_stream n).snd = (stream.iterate (λ p, _) (0, 1) (n + 1)).fst, by simpa only [fib, fib.aux_stream], rw ←fib_recurrence_aux, refl end lemma fib_pos {n : ℕ} (n_pos : 0 < n) : 0 < fib n := begin induction n with n IH, case nat.zero { norm_num at n_pos }, case nat.succ { cases n, case nat.zero { simp [fib_succ_succ, zero_lt_one] }, case nat.succ { have : 0 ≤ fib n, by simp, exact (lt_add_of_nonneg_of_lt this $ IH n.succ_pos) }} end lemma fib_le_fib_succ {n : ℕ} : fib n ≤ fib (n + 1) := by { cases n; simp [fib_succ_succ] } lemma fib_mono {n m : ℕ} (n_le_m : n ≤ m) : fib n ≤ fib m := by { induction n_le_m with m n_le_m IH, { refl }, { exact (le_trans IH fib_le_fib_succ) }} lemma le_fib_self {n : ℕ} (five_le_n : 5 ≤ n) : n ≤ fib n := begin induction five_le_n with n five_le_n IH, { have : 5 = fib 5, by refl, -- 5 ≤ fib 5 exact le_of_eq this }, { -- n + 1 ≤ fib (n + 1) for 5 ≤ n cases n with n', -- rewrite n = succ n' to use fib.succ_succ { have : 5 = 0, from nat.le_zero_iff.elim_left five_le_n, contradiction }, rw fib_succ_succ, suffices : 1 + (n' + 1) ≤ fib n' + fib (n' + 1), by rwa [nat.succ_eq_add_one, add_comm], have : n' ≠ 0, by { intro h, have : 5 ≤ 1, by rwa h at five_le_n, norm_num at this }, have : 1 ≤ fib n', from nat.succ_le_of_lt (fib_pos $ zero_lt_iff_ne_zero.mpr this), mono } end end nat
4d58b3bd4c1f870be4be10eb575edeecea50d35f
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/section1.lean
5f34e4f246c07b7f3ee983bb1f6435b790301ee4
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
212
lean
open tactic section set_option pp.universes true set_option pp.implicit true variable {A : Type} variables {a b : A} variable H : a = b variables H1 H2 : b = a check H1 check H check H2 end
2f798eac6bd2f96f1d1295a67a44f0a95d459850
fbef61907e2e2afef7e1e91395505ed27448a945
/LeanProtocPlugin/Helpers.lean
ebf061f22852a9d0101d84f411128924d1e9d629
[ "MIT" ]
permissive
yatima-inc/Protoc.lean
7edecca1f5b33909e6dfef1bcebcbbf9a322ca8c
3ad7839ec911906e19984e5b60958ee9c866b7ec
refs/heads/master
1,682,196,995,576
1,620,507,180,000
1,620,507,180,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,978
lean
import AssertCmd import Std.Data.RBTree import Std.Data.RBMap import Init.System.IO instance : MonadLift (Except ε) (EIO ε) := ⟨fun e => match e with | Except.ok r => pure r | Except.error e => fun s => EStateM.Result.error e s ⟩ def String.toCamelCase (s: String) (firstCap : Bool) : String := do let mut newString := "" let mut sawUnderscoreBefore := false for idx in [:s.length] do if s[idx] == '_' then sawUnderscoreBefore := true continue if s[idx].isLower && (sawUnderscoreBefore || (idx == 0 && firstCap)) then newString := newString.push s[idx].toUpper else newString := newString.push s[idx] sawUnderscoreBefore := false return newString #assert (String.toCamelCase "_one_two__three_" true) == "OneTwoThree" #assert (String.toCamelCase "one_two__three_" true) == "OneTwoThree" #assert (String.toCamelCase "one_two__three_" false) == "oneTwoThree" def rbtreeOfC [Ord α] (a: Array α) := Std.rbtreeOf a.toList Ord.compare def rbmapOfC [Ord α] (a: Array (α × β)) := Std.rbmapOf a.toList Ord.compare abbrev Std.RBMapC (α β) [Ord α] := Std.RBMap α β Ord.compare abbrev Std.RBTreeC (α) [Ord α] := Std.RBTree α Ord.compare def String.stripFileEnding (s: String) := (s.dropRightWhile (· != '.')).dropRight 1 def packageNamePieceToLean (s: String) := (s.toCamelCase true) def fileTopNameToLean (s: String) := (s.toCamelCase true) def protoMessageNameToLean (s: String) := (s.toCamelCase true) def protoEnumNameToLean (s: String) := (s.toCamelCase true) def protoOneofNameToLean (s: String) := (s.toCamelCase true) ++ "Oneof" def protoEndpointNameToLean (s: String) := (s.toCamelCase true) def protoServiceNameToLean (s: String) := (s.toCamelCase false) ++ "Service" def reservedNames := rbtreeOfC #["syntax", "begin", "end", "structure", "inductive", "class", "where"] def fieldNameToLean (s: String) := let mapped := (s.toCamelCase false) if reservedNames.contains mapped then "_"++mapped else mapped def filePathPartsToLeanPackageParts (x: List String) := let rec work : List String -> List String | List.nil => List.nil | s :: List.nil => fileTopNameToLean s :: List.nil | s :: xs => packageNamePieceToLean s :: work xs work x def filePathToPackage (s: String) : String := do let f := filePathPartsToLeanPackageParts $ s.stripFileEnding.splitOn "/" ".".intercalate f #assert (filePathToPackage "google/protobuf/compiler/plugin.proto") == "Google.Protobuf.Compiler.Plugin" def protoPackageToLeanPackagePrefix (s: String) : String := let trimmed := if s.get 0 == '.' then s.drop 1 else s trimmed.splitOn "." |> (·.map packageNamePieceToLean) |> (".".intercalate ·) partial def IO.FS.Stream.readBinToEnd [Monad m] [MonadLiftT IO m] (h : IO.FS.Stream) : m ByteArray := do let rec loop (acc : ByteArray) : m ByteArray := do if ← h.isEof then return acc else let buf ← h.read 1024 loop (acc ++ buf) loop ByteArray.empty
3846d4ebc24fa31c91e7b0bcf2f6bf9051f7ff02
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/ring_theory/localization.lean
a20cfa4ff763f7ab597601fdf29a7087bcd0c246
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
49,253
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro, Johan Commelin, Amelia Livingston -/ import data.equiv.ring import tactic.ring_exp import ring_theory.ideal_operations import group_theory.monoid_localization import ring_theory.algebraic import ring_theory.integral_closure /-! # Localizations of commutative rings We characterize the localization of a commutative ring `R` at a submonoid `M` up to isomorphism; that is, a commutative ring `S` is the localization of `R` at `M` iff we can find a ring homomorphism `f : R →+* S` satisfying 3 properties: 1. For all `y ∈ M`, `f y` is a unit; 2. For all `z : S`, there exists `(x, y) : R × M` such that `z * f y = f x`; 3. For all `x, y : R`, `f x = f y` iff there exists `c ∈ M` such that `x * c = y * c`. Given such a localization map `f : R →+* S`, we can define the surjection `localization_map.mk'` sending `(x, y) : R × M` to `f x * (f y)⁻¹`, and `localization_map.lift`, the homomorphism from `S` induced by a homomorphism from `R` which maps elements of `M` to invertible elements of the codomain. Similarly, given commutative rings `P, Q`, a submonoid `T` of `P` and a localization map for `T` from `P` to `Q`, then a homomorphism `g : R →+* P` such that `g(M) ⊆ T` induces a homomorphism of localizations, `localization_map.map`, from `S` to `Q`. We show the localization as a quotient type, defined in `group_theory.monoid_localization` as `submonoid.localization`, is a `comm_ring` and that the natural ring hom `of : R →+* localization M` is a localization map. We show that a localization at the complement of a prime ideal is a local ring. We prove some lemmas about the `R`-algebra structure of `S`. When `R` is an integral domain, we define `fraction_map R K` as an abbreviation for `localization (non_zero_divisors R) K`, the natural map to `R`'s field of fractions. We show that a `comm_ring` `K` which is the localization of an integral domain `R` at `R \ {0}` is a field. We use this to show the field of fractions as a quotient type, `fraction_ring`, is a field. ## Implementation notes In maths it is natural to reason up to isomorphism, but in Lean we cannot naturally `rewrite` one structure with an isomorphic one; one way around this is to isolate a predicate characterizing a structure up to isomorphism, and reason about things that satisfy the predicate. A ring localization map is defined to be a localization map of the underlying `comm_monoid` (a `submonoid.localization_map`) which is also a ring hom. To prove most lemmas about a `localization_map` `f` in this file we invoke the corresponding proof for the underlying `comm_monoid` localization map `f.to_localization_map`, which can be found in `group_theory.monoid_localization` and the namespace `submonoid.localization_map`. To apply a localization map `f` as a function, we use `f.to_map`, as coercions don't work well for this structure. To reason about the localization as a quotient type, use `mk_eq_of_mk'` and associated lemmas. These show the quotient map `mk : R → M → localization M` equals the surjection `localization_map.mk'` induced by the map `of : localization_map M (localization M)` (where `of` establishes the localization as a quotient type satisfies the characteristic predicate). The lemma `mk_eq_of_mk'` hence gives you access to the results in the rest of the file, which are about the `localization_map.mk'` induced by any localization map. We define a copy of the localization map `f`'s codomain `S` carrying the data of `f` so that instances on `S` induced by `f` can 'know' the map needed to induce the instance. The proof that "a `comm_ring` `K` which is the localization of an integral domain `R` at `R \ {0}` is a field" is a `def` rather than an `instance`, so if you want to reason about a field of fractions `K`, assume `[field K]` instead of just `[comm_ring K]`. ## Tags localization, ring localization, commutative ring localization, characteristic predicate, commutative ring, field of fractions -/ variables {R : Type*} [comm_ring R] (M : submonoid R) (S : Type*) [comm_ring S] {P : Type*} [comm_ring P] open function set_option old_structure_cmd true /-- The type of ring homomorphisms satisfying the characteristic predicate: if `f : R →+* S` satisfies this predicate, then `S` is isomorphic to the localization of `R` at `M`. We later define an instance coercing a localization map `f` to its codomain `S` so that instances on `S` induced by `f` can 'know' the map needed to induce the instance. -/ @[nolint has_inhabited_instance] structure localization_map extends ring_hom R S, submonoid.localization_map M S /-- The ring hom underlying a `localization_map`. -/ add_decl_doc localization_map.to_ring_hom /-- The `comm_monoid` `localization_map` underlying a `comm_ring` `localization_map`. See `group_theory.monoid_localization` for its definition. -/ add_decl_doc localization_map.to_localization_map variables {M S} namespace ring_hom /-- Makes a localization map from a `comm_ring` hom satisfying the characteristic predicate. -/ def to_localization_map (f : R →+* S) (H1 : ∀ y : M, is_unit (f y)) (H2 : ∀ z, ∃ x : R × M, z * f x.2 = f x.1) (H3 : ∀ x y, f x = f y ↔ ∃ c : M, x * c = y * c) : localization_map M S := { map_units' := H1, surj' := H2, eq_iff_exists' := H3, .. f } end ring_hom /-- Makes a `comm_ring` localization map from an additive `comm_monoid` localization map of `comm_ring`s. -/ def submonoid.localization_map.to_ring_localization (f : submonoid.localization_map M S) (h : ∀ x y, f.to_map (x + y) = f.to_map x + f.to_map y) : localization_map M S := { ..ring_hom.mk' f.to_monoid_hom h, ..f } namespace localization_map variables (f : localization_map M S) /-- We define a copy of the localization map `f`'s codomain `S` carrying the data of `f` so that instances on `S` induced by `f` can 'know` the map needed to induce the instance. -/ @[nolint unused_arguments has_inhabited_instance] def codomain (f : localization_map M S) := S instance : comm_ring f.codomain := by assumption instance {K : Type*} [field K] (f : localization_map M K) : field f.codomain := by assumption /-- Short for `to_ring_hom`; used for applying a localization map as a function. -/ abbreviation to_map := f.to_ring_hom lemma map_units (y : M) : is_unit (f.to_map y) := f.6 y lemma surj (z) : ∃ x : R × M, z * f.to_map x.2 = f.to_map x.1 := f.7 z lemma eq_iff_exists {x y} : f.to_map x = f.to_map y ↔ ∃ c : M, x * c = y * c := f.8 x y @[ext] lemma ext {f g : localization_map M S} (h : ∀ x, f.to_map x = g.to_map x) : f = g := begin cases f, cases g, simp only at *, exact funext h end lemma ext_iff {f g : localization_map M S} : f = g ↔ ∀ x, f.to_map x = g.to_map x := ⟨λ h x, h ▸ rfl, ext⟩ lemma to_map_injective : injective (@localization_map.to_map _ _ M S _) := λ _ _ h, ext $ ring_hom.ext_iff.1 h /-- Given `a : S`, `S` a localization of `R`, `is_integer a` iff `a` is in the image of the localization map from `R` to `S`. -/ def is_integer (a : S) : Prop := a ∈ set.range f.to_map variables {f} lemma is_integer_add {a b} (ha : f.is_integer a) (hb : f.is_integer b) : f.is_integer (a + b) := begin rcases ha with ⟨a', ha⟩, rcases hb with ⟨b', hb⟩, use a' + b', rw [f.to_map.map_add, ha, hb] end lemma is_integer_mul {a b} (ha : f.is_integer a) (hb : f.is_integer b) : f.is_integer (a * b) := begin rcases ha with ⟨a', ha⟩, rcases hb with ⟨b', hb⟩, use a' * b', rw [f.to_map.map_mul, ha, hb] end lemma is_integer_smul {a : R} {b} (hb : f.is_integer b) : f.is_integer (f.to_map a * b) := begin rcases hb with ⟨b', hb⟩, use a * b', rw [←hb, f.to_map.map_mul] end variables (f) /-- Each element `a : S` has an `M`-multiple which is an integer. This version multiplies `a` on the right, matching the argument order in `localization_map.surj`. -/ lemma exists_integer_multiple' (a : S) : ∃ (b : M), is_integer f (a * f.to_map b) := let ⟨⟨num, denom⟩, h⟩ := f.surj a in ⟨denom, set.mem_range.mpr ⟨num, h.symm⟩⟩ /-- Each element `a : S` has an `M`-multiple which is an integer. This version multiplies `a` on the left, matching the argument order in the `has_scalar` instance. -/ lemma exists_integer_multiple (a : S) : ∃ (b : M), is_integer f (f.to_map b * a) := by { simp_rw mul_comm _ a, apply exists_integer_multiple' } /-- Given `z : S`, `f.to_localization_map.sec z` is defined to be a pair `(x, y) : R × M` such that `z * f y = f x` (so this lemma is true by definition). -/ lemma sec_spec {f : localization_map M S} (z : S) : z * f.to_map (f.to_localization_map.sec z).2 = f.to_map (f.to_localization_map.sec z).1 := classical.some_spec $ f.surj z /-- Given `z : S`, `f.to_localization_map.sec z` is defined to be a pair `(x, y) : R × M` such that `z * f y = f x`, so this lemma is just an application of `S`'s commutativity. -/ lemma sec_spec' {f : localization_map M S} (z : S) : f.to_map (f.to_localization_map.sec z).1 = f.to_map (f.to_localization_map.sec z).2 * z := by rw [mul_comm, sec_spec] open_locale big_operators /-- We can clear the denominators of a finite set of fractions. -/ lemma exist_integer_multiples_of_finset (s : finset S) : ∃ (b : M), ∀ a ∈ s, is_integer f (f.to_map b * a) := begin haveI := classical.prop_decidable, use ∏ a in s, (f.to_localization_map.sec a).2, intros a ha, use (∏ x in s.erase a, (f.to_localization_map.sec x).2) * (f.to_localization_map.sec a).1, rw [ring_hom.map_mul, sec_spec', ←mul_assoc, ←f.to_map.map_mul], congr' 2, refine trans _ ((submonoid.subtype M).map_prod _ _).symm, rw [mul_comm, ←finset.prod_insert (s.not_mem_erase a), finset.insert_erase ha], refl, end lemma map_right_cancel {x y} {c : M} (h : f.to_map (c * x) = f.to_map (c * y)) : f.to_map x = f.to_map y := f.to_localization_map.map_right_cancel h lemma map_left_cancel {x y} {c : M} (h : f.to_map (x * c) = f.to_map (y * c)) : f.to_map x = f.to_map y := f.to_localization_map.map_left_cancel h lemma eq_zero_of_fst_eq_zero {z x} {y : M} (h : z * f.to_map y = f.to_map x) (hx : x = 0) : z = 0 := by rw [hx, f.to_map.map_zero] at h; exact (f.map_units y).mul_left_eq_zero.1 h /-- Given a localization map `f : R →+* S`, the surjection sending `(x, y) : R × M` to `f x * (f y)⁻¹`. -/ noncomputable def mk' (f : localization_map M S) (x : R) (y : M) : S := f.to_localization_map.mk' x y @[simp] lemma mk'_sec (z : S) : f.mk' (f.to_localization_map.sec z).1 (f.to_localization_map.sec z).2 = z := f.to_localization_map.mk'_sec _ lemma mk'_mul (x₁ x₂ : R) (y₁ y₂ : M) : f.mk' (x₁ * x₂) (y₁ * y₂) = f.mk' x₁ y₁ * f.mk' x₂ y₂ := f.to_localization_map.mk'_mul _ _ _ _ lemma mk'_one (x) : f.mk' x (1 : M) = f.to_map x := f.to_localization_map.mk'_one _ lemma mk'_spec (x) (y : M) : f.mk' x y * f.to_map y = f.to_map x := f.to_localization_map.mk'_spec _ _ lemma mk'_spec' (x) (y : M) : f.to_map y * f.mk' x y = f.to_map x := f.to_localization_map.mk'_spec' _ _ theorem eq_mk'_iff_mul_eq {x} {y : M} {z} : z = f.mk' x y ↔ z * f.to_map y = f.to_map x := f.to_localization_map.eq_mk'_iff_mul_eq theorem mk'_eq_iff_eq_mul {x} {y : M} {z} : f.mk' x y = z ↔ f.to_map x = z * f.to_map y := f.to_localization_map.mk'_eq_iff_eq_mul lemma mk'_surjective (z : S) : ∃ x (y : M), f.mk' x y = z := let ⟨r, hr⟩ := f.surj z in ⟨r.1, r.2, (f.eq_mk'_iff_mul_eq.2 hr).symm⟩ lemma mk'_eq_iff_eq {x₁ x₂} {y₁ y₂ : M} : f.mk' x₁ y₁ = f.mk' x₂ y₂ ↔ f.to_map (x₁ * y₂) = f.to_map (x₂ * y₁) := f.to_localization_map.mk'_eq_iff_eq protected lemma eq {a₁ b₁} {a₂ b₂ : M} : f.mk' a₁ a₂ = f.mk' b₁ b₂ ↔ ∃ c : M, a₁ * b₂ * c = b₁ * a₂ * c := f.to_localization_map.eq lemma eq_iff_eq (g : localization_map M P) {x y} : f.to_map x = f.to_map y ↔ g.to_map x = g.to_map y := f.to_localization_map.eq_iff_eq g.to_localization_map lemma mk'_eq_iff_mk'_eq (g : localization_map M P) {x₁ x₂} {y₁ y₂ : M} : f.mk' x₁ y₁ = f.mk' x₂ y₂ ↔ g.mk' x₁ y₁ = g.mk' x₂ y₂ := f.to_localization_map.mk'_eq_iff_mk'_eq g.to_localization_map lemma mk'_eq_of_eq {a₁ b₁ : R} {a₂ b₂ : M} (H : b₁ * a₂ = a₁ * b₂) : f.mk' a₁ a₂ = f.mk' b₁ b₂ := f.to_localization_map.mk'_eq_of_eq H @[simp] lemma mk'_self {x : R} (hx : x ∈ M) : f.mk' x ⟨x, hx⟩ = 1 := f.to_localization_map.mk'_self' _ hx @[simp] lemma mk'_self' {x : M} : f.mk' x x = 1 := f.to_localization_map.mk'_self _ lemma mk'_self'' {x : M} : f.mk' x.1 x = 1 := f.mk'_self' lemma mul_mk'_eq_mk'_of_mul (x y : R) (z : M) : f.to_map x * f.mk' y z = f.mk' (x * y) z := f.to_localization_map.mul_mk'_eq_mk'_of_mul _ _ _ lemma mk'_eq_mul_mk'_one (x : R) (y : M) : f.mk' x y = f.to_map x * f.mk' 1 y := (f.to_localization_map.mul_mk'_one_eq_mk' _ _).symm @[simp] lemma mk'_mul_cancel_left (x : R) (y : M) : f.mk' (y * x) y = f.to_map x := f.to_localization_map.mk'_mul_cancel_left _ _ lemma mk'_mul_cancel_right (x : R) (y : M) : f.mk' (x * y) y = f.to_map x := f.to_localization_map.mk'_mul_cancel_right _ _ @[simp] lemma mk'_mul_mk'_eq_one (x y : M) : f.mk' x y * f.mk' y x = 1 := by rw [←f.mk'_mul, mul_comm]; exact f.mk'_self _ lemma mk'_mul_mk'_eq_one' (x : R) (y : M) (h : x ∈ M) : f.mk' x y * f.mk' y ⟨x, h⟩ = 1 := f.mk'_mul_mk'_eq_one ⟨x, h⟩ _ lemma is_unit_comp (j : S →+* P) (y : M) : is_unit (j.comp f.to_map y) := f.to_localization_map.is_unit_comp j.to_monoid_hom _ /-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_ring`s `g : R →+* P` such that `g(M) ⊆ units P`, `f x = f y → g x = g y` for all `x y : R`. -/ lemma eq_of_eq {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) {x y} (h : f.to_map x = f.to_map y) : g x = g y := @submonoid.localization_map.eq_of_eq _ _ _ _ _ _ _ f.to_localization_map g.to_monoid_hom hg _ _ h lemma mk'_add (x₁ x₂ : R) (y₁ y₂ : M) : f.mk' (x₁ * y₂ + x₂ * y₁) (y₁ * y₂) = f.mk' x₁ y₁ + f.mk' x₂ y₂ := f.mk'_eq_iff_eq_mul.2 $ eq.symm begin rw [mul_comm (_ + _), mul_add, mul_mk'_eq_mk'_of_mul, ←eq_sub_iff_add_eq, mk'_eq_iff_eq_mul, mul_comm _ (f.to_map _), mul_sub, eq_sub_iff_add_eq, ←eq_sub_iff_add_eq', ←mul_assoc, ←f.to_map.map_mul, mul_mk'_eq_mk'_of_mul, mk'_eq_iff_eq_mul], simp only [f.to_map.map_add, submonoid.coe_mul, f.to_map.map_mul], ring_exp, end /-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_ring`s `g : R →+* P` such that `g y` is invertible for all `y : M`, the homomorphism induced from `S` to `P` sending `z : S` to `g x * (g y)⁻¹`, where `(x, y) : R × M` are such that `z = f x * (f y)⁻¹`. -/ noncomputable def lift {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) : S →+* P := ring_hom.mk' (@submonoid.localization_map.lift _ _ _ _ _ _ _ f.to_localization_map g.to_monoid_hom hg) $ begin intros x y, rw [f.to_localization_map.lift_spec, mul_comm, add_mul, ←sub_eq_iff_eq_add, eq_comm, f.to_localization_map.lift_spec_mul, mul_comm _ (_ - _), sub_mul, eq_sub_iff_add_eq', ←eq_sub_iff_add_eq, mul_assoc, f.to_localization_map.lift_spec_mul], show g _ * (g _ * g _) = g _ * (g _ * g _ - g _ * g _), repeat {rw ←g.map_mul}, rw [←g.map_sub, ←g.map_mul], apply f.eq_of_eq hg, erw [f.to_map.map_mul, sec_spec', mul_sub, f.to_map.map_sub], simp only [f.to_map.map_mul, sec_spec'], ring_exp, end variables {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) /-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_ring`s `g : R →* P` such that `g y` is invertible for all `y : M`, the homomorphism induced from `S` to `P` maps `f x * (f y)⁻¹` to `g x * (g y)⁻¹` for all `x : R, y ∈ M`. -/ lemma lift_mk' (x y) : f.lift hg (f.mk' x y) = g x * ↑(is_unit.lift_right (g.to_monoid_hom.mrestrict M) hg y)⁻¹ := f.to_localization_map.lift_mk' _ _ _ lemma lift_mk'_spec (x v) (y : M) : f.lift hg (f.mk' x y) = v ↔ g x = g y * v := f.to_localization_map.lift_mk'_spec _ _ _ _ @[simp] lemma lift_eq (x : R) : f.lift hg (f.to_map x) = g x := f.to_localization_map.lift_eq _ _ lemma lift_eq_iff {x y : R × M} : f.lift hg (f.mk' x.1 x.2) = f.lift hg (f.mk' y.1 y.2) ↔ g (x.1 * y.2) = g (y.1 * x.2) := f.to_localization_map.lift_eq_iff _ @[simp] lemma lift_comp : (f.lift hg).comp f.to_map = g := ring_hom.ext $ monoid_hom.ext_iff.1 $ f.to_localization_map.lift_comp _ @[simp] lemma lift_of_comp (j : S →+* P) : f.lift (f.is_unit_comp j) = j := ring_hom.ext $ monoid_hom.ext_iff.1 $ f.to_localization_map.lift_of_comp j.to_monoid_hom lemma epic_of_localization_map {j k : S →+* P} (h : ∀ a, j.comp f.to_map a = k.comp f.to_map a) : j = k := ring_hom.ext $ monoid_hom.ext_iff.1 $ @submonoid.localization_map.epic_of_localization_map _ _ _ _ _ _ _ f.to_localization_map j.to_monoid_hom k.to_monoid_hom h lemma lift_unique {j : S →+* P} (hj : ∀ x, j (f.to_map x) = g x) : f.lift hg = j := ring_hom.ext $ monoid_hom.ext_iff.1 $ @submonoid.localization_map.lift_unique _ _ _ _ _ _ _ f.to_localization_map g.to_monoid_hom hg j.to_monoid_hom hj @[simp] lemma lift_id (x) : f.lift f.map_units x = x := f.to_localization_map.lift_id _ /-- Given two localization maps `f : R →+* S, k : R →+* P` for a submonoid `M ⊆ R`, the hom from `P` to `S` induced by `f` is left inverse to the hom from `S` to `P` induced by `k`. -/ @[simp] lemma lift_left_inverse {k : localization_map M S} (z : S) : k.lift f.map_units (f.lift k.map_units z) = z := f.to_localization_map.lift_left_inverse _ lemma lift_surjective_iff : surjective (f.lift hg) ↔ ∀ v : P, ∃ x : R × M, v * g x.2 = g x.1 := f.to_localization_map.lift_surjective_iff hg lemma lift_injective_iff : injective (f.lift hg) ↔ ∀ x y, f.to_map x = f.to_map y ↔ g x = g y := f.to_localization_map.lift_injective_iff hg variables {T : submonoid P} (hy : ∀ y : M, g y ∈ T) {Q : Type*} [comm_ring Q] (k : localization_map T Q) /-- Given a `comm_ring` homomorphism `g : R →+* P` where for submonoids `M ⊆ R, T ⊆ P` we have `g(M) ⊆ T`, the induced ring homomorphism from the localization of `R` at `M` to the localization of `P` at `T`: if `f : R →+* S` and `k : P →+* Q` are localization maps for `M` and `T` respectively, we send `z : S` to `k (g x) * (k (g y))⁻¹`, where `(x, y) : R × M` are such that `z = f x * (f y)⁻¹`. -/ noncomputable def map : S →+* Q := @lift _ _ _ _ _ _ _ f (k.to_map.comp g) $ λ y, k.map_units ⟨g y, hy y⟩ variables {k} lemma map_eq (x) : f.map hy k (f.to_map x) = k.to_map (g x) := f.lift_eq (λ y, k.map_units ⟨g y, hy y⟩) x @[simp] lemma map_comp : (f.map hy k).comp f.to_map = k.to_map.comp g := f.lift_comp $ λ y, k.map_units ⟨g y, hy y⟩ lemma map_mk' (x) (y : M) : f.map hy k (f.mk' x y) = k.mk' (g x) ⟨g y, hy y⟩ := @submonoid.localization_map.map_mk' _ _ _ _ _ _ _ f.to_localization_map g.to_monoid_hom _ hy _ _ k.to_localization_map _ _ @[simp] lemma map_id (z : S) : f.map (λ y, show ring_hom.id R y ∈ M, from y.2) f z = z := f.lift_id _ /-- If `comm_ring` homs `g : R →+* P, l : P →+* A` induce maps of localizations, the composition of the induced maps equals the map of localizations induced by `l ∘ g`. -/ lemma map_comp_map {A : Type*} [comm_ring A] {U : submonoid A} {W} [comm_ring W] (j : localization_map U W) {l : P →+* A} (hl : ∀ w : T, l w ∈ U) : (k.map hl j).comp (f.map hy k) = f.map (λ x, show l.comp g x ∈ U, from hl ⟨g x, hy x⟩) j := ring_hom.ext $ monoid_hom.ext_iff.1 $ @submonoid.localization_map.map_comp_map _ _ _ _ _ _ _ f.to_localization_map g.to_monoid_hom _ hy _ _ k.to_localization_map _ _ _ _ _ j.to_localization_map l.to_monoid_hom hl /-- If `comm_ring` homs `g : R →+* P, l : P →+* A` induce maps of localizations, the composition of the induced maps equals the map of localizations induced by `l ∘ g`. -/ lemma map_map {A : Type*} [comm_ring A] {U : submonoid A} {W} [comm_ring W] (j : localization_map U W) {l : P →+* A} (hl : ∀ w : T, l w ∈ U) (x) : k.map hl j (f.map hy k x) = f.map (λ x, show l.comp g x ∈ U, from hl ⟨g x, hy x⟩) j x := by rw ←f.map_comp_map hy j hl; refl /-- Given localization maps `f : R →+* S, k : P →+* Q` for submonoids `M, T` respectively, an isomorphism `j : R ≃+* P` such that `j(M) = T` induces an isomorphism of localizations `S ≃+* Q`. -/ noncomputable def ring_equiv_of_ring_equiv (k : localization_map T Q) (h : R ≃+* P) (H : M.map h.to_monoid_hom = T) : S ≃+* Q := (f.to_localization_map.mul_equiv_of_mul_equiv k.to_localization_map H).to_ring_equiv $ (@lift _ _ _ _ _ _ _ f (k.to_map.comp h.to_ring_hom) (λ y, k.map_units ⟨(h y), H ▸ set.mem_image_of_mem h y.2⟩)).map_add @[simp] lemma ring_equiv_of_ring_equiv_eq_map_apply {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) (x) : f.ring_equiv_of_ring_equiv k j H x = f.map (λ y : M, show j.to_monoid_hom y ∈ T, from H ▸ set.mem_image_of_mem j y.2) k x := rfl lemma ring_equiv_of_ring_equiv_eq_map {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) : (f.ring_equiv_of_ring_equiv k j H).to_monoid_hom = f.map (λ y : M, show j.to_monoid_hom y ∈ T, from H ▸ set.mem_image_of_mem j y.2) k := rfl @[simp] lemma ring_equiv_of_ring_equiv_eq {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) (x) : f.ring_equiv_of_ring_equiv k j H (f.to_map x) = k.to_map (j x) := f.to_localization_map.mul_equiv_of_mul_equiv_eq H _ lemma ring_equiv_of_ring_equiv_mk' {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) (x y) : f.ring_equiv_of_ring_equiv k j H (f.mk' x y) = k.mk' (j x) ⟨j y, H ▸ set.mem_image_of_mem j y.2⟩ := f.to_localization_map.mul_equiv_of_mul_equiv_mk' H _ _ end localization_map namespace localization variables {M} instance : has_add (localization M) := ⟨λ z w, con.lift_on₂ z w (λ x y : R × M, mk ((x.2 : R) * y.1 + y.2 * x.1) (x.2 * y.2)) $ λ r1 r2 r3 r4 h1 h2, (con.eq _).2 begin rw r_eq_r' at h1 h2 ⊢, cases h1 with t₅ ht₅, cases h2 with t₆ ht₆, use t₆ * t₅, calc ((r1.2 : R) * r2.1 + r2.2 * r1.1) * (r3.2 * r4.2) * (t₆ * t₅) = (r2.1 * r4.2 * t₆) * (r1.2 * r3.2 * t₅) + (r1.1 * r3.2 * t₅) * (r2.2 * r4.2 * t₆) : by ring ... = (r3.2 * r4.1 + r4.2 * r3.1) * (r1.2 * r2.2) * (t₆ * t₅) : by rw [ht₆, ht₅]; ring end⟩ instance : has_neg (localization M) := ⟨λ z, con.lift_on z (λ x : R × M, mk (-x.1) x.2) $ λ r1 r2 h, (con.eq _).2 begin rw r_eq_r' at h ⊢, cases h with t ht, use t, rw [neg_mul_eq_neg_mul_symm, neg_mul_eq_neg_mul_symm, ht], ring, end⟩ instance : has_zero (localization M) := ⟨mk 0 1⟩ private meta def tac := `[{ intros, refine quotient.sound' (r_of_eq _), simp only [prod.snd_mul, prod.fst_mul, submonoid.coe_mul], ring }] instance : comm_ring (localization M) := { zero := 0, one := 1, add := (+), mul := (*), add_assoc := λ m n k, quotient.induction_on₃' m n k (by tac), zero_add := λ y, quotient.induction_on' y (by tac), add_zero := λ y, quotient.induction_on' y (by tac), neg := has_neg.neg, add_left_neg := λ y, quotient.induction_on' y (by tac), add_comm := λ y z, quotient.induction_on₂' z y (by tac), left_distrib := λ m n k, quotient.induction_on₃' m n k (by tac), right_distrib := λ m n k, quotient.induction_on₃' m n k (by tac), ..localization.comm_monoid M } variables (M) /-- Natural hom sending `x : R`, `R` a `comm_ring`, to the equivalence class of `(x, 1)` in the localization of `R` at a submonoid. -/ def of : localization_map M (localization M) := (localization.monoid_of M).to_ring_localization $ λ x y, (con.eq _).2 $ r_of_eq $ by simp [add_comm] variables {M} lemma monoid_of_eq_of (x) : (monoid_of M).to_map x = (of M).to_map x := rfl lemma mk_one_eq_of (x) : mk x 1 = (of M).to_map x := rfl lemma mk_eq_mk'_apply (x y) : mk x y = (of M).mk' x y := mk_eq_monoid_of_mk'_apply _ _ @[simp] lemma mk_eq_mk' : mk = (of M).mk' := mk_eq_monoid_of_mk' variables (f : localization_map M S) /-- Given a localization map `f : R →+* S` for a submonoid `M`, we get an isomorphism between the localization of `R` at `M` as a quotient type and `S`. -/ noncomputable def ring_equiv_of_quotient : localization M ≃+* S := (mul_equiv_of_quotient f.to_localization_map).to_ring_equiv $ ((of M).lift f.map_units).map_add variables {f} @[simp] lemma ring_equiv_of_quotient_apply (x) : ring_equiv_of_quotient f x = (of M).lift f.map_units x := rfl @[simp] lemma ring_equiv_of_quotient_mk' (x y) : ring_equiv_of_quotient f ((of M).mk' x y) = f.mk' x y := mul_equiv_of_quotient_mk' _ _ lemma ring_equiv_of_quotient_mk (x y) : ring_equiv_of_quotient f (mk x y) = f.mk' x y := mul_equiv_of_quotient_mk _ _ @[simp] lemma ring_equiv_of_quotient_of (x) : ring_equiv_of_quotient f ((of M).to_map x) = f.to_map x := mul_equiv_of_quotient_monoid_of _ @[simp] lemma ring_equiv_of_quotient_symm_mk' (x y) : (ring_equiv_of_quotient f).symm (f.mk' x y) = (of M).mk' x y := mul_equiv_of_quotient_symm_mk' _ _ lemma ring_equiv_of_quotient_symm_mk (x y) : (ring_equiv_of_quotient f).symm (f.mk' x y) = mk x y := mul_equiv_of_quotient_symm_mk _ _ @[simp] lemma ring_equiv_of_quotient_symm_of (x) : (ring_equiv_of_quotient f).symm (f.to_map x) = (of M).to_map x := mul_equiv_of_quotient_symm_monoid_of _ end localization variables {M} section at_prime variables (I : ideal R) [hp : I.is_prime] include hp namespace ideal /-- The complement of a prime ideal `I ⊆ R` is a submonoid of `R`. -/ def prime_compl : submonoid R := { carrier := (Iᶜ : set R), one_mem' := by convert I.ne_top_iff_one.1 hp.1; refl, mul_mem' := λ x y hnx hny hxy, or.cases_on (hp.2 hxy) hnx hny } end ideal namespace localization_map variables (S) /-- A localization map from `R` to `S` where the submonoid is the complement of a prime ideal of `R`. -/ @[reducible] def at_prime := localization_map I.prime_compl S end localization_map namespace localization /-- The localization of `R` at the complement of a prime ideal, as a quotient type. -/ @[reducible] def at_prime := localization I.prime_compl end localization namespace localization_map variables {I} /-- When `f` is a localization map from `R` at the complement of a prime ideal `I`, we use a copy of the localization map `f`'s codomain `S` carrying the data of `f` so that the `local_ring` instance on `S` can 'know' the map needed to induce the instance. -/ instance at_prime.local_ring (f : at_prime S I) : local_ring f.codomain := local_of_nonunits_ideal (λ hze, begin rw [←f.to_map.map_one, ←f.to_map.map_zero] at hze, obtain ⟨t, ht⟩ := f.eq_iff_exists.1 hze, exact ((show (t : R) ∉ I, from t.2) (have htz : (t : R) = 0, by simpa using ht.symm, htz.symm ▸ I.zero_mem)) end) (begin intros x y hx hy hu, cases is_unit_iff_exists_inv.1 hu with z hxyz, have : ∀ {r s}, f.mk' r s ∈ nonunits S → r ∈ I, from λ r s, (@not_imp_comm _ _ (classical.dec _) (classical.dec _)).1 (λ nr, is_unit_iff_exists_inv.2 ⟨f.mk' s ⟨r, nr⟩, f.mk'_mul_mk'_eq_one' _ _ nr⟩), rcases f.mk'_surjective x with ⟨rx, sx, hrx⟩, rcases f.mk'_surjective y with ⟨ry, sy, hry⟩, rcases f.mk'_surjective z with ⟨rz, sz, hrz⟩, rw [←hrx, ←hry, ←hrz, ←f.mk'_add, ←f.mk'_mul, ←f.mk'_self I.prime_compl.one_mem] at hxyz, rw ←hrx at hx, rw ←hry at hy, cases f.eq.1 hxyz with t ht, simp only [mul_one, one_mul, submonoid.coe_mul, subtype.coe_mk] at ht, rw [←sub_eq_zero, ←sub_mul] at ht, have hr := (hp.mem_or_mem_of_mul_eq_zero ht).resolve_right t.2, have := I.neg_mem_iff.1 ((ideal.add_mem_iff_right _ _).1 hr), { exact not_or (mt hp.mem_or_mem (not_or sx.2 sy.2)) sz.2 (hp.mem_or_mem this)}, { exact I.mul_mem_right (I.add_mem (I.mul_mem_right (this hx)) (I.mul_mem_right (this hy)))} end) end localization_map namespace localization /-- The localization of `R` at the complement of a prime ideal is a local ring. -/ instance at_prime.local_ring : local_ring (localization I.prime_compl) := localization_map.at_prime.local_ring (of I.prime_compl) end localization end at_prime namespace localization_map variables (f : localization_map M S) section ideals theorem map_comap (J : ideal S) : ideal.map f.to_map (ideal.comap f.to_map J) = J := le_antisymm (ideal.map_le_iff_le_comap.2 (le_refl _)) $ λ x hJ, begin obtain ⟨r, s, hx⟩ := f.mk'_surjective x, rw ←hx at ⊢ hJ, exact ideal.mul_mem_right _ (ideal.mem_map_of_mem (show f.to_map r ∈ J, from f.mk'_spec r s ▸ @ideal.mul_mem_right _ _ J (f.mk' r s) (f.to_map s) hJ)), end /-- If `S` is the localization of `R` at a submonoid, the ordering of ideals of `S` is embedded in the ordering of ideals of `R`. -/ def le_order_embedding : ((≤) : ideal S → ideal S → Prop) ≼o ((≤) : ideal R → ideal R → Prop) := { to_fun := λ J, ideal.comap f.to_map J, inj' := function.left_inverse.injective f.map_comap, ord' := λ J₁ J₂, ⟨ideal.comap_mono, λ hJ, f.map_comap J₁ ▸ f.map_comap J₂ ▸ ideal.map_mono hJ⟩ } end ideals /-! ### `algebra` section Defines the `R`-algebra instance on a copy of `S` carrying the data of the localization map `f` needed to induce the `R`-algebra structure. -/ /-- We use a copy of the localization map `f`'s codomain `S` carrying the data of `f` so that the `R`-algebra instance on `S` can 'know' the map needed to induce the `R`-algebra structure. -/ instance : algebra R f.codomain := f.to_map.to_algebra end localization_map namespace localization instance : algebra R (localization M) := localization_map.algebra (of M) end localization namespace localization_map variables (f : localization_map M S) @[simp] lemma of_id (a : R) : (algebra.of_id R f.codomain) a = f.to_map a := rfl @[simp] lemma algebra_map_eq : algebra_map R f.codomain = f.to_map := rfl variables (f) /-- Localization map `f` from `R` to `S` as an `R`-linear map. -/ def lin_coe : R →ₗ[R] f.codomain := { to_fun := f.to_map, map_add' := f.to_map.map_add, map_smul' := f.to_map.map_mul } variables {f} instance coe_submodules : has_coe (ideal R) (submodule R f.codomain) := ⟨λ I, submodule.map f.lin_coe I⟩ lemma mem_coe (I : ideal R) {x : S} : x ∈ (I : submodule R f.codomain) ↔ ∃ y : R, y ∈ I ∧ f.to_map y = x := iff.rfl @[simp] lemma lin_coe_apply {x} : f.lin_coe x = f.to_map x := rfl variables {g : R →+* P} variables {T : submonoid P} (hy : ∀ y : M, g y ∈ T) {Q : Type*} [comm_ring Q] (k : localization_map T Q) lemma map_smul (x : f.codomain) (z : R) : f.map hy k (z • x : f.codomain) = @has_scalar.smul P k.codomain _ (g z) (f.map hy k x) := show f.map hy k (f.to_map z * x) = k.to_map (g z) * f.map hy k x, by rw [ring_hom.map_mul, map_eq] section integer_normalization open finsupp polynomial open_locale classical /-- `coeff_integer_normalization p` gives the coefficients of the polynomial `integer_normalization p` -/ noncomputable def coeff_integer_normalization (p : polynomial f.codomain) (i : ℕ) : R := if hi : i ∈ p.support then classical.some (classical.some_spec (f.exist_integer_multiples_of_finset (p.support.image p.coeff)) (p.coeff i) (finset.mem_image.mpr ⟨i, hi, rfl⟩)) else 0 lemma coeff_integer_normalization_mem_support (p : polynomial f.codomain) (i : ℕ) (h : coeff_integer_normalization p i ≠ 0) : i ∈ p.support := begin contrapose h, rw [ne.def, not_not, coeff_integer_normalization, dif_neg h] end /-- `integer_normalization g` normalizes `g` to have integer coefficients by clearing the denominators -/ noncomputable def integer_normalization : polynomial f.codomain → polynomial R := λ p, on_finset p.support (coeff_integer_normalization p) (coeff_integer_normalization_mem_support p) @[simp] lemma integer_normalization_coeff (p : polynomial f.codomain) (i : ℕ) : (integer_normalization p).coeff i = coeff_integer_normalization p i := rfl lemma integer_normalization_spec (p : polynomial f.codomain) : ∃ (b : M), ∀ i, f.to_map ((integer_normalization p).coeff i) = f.to_map b * p.coeff i := begin use classical.some (f.exist_integer_multiples_of_finset (p.support.image p.coeff)), intro i, rw [integer_normalization_coeff, coeff_integer_normalization], split_ifs with hi, { exact classical.some_spec (classical.some_spec (f.exist_integer_multiples_of_finset (p.support.image p.coeff)) (p.coeff i) (finset.mem_image.mpr ⟨i, hi, rfl⟩)) }, { convert (_root_.mul_zero (f.to_map _)).symm, { exact f.to_ring_hom.map_zero }, { exact finsupp.not_mem_support_iff.mp hi } } end lemma integer_normalization_map_to_map (p : polynomial f.codomain) : ∃ (b : M), (integer_normalization p).map f.to_map = f.to_map b • p := let ⟨b, hb⟩ := integer_normalization_spec p in ⟨b, polynomial.ext (λ i, by { rw coeff_map, exact hb i })⟩ variables {R' : Type*} [comm_ring R'] lemma integer_normalization_eval₂_eq_zero (g : f.codomain →+* R') (p : polynomial f.codomain) {x : R'} (hx : eval₂ g x p = 0) : eval₂ (g.comp f.to_map) x (integer_normalization p) = 0 := let ⟨b, hb⟩ := integer_normalization_map_to_map p in trans (eval₂_map f.to_map g x).symm (by rw [hb, eval₂_smul, hx, smul_zero]) lemma integer_normalization_aeval_eq_zero [algebra R R'] [algebra f.codomain R'] [is_algebra_tower R f.codomain R'] (p : polynomial f.codomain) {x : R'} (hx : aeval x p = 0) : aeval x (integer_normalization p) = 0 := by rw [aeval_def, is_algebra_tower.algebra_map_eq R f.codomain R', algebra_map_eq, integer_normalization_eval₂_eq_zero _ _ hx] end integer_normalization end localization_map variables (R) /-- The submonoid of non-zero-divisors of a `comm_ring` `R`. -/ def non_zero_divisors : submonoid R := { carrier := {x | ∀ z, z * x = 0 → z = 0}, one_mem' := λ z hz, by rwa mul_one at hz, mul_mem' := λ x₁ x₂ hx₁ hx₂ z hz, have z * x₁ * x₂ = 0, by rwa mul_assoc, hx₁ z $ hx₂ (z * x₁) this } variables {R} lemma mul_mem_non_zero_divisors {a b : R} : a * b ∈ non_zero_divisors R ↔ a ∈ non_zero_divisors R ∧ b ∈ non_zero_divisors R := begin split, { intro h, split; intros x h'; apply h, { rw [←mul_assoc, h', zero_mul] }, { rw [mul_comm a b, ←mul_assoc, h', zero_mul] } }, { rintros ⟨ha, hb⟩ x hx, apply ha, apply hb, rw [mul_assoc, hx] }, end variables (R) {A : Type*} [integral_domain A] lemma eq_zero_of_ne_zero_of_mul_eq_zero {x y : A} (hnx : x ≠ 0) (hxy : y * x = 0) : y = 0 := or.resolve_right (eq_zero_or_eq_zero_of_mul_eq_zero hxy) hnx lemma mem_non_zero_divisors_iff_ne_zero {x : A} : x ∈ non_zero_divisors A ↔ x ≠ 0 := ⟨λ hm hz, zero_ne_one (hm 1 $ by rw [hz, one_mul]).symm, λ hnx z, eq_zero_of_ne_zero_of_mul_eq_zero hnx⟩ lemma map_ne_zero_of_mem_non_zero_divisors {B : Type*} [ring B] {g : A →+* B} (hg : injective g) {x : non_zero_divisors A} : g x ≠ 0 := λ h0, mem_non_zero_divisors_iff_ne_zero.1 x.2 $ g.injective_iff.1 hg x h0 lemma map_mem_non_zero_divisors {B : Type*} [integral_domain B] {g : A →+* B} (hg : injective g) {x : non_zero_divisors A} : g x ∈ non_zero_divisors B := λ z hz, eq_zero_of_ne_zero_of_mul_eq_zero (map_ne_zero_of_mem_non_zero_divisors hg) hz variables (K : Type*) /-- Localization map from an integral domain `R` to its field of fractions. -/ @[reducible] def fraction_map [comm_ring K] := localization_map (non_zero_divisors R) K namespace fraction_map open localization_map variables {R K} lemma to_map_eq_zero_iff [comm_ring K] (φ : fraction_map R K) {x : R} : x = 0 ↔ φ.to_map x = 0 := begin rw ← φ.to_map.map_zero, split; intro h, { rw h }, { cases φ.eq_iff_exists.mp h with c hc, rw zero_mul at hc, exact c.2 x hc } end protected theorem injective [comm_ring K] (φ : fraction_map R K) : injective φ.to_map := φ.to_map.injective_iff.2 (λ _ h, φ.to_map_eq_zero_iff.mpr h) protected lemma map_ne_zero_of_mem_non_zero_divisors [comm_ring K] (φ : fraction_map A K) (x : non_zero_divisors A) : φ.to_map x ≠ 0 := map_ne_zero_of_mem_non_zero_divisors φ.injective local attribute [instance] classical.dec_eq /-- A `comm_ring` `K` which is the localization of an integral domain `R` at `R - {0}` is an integral domain. -/ def to_integral_domain [comm_ring K] (φ : fraction_map A K) : integral_domain K := { eq_zero_or_eq_zero_of_mul_eq_zero := begin intros z w h, cases φ.surj z with x hx, cases φ.surj w with y hy, have : z * w * φ.to_map y.2 * φ.to_map x.2 = φ.to_map x.1 * φ.to_map y.1, by rw [mul_assoc z, hy, ←hx]; ac_refl, erw h at this, rw [zero_mul, zero_mul, ←φ.to_map.map_mul] at this, cases eq_zero_or_eq_zero_of_mul_eq_zero (φ.to_map_eq_zero_iff.mpr this.symm) with H H, { exact or.inl (φ.eq_zero_of_fst_eq_zero hx H) }, { exact or.inr (φ.eq_zero_of_fst_eq_zero hy H) }, end, exists_pair_ne := ⟨φ.to_map 0, φ.to_map 1, λ h, zero_ne_one (φ.injective h)⟩, ..(infer_instance : comm_ring K) } /-- The inverse of an element in the field of fractions of an integral domain. -/ protected noncomputable def inv [comm_ring K] (φ : fraction_map A K) (z : K) : K := if h : z = 0 then 0 else φ.mk' (φ.to_localization_map.sec z).2 ⟨(φ.to_localization_map.sec z).1, mem_non_zero_divisors_iff_ne_zero.2 $ λ h0, h $ φ.eq_zero_of_fst_eq_zero (sec_spec z) h0⟩ protected lemma mul_inv_cancel [comm_ring K] (φ : fraction_map A K) (x : K) (hx : x ≠ 0) : x * φ.inv x = 1 := show x * dite _ _ _ = 1, by rw [dif_neg hx, ←is_unit.mul_left_inj (φ.map_units ⟨(φ.to_localization_map.sec x).1, mem_non_zero_divisors_iff_ne_zero.2 $ λ h0, hx $ φ.eq_zero_of_fst_eq_zero (sec_spec x) h0⟩), one_mul, mul_assoc, mk'_spec, ←eq_mk'_iff_mul_eq]; exact (φ.mk'_sec x).symm /-- A `comm_ring` `K` which is the localization of an integral domain `R` at `R - {0}` is a field. -/ noncomputable def to_field [comm_ring K] (φ : fraction_map A K) : field K := { inv := φ.inv, mul_inv_cancel := φ.mul_inv_cancel, inv_zero := dif_pos rfl, ..φ.to_integral_domain } variables {B : Type*} [integral_domain B] [field K] {L : Type*} [field L] (f : fraction_map A K) {g : A →+* L} lemma mk'_eq_div {r s} : f.mk' r s = f.to_map r / f.to_map s := f.mk'_eq_iff_eq_mul.2 $ (div_mul_cancel _ (f.map_ne_zero_of_mem_non_zero_divisors _)).symm lemma is_unit_map_of_injective (hg : injective g) (y : non_zero_divisors A) : is_unit (g y) := is_unit.mk0 (g y) $ map_ne_zero_of_mem_non_zero_divisors hg /-- Given an integral domain `A`, a localization map to its fields of fractions `f : A →+* K`, and an injective ring hom `g : A →+* L` where `L` is a field, we get a field hom sending `z : K` to `g x * (g y)⁻¹`, where `(x, y) : A × (non_zero_divisors A)` are such that `z = f x * (f y)⁻¹`. -/ noncomputable def lift (hg : injective g) : K →+* L := f.lift $ is_unit_map_of_injective hg /-- Given an integral domain `A`, a localization map to its fields of fractions `f : A →+* K`, and an injective ring hom `g : A →+* L` where `L` is a field, field hom induced from `K` to `L` maps `f x / f y` to `g x / g y` for all `x : A, y ∈ non_zero_divisors A`. -/ @[simp] lemma lift_mk' (hg : injective g) (x y) : f.lift hg (f.mk' x y) = g x / g y := begin erw f.lift_mk' (is_unit_map_of_injective hg), erw submonoid.localization_map.mul_inv_left (λ y : non_zero_divisors A, show is_unit (g.to_monoid_hom y), from is_unit_map_of_injective hg y), exact (mul_div_cancel' _ (map_ne_zero_of_mem_non_zero_divisors hg)).symm, end /-- Given integral domains `A, B` and localization maps to their fields of fractions `f : A →+* K, g : B →+* L` and an injective ring hom `j : A →+* B`, we get a field hom sending `z : K` to `g (j x) * (g (j y))⁻¹`, where `(x, y) : A × (non_zero_divisors A)` are such that `z = f x * (f y)⁻¹`. -/ noncomputable def map (g : fraction_map B L) {j : A →+* B} (hj : injective j) : K →+* L := f.map (λ y, mem_non_zero_divisors_iff_ne_zero.2 $ map_ne_zero_of_mem_non_zero_divisors hj) g /-- Given integral domains `A, B` and localization maps to their fields of fractions `f : A →+* K, g : B →+* L`, an isomorphism `j : A ≃+* B` induces an isomorphism of fields of fractions `K ≃+* L`. -/ noncomputable def field_equiv_of_ring_equiv (g : fraction_map B L) (h : A ≃+* B) : K ≃+* L := f.ring_equiv_of_ring_equiv g h begin ext b, show b ∈ h.to_equiv '' _ ↔ _, erw [h.to_equiv.image_eq_preimage, set.preimage, set.mem_set_of_eq, mem_non_zero_divisors_iff_ne_zero, mem_non_zero_divisors_iff_ne_zero], exact h.symm.map_ne_zero_iff end /-- The cast from `int` to `rat` as a `fraction_map`. -/ def int.fraction_map : fraction_map ℤ ℚ := { to_fun := coe, map_units' := begin rintro ⟨x, hx⟩, rw [submonoid.mem_carrier, mem_non_zero_divisors_iff_ne_zero] at hx, simpa only [is_unit_iff_ne_zero, int.cast_eq_zero, ne.def, subtype.coe_mk] using hx, end, surj' := begin rintro ⟨n, d, hd, h⟩, refine ⟨⟨n, ⟨d, _⟩⟩, rat.mul_denom_eq_num⟩, rwa [submonoid.mem_carrier, mem_non_zero_divisors_iff_ne_zero, int.coe_nat_ne_zero_iff_pos] end, eq_iff_exists' := begin intros x y, rw [int.cast_inj], refine ⟨by { rintro rfl, use 1 }, _⟩, rintro ⟨⟨c, hc⟩, h⟩, apply int.eq_of_mul_eq_mul_right _ h, rwa [submonoid.mem_carrier, mem_non_zero_divisors_iff_ne_zero] at hc, end, ..int.cast_ring_hom ℚ } lemma integer_normalization_eq_zero_iff {p : polynomial f.codomain} : integer_normalization p = 0 ↔ p = 0 := begin refine (polynomial.ext_iff.trans (polynomial.ext_iff.trans _).symm), obtain ⟨⟨b, nonzero⟩, hb⟩ := integer_normalization_spec p, split; intros h i, { apply f.to_map_eq_zero_iff.mpr, rw [hb i, h i], exact _root_.mul_zero _ }, { have hi := h i, rw [polynomial.coeff_zero, f.to_map_eq_zero_iff, hb i] at hi, apply or.resolve_left (eq_zero_or_eq_zero_of_mul_eq_zero hi), intro h, apply mem_non_zero_divisors_iff_ne_zero.mp nonzero, exact f.to_map_eq_zero_iff.mpr h } end /-- A field is algebraic over the ring `A` iff it is algebraic over the field of fractions of `A`. -/ lemma comap_is_algebraic_iff [algebra A L] [algebra f.codomain L] [is_algebra_tower A f.codomain L] : algebra.is_algebraic A L ↔ algebra.is_algebraic f.codomain L := begin split; intros h x; obtain ⟨p, hp, px⟩ := h x, { refine ⟨p.map f.to_map, λ h, hp (polynomial.ext (λ i, _)), _⟩, { have : f.to_map (p.coeff i) = 0 := trans (polynomial.coeff_map _ _).symm (by simp [h]), exact f.to_map_eq_zero_iff.mpr this }, { rwa [is_algebra_tower.aeval_apply _ f.codomain, algebra_map_eq] at px } }, { exact ⟨integer_normalization p, mt f.integer_normalization_eq_zero_iff.mp hp, integer_normalization_aeval_eq_zero p px⟩ }, end section num_denom variables [unique_factorization_domain A] (φ : fraction_map A K) lemma exists_reduced_fraction (x : φ.codomain) : ∃ (a : A) (b : non_zero_divisors A), (∀ {d}, d ∣ a → d ∣ b → is_unit d) ∧ φ.mk' a b = x := begin obtain ⟨⟨b, b_nonzero⟩, a, hab⟩ := φ.exists_integer_multiple x, obtain ⟨a', b', c', no_factor, rfl, rfl⟩ := unique_factorization_domain.exists_reduced_factors' a b (mem_non_zero_divisors_iff_ne_zero.mp b_nonzero), obtain ⟨c'_nonzero, b'_nonzero⟩ := mul_mem_non_zero_divisors.mp b_nonzero, refine ⟨a', ⟨b', b'_nonzero⟩, @no_factor, _⟩, apply mul_left_cancel' (φ.map_ne_zero_of_mem_non_zero_divisors ⟨c' * b', b_nonzero⟩), simp only [subtype.coe_mk, φ.to_map.map_mul] at *, erw [←hab, mul_assoc, φ.mk'_spec' a' ⟨b', b'_nonzero⟩], end /-- `f.num x` is the numerator of `x : f.codomain` as a reduced fraction. -/ noncomputable def num (x : φ.codomain) : A := classical.some (φ.exists_reduced_fraction x) /-- `f.num x` is the denominator of `x : f.codomain` as a reduced fraction. -/ noncomputable def denom (x : φ.codomain) : non_zero_divisors A := classical.some (classical.some_spec (φ.exists_reduced_fraction x)) lemma num_denom_reduced (x : φ.codomain) : ∀ {d}, d ∣ φ.num x → d ∣ φ.denom x → is_unit d := (classical.some_spec (classical.some_spec (φ.exists_reduced_fraction x))).1 @[simp] lemma mk'_num_denom (x : φ.codomain) : φ.mk' (φ.num x) (φ.denom x) = x := (classical.some_spec (classical.some_spec (φ.exists_reduced_fraction x))).2 lemma num_mul_denom_eq_num_iff_eq {x y : φ.codomain} : x * φ.to_map (φ.denom y) = φ.to_map (φ.num y) ↔ x = y := ⟨ λ h, by simpa only [mk'_num_denom] using φ.eq_mk'_iff_mul_eq.mpr h, λ h, φ.eq_mk'_iff_mul_eq.mp (by rw [h, mk'_num_denom]) ⟩ lemma num_mul_denom_eq_num_iff_eq' {x y : φ.codomain} : y * φ.to_map (φ.denom x) = φ.to_map (φ.num x) ↔ x = y := ⟨ λ h, by simpa only [eq_comm, mk'_num_denom] using φ.eq_mk'_iff_mul_eq.mpr h, λ h, φ.eq_mk'_iff_mul_eq.mp (by rw [h, mk'_num_denom]) ⟩ lemma num_mul_denom_eq_num_mul_denom_iff_eq {x y : φ.codomain} : φ.num y * φ.denom x = φ.num x * φ.denom y ↔ x = y := ⟨ λ h, by simpa only [mk'_num_denom] using φ.mk'_eq_of_eq h, λ h, by rw h ⟩ lemma eq_zero_of_num_eq_zero {x : φ.codomain} (h : φ.num x = 0) : x = 0 := φ.num_mul_denom_eq_num_iff_eq'.mp (by rw [zero_mul, h, ring_hom.map_zero]) lemma is_integer_of_is_unit_denom {x : φ.codomain} (h : is_unit (φ.denom x : A)) : φ.is_integer x := begin cases h with d hd, have d_ne_zero : φ.to_map (φ.denom x) ≠ 0 := φ.map_ne_zero_of_mem_non_zero_divisors (φ.denom x), use ↑d⁻¹ * φ.num x, refine trans _ (φ.mk'_num_denom x), rw [φ.to_map.map_mul, φ.to_map.map_units_inv, hd], apply mul_left_cancel' d_ne_zero, rw [←mul_assoc, mul_inv_cancel d_ne_zero, one_mul, φ.mk'_spec'] end lemma is_unit_denom_of_num_eq_zero {x : φ.codomain} (h : φ.num x = 0) : is_unit (φ.denom x : A) := φ.num_denom_reduced x (h.symm ▸ dvd_zero _) (dvd_refl _) end num_denom end fraction_map namespace integral_closure variables {L : Type*} [field K] [field L] {f : fraction_map A K} open algebra /-- If the field `L` is an algebraic extension of the integral domain `A`, the integral closure of `A` in `L` has fraction field `L`. -/ def fraction_map_of_algebraic [algebra A L] (alg : is_algebraic A L) (inj : ∀ x, algebra_map A L x = 0 → x = 0) : fraction_map (integral_closure A L) L := (algebra_map (integral_closure A L) L).to_localization_map (λ ⟨⟨y, integral⟩, nonzero⟩, have y ≠ 0 := λ h, mem_non_zero_divisors_iff_ne_zero.mp nonzero (subtype.ext_iff_val.mpr h), show is_unit y, from ⟨⟨y, y⁻¹, mul_inv_cancel this, inv_mul_cancel this⟩, rfl⟩) (λ z, let ⟨x, y, hy, hxy⟩ := exists_integral_multiple (alg z) inj in ⟨⟨x, ⟨y, mem_non_zero_divisors_iff_ne_zero.mpr hy⟩⟩, hxy⟩) (λ x y, ⟨ λ (h : x.1 = y.1), ⟨1, by simpa using subtype.ext_iff_val.mpr h⟩, λ ⟨c, hc⟩, congr_arg (algebra_map _ L) (mul_right_cancel' (mem_non_zero_divisors_iff_ne_zero.mp c.2) hc) ⟩) /-- If the field `L` is a finite extension of the fraction field of the integral domain `A`, the integral closure of `A` in `L` has fraction field `L`. -/ def fraction_map_of_finite_extension [algebra A L] [algebra f.codomain L] [is_algebra_tower A f.codomain L] [finite_dimensional f.codomain L] : fraction_map (integral_closure A L) L := fraction_map_of_algebraic (f.comap_is_algebraic_iff.mpr is_algebraic_of_finite) (λ x hx, f.to_map_eq_zero_iff.mpr ((algebra_map f.codomain L).map_eq_zero.mp $ (is_algebra_tower.algebra_map_apply _ _ _ _).symm.trans hx)) end integral_closure variables (A) /-- The fraction field of an integral domain as a quotient type. -/ @[reducible] def fraction_ring := localization (non_zero_divisors A) /-- Natural hom sending `x : A`, `A` an integral domain, to the equivalence class of `(x, 1)` in the field of fractions of `A`. -/ def of : fraction_map A (localization (non_zero_divisors A)) := localization.of (non_zero_divisors A) namespace fraction_ring variables {A} noncomputable instance : field (fraction_ring A) := (of A).to_field @[simp] lemma mk_eq_div {r s} : (localization.mk r s : fraction_ring A) = ((of A).to_map r / (of A).to_map s : fraction_ring A) := by erw [localization.mk_eq_mk', (of A).mk'_eq_div] /-- Given an integral domain `A` and a localization map to a field of fractions `f : A →+* K`, we get an isomorphism between the field of fractions of `A` as a quotient type and `K`. -/ noncomputable def field_equiv_of_quotient {K : Type*} [field K] (f : fraction_map A K) : fraction_ring A ≃+* K := localization.ring_equiv_of_quotient f end fraction_ring
75a56c3e787711de33a7ee6552865cfdf5b203e5
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/analysis/normed_space/multilinear.lean
9b82b9a39dd3a2d603d3a3bcd71a84f0a1d288aa
[]
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
66,806
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.analysis.normed_space.operator_norm import Mathlib.topology.algebra.multilinear import Mathlib.PostPort universes u v w₁ w₂ wG u_1 w namespace Mathlib /-! # Operator norm on the space of continuous multilinear maps When `f` is a continuous multilinear map in finitely many variables, we define its norm `∥f∥` as the smallest number such that `∥f m∥ ≤ ∥f∥ * ∏ i, ∥m i∥` for all `m`. We show that it is indeed a norm, and prove its basic properties. ## Main results Let `f` be a multilinear map in finitely many variables. * `exists_bound_of_continuous` asserts that, if `f` is continuous, then there exists `C > 0` with `∥f m∥ ≤ C * ∏ i, ∥m i∥` for all `m`. * `continuous_of_bound`, conversely, asserts that this bound implies continuity. * `mk_continuous` constructs the associated continuous multilinear map. Let `f` be a continuous multilinear map in finitely many variables. * `∥f∥` is its norm, i.e., the smallest number such that `∥f m∥ ≤ ∥f∥ * ∏ i, ∥m i∥` for all `m`. * `le_op_norm f m` asserts the fundamental inequality `∥f m∥ ≤ ∥f∥ * ∏ i, ∥m i∥`. * `norm_image_sub_le f m₁ m₂` gives a control of the difference `f m₁ - f m₂` in terms of `∥f∥` and `∥m₁ - m₂∥`. We also register isomorphisms corresponding to currying or uncurrying variables, transforming a continuous multilinear function `f` in `n+1` variables into a continuous linear function taking values in continuous multilinear functions in `n` variables, and also into a continuous multilinear function in `n` variables taking values in continuous linear functions. These operations are called `f.curry_left` and `f.curry_right` respectively (with inverses `f.uncurry_left` and `f.uncurry_right`). They induce continuous linear equivalences between spaces of continuous multilinear functions in `n+1` variables and spaces of continuous linear functions into continuous multilinear functions in `n` variables (resp. continuous multilinear functions in `n` variables taking values in continuous linear functions), called respectively `continuous_multilinear_curry_left_equiv` and `continuous_multilinear_curry_right_equiv`. ## Implementation notes We mostly follow the API (and the proofs) of `operator_norm.lean`, with the additional complexity that we should deal with multilinear maps in several variables. The currying/uncurrying constructions are based on those in `multilinear.lean`. From the mathematical point of view, all the results follow from the results on operator norm in one variable, by applying them to one variable after the other through currying. However, this is only well defined when there is an order on the variables (for instance on `fin n`) although the final result is independent of the order. While everything could be done following this approach, it turns out that direct proofs are easier and more efficient. -/ /-! ### Continuity properties of multilinear maps We relate continuity of multilinear maps to the inequality `∥f m∥ ≤ C * ∏ i, ∥m i∥`, in both directions. Along the way, we prove useful bounds on the difference `∥f m₁ - f m₂∥`. -/ namespace multilinear_map /-- If a multilinear map in finitely many variables on normed spaces satisfies the inequality `∥f m∥ ≤ C * ∏ i, ∥m i∥` on a shell `ε i / ∥c i∥ < ∥m i∥ < ε i` for some positive numbers `ε i` and elements `c i : 𝕜`, `1 < ∥c i∥`, then it satisfies this inequality for all `m`. -/ theorem bound_of_shell {𝕜 : Type u} {ι : Type v} {E₁ : ι → Type w₁} {E₂ : Type w₂} [DecidableEq ι] [fintype ι] [nondiscrete_normed_field 𝕜] [(i : ι) → normed_group (E₁ i)] [normed_group E₂] [(i : ι) → normed_space 𝕜 (E₁ i)] [normed_space 𝕜 E₂] (f : multilinear_map 𝕜 E₁ E₂) {ε : ι → ℝ} {C : ℝ} (hε : ∀ (i : ι), 0 < ε i) {c : ι → 𝕜} (hc : ∀ (i : ι), 1 < norm (c i)) (hf : ∀ (m : (i : ι) → E₁ i), (∀ (i : ι), ε i / norm (c i) ≤ norm (m i)) → (∀ (i : ι), norm (m i) < ε i) → norm (coe_fn f m) ≤ C * finset.prod finset.univ fun (i : ι) => norm (m i)) (m : (i : ι) → E₁ i) : norm (coe_fn f m) ≤ C * finset.prod finset.univ fun (i : ι) => norm (m i) := sorry /-- If a multilinear map in finitely many variables on normed spaces is continuous, then it satisfies the inequality `∥f m∥ ≤ C * ∏ i, ∥m i∥`, for some `C` which can be chosen to be positive. -/ theorem exists_bound_of_continuous {𝕜 : Type u} {ι : Type v} {E₁ : ι → Type w₁} {E₂ : Type w₂} [DecidableEq ι] [fintype ι] [nondiscrete_normed_field 𝕜] [(i : ι) → normed_group (E₁ i)] [normed_group E₂] [(i : ι) → normed_space 𝕜 (E₁ i)] [normed_space 𝕜 E₂] (f : multilinear_map 𝕜 E₁ E₂) (hf : continuous ⇑f) : ∃ (C : ℝ), 0 < C ∧ ∀ (m : (i : ι) → E₁ i), norm (coe_fn f m) ≤ C * finset.prod finset.univ fun (i : ι) => norm (m i) := sorry /-- If `f` satisfies a boundedness property around `0`, one can deduce a bound on `f m₁ - f m₂` using the multilinearity. Here, we give a precise but hard to use version. See `norm_image_sub_le_of_bound` for a less precise but more usable version. The bound reads `∥f m - f m'∥ ≤ C * ∥m 1 - m' 1∥ * max ∥m 2∥ ∥m' 2∥ * max ∥m 3∥ ∥m' 3∥ * ... * max ∥m n∥ ∥m' n∥ + ...`, where the other terms in the sum are the same products where `1` is replaced by any `i`. -/ theorem norm_image_sub_le_of_bound' {𝕜 : Type u} {ι : Type v} {E₁ : ι → Type w₁} {E₂ : Type w₂} [DecidableEq ι] [fintype ι] [nondiscrete_normed_field 𝕜] [(i : ι) → normed_group (E₁ i)] [normed_group E₂] [(i : ι) → normed_space 𝕜 (E₁ i)] [normed_space 𝕜 E₂] (f : multilinear_map 𝕜 E₁ E₂) {C : ℝ} (hC : 0 ≤ C) (H : ∀ (m : (i : ι) → E₁ i), norm (coe_fn f m) ≤ C * finset.prod finset.univ fun (i : ι) => norm (m i)) (m₁ : (i : ι) → E₁ i) (m₂ : (i : ι) → E₁ i) : norm (coe_fn f m₁ - coe_fn f m₂) ≤ C * finset.sum finset.univ fun (i : ι) => finset.prod finset.univ fun (j : ι) => ite (j = i) (norm (m₁ i - m₂ i)) (max (norm (m₁ j)) (norm (m₂ j))) := sorry /-- If `f` satisfies a boundedness property around `0`, one can deduce a bound on `f m₁ - f m₂` using the multilinearity. Here, we give a usable but not very precise version. See `norm_image_sub_le_of_bound'` for a more precise but less usable version. The bound is `∥f m - f m'∥ ≤ C * card ι * ∥m - m'∥ * (max ∥m∥ ∥m'∥) ^ (card ι - 1)`. -/ theorem norm_image_sub_le_of_bound {𝕜 : Type u} {ι : Type v} {E₁ : ι → Type w₁} {E₂ : Type w₂} [DecidableEq ι] [fintype ι] [nondiscrete_normed_field 𝕜] [(i : ι) → normed_group (E₁ i)] [normed_group E₂] [(i : ι) → normed_space 𝕜 (E₁ i)] [normed_space 𝕜 E₂] (f : multilinear_map 𝕜 E₁ E₂) {C : ℝ} (hC : 0 ≤ C) (H : ∀ (m : (i : ι) → E₁ i), norm (coe_fn f m) ≤ C * finset.prod finset.univ fun (i : ι) => norm (m i)) (m₁ : (i : ι) → E₁ i) (m₂ : (i : ι) → E₁ i) : norm (coe_fn f m₁ - coe_fn f m₂) ≤ C * ↑(fintype.card ι) * max (norm m₁) (norm m₂) ^ (fintype.card ι - 1) * norm (m₁ - m₂) := sorry /-- If a multilinear map satisfies an inequality `∥f m∥ ≤ C * ∏ i, ∥m i∥`, then it is continuous. -/ theorem continuous_of_bound {𝕜 : Type u} {ι : Type v} {E₁ : ι → Type w₁} {E₂ : Type w₂} [DecidableEq ι] [fintype ι] [nondiscrete_normed_field 𝕜] [(i : ι) → normed_group (E₁ i)] [normed_group E₂] [(i : ι) → normed_space 𝕜 (E₁ i)] [normed_space 𝕜 E₂] (f : multilinear_map 𝕜 E₁ E₂) (C : ℝ) (H : ∀ (m : (i : ι) → E₁ i), norm (coe_fn f m) ≤ C * finset.prod finset.univ fun (i : ι) => norm (m i)) : continuous ⇑f := sorry /-- Constructing a continuous multilinear map from a multilinear map satisfying a boundedness condition. -/ def mk_continuous {𝕜 : Type u} {ι : Type v} {E₁ : ι → Type w₁} {E₂ : Type w₂} [DecidableEq ι] [fintype ι] [nondiscrete_normed_field 𝕜] [(i : ι) → normed_group (E₁ i)] [normed_group E₂] [(i : ι) → normed_space 𝕜 (E₁ i)] [normed_space 𝕜 E₂] (f : multilinear_map 𝕜 E₁ E₂) (C : ℝ) (H : ∀ (m : (i : ι) → E₁ i), norm (coe_fn f m) ≤ C * finset.prod finset.univ fun (i : ι) => norm (m i)) : continuous_multilinear_map 𝕜 E₁ E₂ := continuous_multilinear_map.mk (mk (to_fun f) sorry sorry) sorry @[simp] theorem coe_mk_continuous {𝕜 : Type u} {ι : Type v} {E₁ : ι → Type w₁} {E₂ : Type w₂} [DecidableEq ι] [fintype ι] [nondiscrete_normed_field 𝕜] [(i : ι) → normed_group (E₁ i)] [normed_group E₂] [(i : ι) → normed_space 𝕜 (E₁ i)] [normed_space 𝕜 E₂] (f : multilinear_map 𝕜 E₁ E₂) (C : ℝ) (H : ∀ (m : (i : ι) → E₁ i), norm (coe_fn f m) ≤ C * finset.prod finset.univ fun (i : ι) => norm (m i)) : ⇑(mk_continuous f C H) = ⇑f := rfl /-- Given a multilinear map in `n` variables, if one restricts it to `k` variables putting `z` on the other coordinates, then the resulting restricted function satisfies an inequality `∥f.restr v∥ ≤ C * ∥z∥^(n-k) * Π ∥v i∥` if the original function satisfies `∥f v∥ ≤ C * Π ∥v i∥`. -/ theorem restr_norm_le {𝕜 : Type u} {G : Type wG} {E₂ : Type w₂} [nondiscrete_normed_field 𝕜] [normed_group G] [normed_group E₂] [normed_space 𝕜 G] [normed_space 𝕜 E₂] {k : ℕ} {n : ℕ} (f : multilinear_map 𝕜 (fun (i : fin n) => G) E₂) (s : finset (fin n)) (hk : finset.card s = k) (z : G) {C : ℝ} (H : ∀ (m : (i : fin n) → (fun (i : fin n) => G) i), norm (coe_fn f m) ≤ C * finset.prod finset.univ fun (i : fin n) => norm (m i)) (v : fin k → G) : norm (coe_fn (restr f s hk z) v) ≤ C * norm z ^ (n - k) * finset.prod finset.univ fun (i : fin k) => norm (v i) := sorry end multilinear_map /-! ### Continuous multilinear maps We define the norm `∥f∥` of a continuous multilinear map `f` in finitely many variables as the smallest number such that `∥f m∥ ≤ ∥f∥ * ∏ i, ∥m i∥` for all `m`. We show that this defines a normed space structure on `continuous_multilinear_map 𝕜 E₁ E₂`. -/ namespace continuous_multilinear_map theorem bound {𝕜 : Type u} {ι : Type v} {E₁ : ι → Type w₁} {E₂ : Type w₂} [DecidableEq ι] [fintype ι] [nondiscrete_normed_field 𝕜] [(i : ι) → normed_group (E₁ i)] [normed_group E₂] [(i : ι) → normed_space 𝕜 (E₁ i)] [normed_space 𝕜 E₂] (f : continuous_multilinear_map 𝕜 E₁ E₂) : ∃ (C : ℝ), 0 < C ∧ ∀ (m : (i : ι) → E₁ i), norm (coe_fn f m) ≤ C * finset.prod finset.univ fun (i : ι) => norm (m i) := multilinear_map.exists_bound_of_continuous (to_multilinear_map f) (cont f) /-- The operator norm of a continuous multilinear map is the inf of all its bounds. -/ def op_norm {𝕜 : Type u} {ι : Type v} {E₁ : ι → Type w₁} {E₂ : Type w₂} [DecidableEq ι] [fintype ι] [nondiscrete_normed_field 𝕜] [(i : ι) → normed_group (E₁ i)] [normed_group E₂] [(i : ι) → normed_space 𝕜 (E₁ i)] [normed_space 𝕜 E₂] (f : continuous_multilinear_map 𝕜 E₁ E₂) : ℝ := Inf (set_of fun (c : ℝ) => 0 ≤ c ∧ ∀ (m : (i : ι) → E₁ i), norm (coe_fn f m) ≤ c * finset.prod finset.univ fun (i : ι) => norm (m i)) protected instance has_op_norm {𝕜 : Type u} {ι : Type v} {E₁ : ι → Type w₁} {E₂ : Type w₂} [DecidableEq ι] [fintype ι] [nondiscrete_normed_field 𝕜] [(i : ι) → normed_group (E₁ i)] [normed_group E₂] [(i : ι) → normed_space 𝕜 (E₁ i)] [normed_space 𝕜 E₂] : has_norm (continuous_multilinear_map 𝕜 E₁ E₂) := has_norm.mk op_norm theorem norm_def {𝕜 : Type u} {ι : Type v} {E₁ : ι → Type w₁} {E₂ : Type w₂} [DecidableEq ι] [fintype ι] [nondiscrete_normed_field 𝕜] [(i : ι) → normed_group (E₁ i)] [normed_group E₂] [(i : ι) → normed_space 𝕜 (E₁ i)] [normed_space 𝕜 E₂] (f : continuous_multilinear_map 𝕜 E₁ E₂) : norm f = Inf (set_of fun (c : ℝ) => 0 ≤ c ∧ ∀ (m : (i : ι) → E₁ i), norm (coe_fn f m) ≤ c * finset.prod finset.univ fun (i : ι) => norm (m i)) := rfl -- So that invocations of `real.Inf_le` make sense: we show that the set of -- bounds is nonempty and bounded below. theorem bounds_nonempty {𝕜 : Type u} {ι : Type v} {E₁ : ι → Type w₁} {E₂ : Type w₂} [DecidableEq ι] [fintype ι] [nondiscrete_normed_field 𝕜] [(i : ι) → normed_group (E₁ i)] [normed_group E₂] [(i : ι) → normed_space 𝕜 (E₁ i)] [normed_space 𝕜 E₂] {f : continuous_multilinear_map 𝕜 E₁ E₂} : ∃ (c : ℝ), c ∈ set_of fun (c : ℝ) => 0 ≤ c ∧ ∀ (m : (i : ι) → E₁ i), norm (coe_fn f m) ≤ c * finset.prod finset.univ fun (i : ι) => norm (m i) := sorry theorem bounds_bdd_below {𝕜 : Type u} {ι : Type v} {E₁ : ι → Type w₁} {E₂ : Type w₂} [DecidableEq ι] [fintype ι] [nondiscrete_normed_field 𝕜] [(i : ι) → normed_group (E₁ i)] [normed_group E₂] [(i : ι) → normed_space 𝕜 (E₁ i)] [normed_space 𝕜 E₂] {f : continuous_multilinear_map 𝕜 E₁ E₂} : bdd_below (set_of fun (c : ℝ) => 0 ≤ c ∧ ∀ (m : (i : ι) → E₁ i), norm (coe_fn f m) ≤ c * finset.prod finset.univ fun (i : ι) => norm (m i)) := sorry theorem op_norm_nonneg {𝕜 : Type u} {ι : Type v} {E₁ : ι → Type w₁} {E₂ : Type w₂} [DecidableEq ι] [fintype ι] [nondiscrete_normed_field 𝕜] [(i : ι) → normed_group (E₁ i)] [normed_group E₂] [(i : ι) → normed_space 𝕜 (E₁ i)] [normed_space 𝕜 E₂] (f : continuous_multilinear_map 𝕜 E₁ E₂) : 0 ≤ norm f := sorry /-- The fundamental property of the operator norm of a continuous multilinear map: `∥f m∥` is bounded by `∥f∥` times the product of the `∥m i∥`. -/ theorem le_op_norm {𝕜 : Type u} {ι : Type v} {E₁ : ι → Type w₁} {E₂ : Type w₂} [DecidableEq ι] [fintype ι] [nondiscrete_normed_field 𝕜] [(i : ι) → normed_group (E₁ i)] [normed_group E₂] [(i : ι) → normed_space 𝕜 (E₁ i)] [normed_space 𝕜 E₂] (f : continuous_multilinear_map 𝕜 E₁ E₂) (m : (i : ι) → E₁ i) : norm (coe_fn f m) ≤ norm f * finset.prod finset.univ fun (i : ι) => norm (m i) := sorry theorem ratio_le_op_norm {𝕜 : Type u} {ι : Type v} {E₁ : ι → Type w₁} {E₂ : Type w₂} [DecidableEq ι] [fintype ι] [nondiscrete_normed_field 𝕜] [(i : ι) → normed_group (E₁ i)] [normed_group E₂] [(i : ι) → normed_space 𝕜 (E₁ i)] [normed_space 𝕜 E₂] (f : continuous_multilinear_map 𝕜 E₁ E₂) (m : (i : ι) → E₁ i) : (norm (coe_fn f m) / finset.prod finset.univ fun (i : ι) => norm (m i)) ≤ norm f := sorry /-- The image of the unit ball under a continuous multilinear map is bounded. -/ theorem unit_le_op_norm {𝕜 : Type u} {ι : Type v} {E₁ : ι → Type w₁} {E₂ : Type w₂} [DecidableEq ι] [fintype ι] [nondiscrete_normed_field 𝕜] [(i : ι) → normed_group (E₁ i)] [normed_group E₂] [(i : ι) → normed_space 𝕜 (E₁ i)] [normed_space 𝕜 E₂] (f : continuous_multilinear_map 𝕜 E₁ E₂) (m : (i : ι) → E₁ i) (h : norm m ≤ 1) : norm (coe_fn f m) ≤ norm f := sorry /-- If one controls the norm of every `f x`, then one controls the norm of `f`. -/ theorem op_norm_le_bound {𝕜 : Type u} {ι : Type v} {E₁ : ι → Type w₁} {E₂ : Type w₂} [DecidableEq ι] [fintype ι] [nondiscrete_normed_field 𝕜] [(i : ι) → normed_group (E₁ i)] [normed_group E₂] [(i : ι) → normed_space 𝕜 (E₁ i)] [normed_space 𝕜 E₂] (f : continuous_multilinear_map 𝕜 E₁ E₂) {M : ℝ} (hMp : 0 ≤ M) (hM : ∀ (m : (i : ι) → E₁ i), norm (coe_fn f m) ≤ M * finset.prod finset.univ fun (i : ι) => norm (m i)) : norm f ≤ M := sorry /-- The operator norm satisfies the triangle inequality. -/ theorem op_norm_add_le {𝕜 : Type u} {ι : Type v} {E₁ : ι → Type w₁} {E₂ : Type w₂} [DecidableEq ι] [fintype ι] [nondiscrete_normed_field 𝕜] [(i : ι) → normed_group (E₁ i)] [normed_group E₂] [(i : ι) → normed_space 𝕜 (E₁ i)] [normed_space 𝕜 E₂] (f : continuous_multilinear_map 𝕜 E₁ E₂) (g : continuous_multilinear_map 𝕜 E₁ E₂) : norm (f + g) ≤ norm f + norm g := sorry /-- A continuous linear map is zero iff its norm vanishes. -/ theorem op_norm_zero_iff {𝕜 : Type u} {ι : Type v} {E₁ : ι → Type w₁} {E₂ : Type w₂} [DecidableEq ι] [fintype ι] [nondiscrete_normed_field 𝕜] [(i : ι) → normed_group (E₁ i)] [normed_group E₂] [(i : ι) → normed_space 𝕜 (E₁ i)] [normed_space 𝕜 E₂] (f : continuous_multilinear_map 𝕜 E₁ E₂) : norm f = 0 ↔ f = 0 := sorry theorem op_norm_smul_le {𝕜 : Type u} {ι : Type v} {E₁ : ι → Type w₁} {E₂ : Type w₂} [DecidableEq ι] [fintype ι] [nondiscrete_normed_field 𝕜] [(i : ι) → normed_group (E₁ i)] [normed_group E₂] [(i : ι) → normed_space 𝕜 (E₁ i)] [normed_space 𝕜 E₂] (f : continuous_multilinear_map 𝕜 E₁ E₂) {𝕜' : Type u_1} [nondiscrete_normed_field 𝕜'] [normed_algebra 𝕜' 𝕜] [normed_space 𝕜' E₂] [is_scalar_tower 𝕜' 𝕜 E₂] (c : 𝕜') : norm (c • f) ≤ norm c * norm f := sorry theorem op_norm_neg {𝕜 : Type u} {ι : Type v} {E₁ : ι → Type w₁} {E₂ : Type w₂} [DecidableEq ι] [fintype ι] [nondiscrete_normed_field 𝕜] [(i : ι) → normed_group (E₁ i)] [normed_group E₂] [(i : ι) → normed_space 𝕜 (E₁ i)] [normed_space 𝕜 E₂] (f : continuous_multilinear_map 𝕜 E₁ E₂) : norm (-f) = norm f := sorry /-- Continuous multilinear maps themselves form a normed space with respect to the operator norm. -/ protected instance to_normed_group {𝕜 : Type u} {ι : Type v} {E₁ : ι → Type w₁} {E₂ : Type w₂} [DecidableEq ι] [fintype ι] [nondiscrete_normed_field 𝕜] [(i : ι) → normed_group (E₁ i)] [normed_group E₂] [(i : ι) → normed_space 𝕜 (E₁ i)] [normed_space 𝕜 E₂] : normed_group (continuous_multilinear_map 𝕜 E₁ E₂) := normed_group.of_core (continuous_multilinear_map 𝕜 E₁ E₂) sorry protected instance to_normed_space {𝕜 : Type u} {ι : Type v} {E₁ : ι → Type w₁} {E₂ : Type w₂} [DecidableEq ι] [fintype ι] [nondiscrete_normed_field 𝕜] [(i : ι) → normed_group (E₁ i)] [normed_group E₂] [(i : ι) → normed_space 𝕜 (E₁ i)] [normed_space 𝕜 E₂] {𝕜' : Type u_1} [nondiscrete_normed_field 𝕜'] [normed_algebra 𝕜' 𝕜] [normed_space 𝕜' E₂] [is_scalar_tower 𝕜' 𝕜 E₂] : normed_space 𝕜' (continuous_multilinear_map 𝕜 E₁ E₂) := normed_space.mk sorry @[simp] theorem norm_restrict_scalars {𝕜 : Type u} {ι : Type v} {E₁ : ι → Type w₁} {E₂ : Type w₂} [DecidableEq ι] [fintype ι] [nondiscrete_normed_field 𝕜] [(i : ι) → normed_group (E₁ i)] [normed_group E₂] [(i : ι) → normed_space 𝕜 (E₁ i)] [normed_space 𝕜 E₂] (f : continuous_multilinear_map 𝕜 E₁ E₂) {𝕜' : Type u_1} [nondiscrete_normed_field 𝕜'] [normed_algebra 𝕜' 𝕜] [normed_space 𝕜' E₂] [is_scalar_tower 𝕜' 𝕜 E₂] [(i : ι) → normed_space 𝕜' (E₁ i)] [∀ (i : ι), is_scalar_tower 𝕜' 𝕜 (E₁ i)] : norm (restrict_scalars 𝕜' f) = norm f := sorry /-- `continuous_multilinear_map.restrict_scalars` as a `continuous_multilinear_map`. -/ def restrict_scalars_linear {𝕜 : Type u} {ι : Type v} {E₁ : ι → Type w₁} {E₂ : Type w₂} [DecidableEq ι] [fintype ι] [nondiscrete_normed_field 𝕜] [(i : ι) → normed_group (E₁ i)] [normed_group E₂] [(i : ι) → normed_space 𝕜 (E₁ i)] [normed_space 𝕜 E₂] (𝕜' : Type u_1) [nondiscrete_normed_field 𝕜'] [normed_algebra 𝕜' 𝕜] [normed_space 𝕜' E₂] [is_scalar_tower 𝕜' 𝕜 E₂] [(i : ι) → normed_space 𝕜' (E₁ i)] [∀ (i : ι), is_scalar_tower 𝕜' 𝕜 (E₁ i)] : continuous_linear_map 𝕜' (continuous_multilinear_map 𝕜 E₁ E₂) (continuous_multilinear_map 𝕜' E₁ E₂) := linear_map.mk_continuous (linear_map.mk (restrict_scalars 𝕜') sorry sorry) 1 sorry theorem continuous_restrict_scalars {𝕜 : Type u} {ι : Type v} {E₁ : ι → Type w₁} {E₂ : Type w₂} [DecidableEq ι] [fintype ι] [nondiscrete_normed_field 𝕜] [(i : ι) → normed_group (E₁ i)] [normed_group E₂] [(i : ι) → normed_space 𝕜 (E₁ i)] [normed_space 𝕜 E₂] {𝕜' : Type u_1} [nondiscrete_normed_field 𝕜'] [normed_algebra 𝕜' 𝕜] [normed_space 𝕜' E₂] [is_scalar_tower 𝕜' 𝕜 E₂] [(i : ι) → normed_space 𝕜' (E₁ i)] [∀ (i : ι), is_scalar_tower 𝕜' 𝕜 (E₁ i)] : continuous (restrict_scalars 𝕜') := continuous_linear_map.continuous (restrict_scalars_linear 𝕜') /-- The difference `f m₁ - f m₂` is controlled in terms of `∥f∥` and `∥m₁ - m₂∥`, precise version. For a less precise but more usable version, see `norm_image_sub_le`. The bound reads `∥f m - f m'∥ ≤ ∥f∥ * ∥m 1 - m' 1∥ * max ∥m 2∥ ∥m' 2∥ * max ∥m 3∥ ∥m' 3∥ * ... * max ∥m n∥ ∥m' n∥ + ...`, where the other terms in the sum are the same products where `1` is replaced by any `i`.-/ theorem norm_image_sub_le' {𝕜 : Type u} {ι : Type v} {E₁ : ι → Type w₁} {E₂ : Type w₂} [DecidableEq ι] [fintype ι] [nondiscrete_normed_field 𝕜] [(i : ι) → normed_group (E₁ i)] [normed_group E₂] [(i : ι) → normed_space 𝕜 (E₁ i)] [normed_space 𝕜 E₂] (f : continuous_multilinear_map 𝕜 E₁ E₂) (m₁ : (i : ι) → E₁ i) (m₂ : (i : ι) → E₁ i) : norm (coe_fn f m₁ - coe_fn f m₂) ≤ norm f * finset.sum finset.univ fun (i : ι) => finset.prod finset.univ fun (j : ι) => ite (j = i) (norm (m₁ i - m₂ i)) (max (norm (m₁ j)) (norm (m₂ j))) := multilinear_map.norm_image_sub_le_of_bound' (to_multilinear_map f) (norm_nonneg f) (le_op_norm f) m₁ m₂ /-- The difference `f m₁ - f m₂` is controlled in terms of `∥f∥` and `∥m₁ - m₂∥`, less precise version. For a more precise but less usable version, see `norm_image_sub_le'`. The bound is `∥f m - f m'∥ ≤ ∥f∥ * card ι * ∥m - m'∥ * (max ∥m∥ ∥m'∥) ^ (card ι - 1)`.-/ theorem norm_image_sub_le {𝕜 : Type u} {ι : Type v} {E₁ : ι → Type w₁} {E₂ : Type w₂} [DecidableEq ι] [fintype ι] [nondiscrete_normed_field 𝕜] [(i : ι) → normed_group (E₁ i)] [normed_group E₂] [(i : ι) → normed_space 𝕜 (E₁ i)] [normed_space 𝕜 E₂] (f : continuous_multilinear_map 𝕜 E₁ E₂) (m₁ : (i : ι) → E₁ i) (m₂ : (i : ι) → E₁ i) : norm (coe_fn f m₁ - coe_fn f m₂) ≤ norm f * ↑(fintype.card ι) * max (norm m₁) (norm m₂) ^ (fintype.card ι - 1) * norm (m₁ - m₂) := multilinear_map.norm_image_sub_le_of_bound (to_multilinear_map f) (norm_nonneg f) (le_op_norm f) m₁ m₂ /-- Applying a multilinear map to a vector is continuous in both coordinates. -/ theorem continuous_eval {𝕜 : Type u} {ι : Type v} {E₁ : ι → Type w₁} {E₂ : Type w₂} [DecidableEq ι] [fintype ι] [nondiscrete_normed_field 𝕜] [(i : ι) → normed_group (E₁ i)] [normed_group E₂] [(i : ι) → normed_space 𝕜 (E₁ i)] [normed_space 𝕜 E₂] : continuous fun (p : continuous_multilinear_map 𝕜 E₁ E₂ × ((i : ι) → E₁ i)) => coe_fn (prod.fst p) (prod.snd p) := sorry theorem continuous_eval_left {𝕜 : Type u} {ι : Type v} {E₁ : ι → Type w₁} {E₂ : Type w₂} [DecidableEq ι] [fintype ι] [nondiscrete_normed_field 𝕜] [(i : ι) → normed_group (E₁ i)] [normed_group E₂] [(i : ι) → normed_space 𝕜 (E₁ i)] [normed_space 𝕜 E₂] (m : (i : ι) → E₁ i) : continuous fun (p : continuous_multilinear_map 𝕜 E₁ E₂) => coe_fn p m := continuous.comp continuous_eval (continuous.prod_mk continuous_id continuous_const) theorem has_sum_eval {𝕜 : Type u} {ι : Type v} {E₁ : ι → Type w₁} {E₂ : Type w₂} [DecidableEq ι] [fintype ι] [nondiscrete_normed_field 𝕜] [(i : ι) → normed_group (E₁ i)] [normed_group E₂] [(i : ι) → normed_space 𝕜 (E₁ i)] [normed_space 𝕜 E₂] {α : Type u_1} {p : α → continuous_multilinear_map 𝕜 E₁ E₂} {q : continuous_multilinear_map 𝕜 E₁ E₂} (h : has_sum p q) (m : (i : ι) → E₁ i) : has_sum (fun (a : α) => coe_fn (p a) m) (coe_fn q m) := sorry /-- If the target space is complete, the space of continuous multilinear maps with its norm is also complete. The proof is essentially the same as for the space of continuous linear maps (modulo the addition of `finset.prod` where needed. The duplication could be avoided by deducing the linear case from the multilinear case via a currying isomorphism. However, this would mess up imports, and it is more satisfactory to have the simplest case as a standalone proof. -/ protected instance complete_space {𝕜 : Type u} {ι : Type v} {E₁ : ι → Type w₁} {E₂ : Type w₂} [DecidableEq ι] [fintype ι] [nondiscrete_normed_field 𝕜] [(i : ι) → normed_group (E₁ i)] [normed_group E₂] [(i : ι) → normed_space 𝕜 (E₁ i)] [normed_space 𝕜 E₂] [complete_space E₂] : complete_space (continuous_multilinear_map 𝕜 E₁ E₂) := sorry end continuous_multilinear_map /-- If a continuous multilinear map is constructed from a multilinear map via the constructor `mk_continuous`, then its norm is bounded by the bound given to the constructor if it is nonnegative. -/ theorem multilinear_map.mk_continuous_norm_le {𝕜 : Type u} {ι : Type v} {E₁ : ι → Type w₁} {E₂ : Type w₂} [DecidableEq ι] [fintype ι] [nondiscrete_normed_field 𝕜] [(i : ι) → normed_group (E₁ i)] [normed_group E₂] [(i : ι) → normed_space 𝕜 (E₁ i)] [normed_space 𝕜 E₂] (f : multilinear_map 𝕜 E₁ E₂) {C : ℝ} (hC : 0 ≤ C) (H : ∀ (m : (i : ι) → E₁ i), norm (coe_fn f m) ≤ C * finset.prod finset.univ fun (i : ι) => norm (m i)) : norm (multilinear_map.mk_continuous f C H) ≤ C := continuous_multilinear_map.op_norm_le_bound (multilinear_map.mk_continuous f C H) hC fun (m : (i : ι) → E₁ i) => H m namespace continuous_multilinear_map /-- Given a continuous multilinear map `f` on `n` variables (parameterized by `fin n`) and a subset `s` of `k` of these variables, one gets a new continuous multilinear map on `fin k` by varying these variables, and fixing the other ones equal to a given value `z`. It is denoted by `f.restr s hk z`, where `hk` is a proof that the cardinality of `s` is `k`. The implicit identification between `fin k` and `s` that we use is the canonical (increasing) bijection. -/ def restr {𝕜 : Type u} {G : Type wG} {E₂ : Type w₂} [nondiscrete_normed_field 𝕜] [normed_group G] [normed_group E₂] [normed_space 𝕜 G] [normed_space 𝕜 E₂] {k : ℕ} {n : ℕ} (f : continuous_multilinear_map 𝕜 (fun (i : fin n) => G) E₂) (s : finset (fin n)) (hk : finset.card s = k) (z : G) : continuous_multilinear_map 𝕜 (fun (i : fin k) => G) E₂ := multilinear_map.mk_continuous (multilinear_map.restr (to_multilinear_map f) s hk z) (norm f * norm z ^ (n - k)) sorry theorem norm_restr {𝕜 : Type u} {G : Type wG} {E₂ : Type w₂} [nondiscrete_normed_field 𝕜] [normed_group G] [normed_group E₂] [normed_space 𝕜 G] [normed_space 𝕜 E₂] {k : ℕ} {n : ℕ} (f : continuous_multilinear_map 𝕜 (fun (i : fin n) => G) E₂) (s : finset (fin n)) (hk : finset.card s = k) (z : G) : norm (restr f s hk z) ≤ norm f * norm z ^ (n - k) := multilinear_map.mk_continuous_norm_le (multilinear_map.restr (to_multilinear_map f) s hk z) (mul_nonneg (norm_nonneg f) (pow_nonneg (norm_nonneg z) (n - k))) (restr._proof_1 f s hk z) /-- The continuous multilinear map on `A^ι`, where `A` is a normed commutative algebra over `𝕜`, associating to `m` the product of all the `m i`. See also `continuous_multilinear_map.mk_pi_algebra_fin`. -/ protected def mk_pi_algebra (𝕜 : Type u) (ι : Type v) [DecidableEq ι] [fintype ι] [nondiscrete_normed_field 𝕜] (A : Type u_1) [normed_comm_ring A] [normed_algebra 𝕜 A] : continuous_multilinear_map 𝕜 (fun (i : ι) => A) A := multilinear_map.mk_continuous (multilinear_map.mk_pi_algebra 𝕜 ι A) (ite (Nonempty ι) 1 (norm 1)) sorry @[simp] theorem mk_pi_algebra_apply {𝕜 : Type u} {ι : Type v} [DecidableEq ι] [fintype ι] [nondiscrete_normed_field 𝕜] {A : Type u_1} [normed_comm_ring A] [normed_algebra 𝕜 A] (m : ι → A) : coe_fn (continuous_multilinear_map.mk_pi_algebra 𝕜 ι A) m = finset.prod finset.univ fun (i : ι) => m i := rfl theorem norm_mk_pi_algebra_le {𝕜 : Type u} {ι : Type v} [DecidableEq ι] [fintype ι] [nondiscrete_normed_field 𝕜] {A : Type u_1} [normed_comm_ring A] [normed_algebra 𝕜 A] [Nonempty ι] : norm (continuous_multilinear_map.mk_pi_algebra 𝕜 ι A) ≤ 1 := sorry theorem norm_mk_pi_algebra_of_empty {𝕜 : Type u} {ι : Type v} [DecidableEq ι] [fintype ι] [nondiscrete_normed_field 𝕜] {A : Type u_1} [normed_comm_ring A] [normed_algebra 𝕜 A] (h : ¬Nonempty ι) : norm (continuous_multilinear_map.mk_pi_algebra 𝕜 ι A) = norm 1 := sorry @[simp] theorem norm_mk_pi_algebra {𝕜 : Type u} {ι : Type v} [DecidableEq ι] [fintype ι] [nondiscrete_normed_field 𝕜] {A : Type u_1} [normed_comm_ring A] [normed_algebra 𝕜 A] [norm_one_class A] : norm (continuous_multilinear_map.mk_pi_algebra 𝕜 ι A) = 1 := sorry /-- The continuous multilinear map on `A^n`, where `A` is a normed algebra over `𝕜`, associating to `m` the product of all the `m i`. See also: `multilinear_map.mk_pi_algebra`. -/ protected def mk_pi_algebra_fin (𝕜 : Type u) (n : ℕ) [nondiscrete_normed_field 𝕜] (A : Type u_1) [normed_ring A] [normed_algebra 𝕜 A] : continuous_multilinear_map 𝕜 (fun (i : fin n) => A) A := multilinear_map.mk_continuous (multilinear_map.mk_pi_algebra_fin 𝕜 n A) (nat.cases_on n (norm 1) fun (_x : ℕ) => 1) sorry @[simp] theorem mk_pi_algebra_fin_apply {𝕜 : Type u} {n : ℕ} [nondiscrete_normed_field 𝕜] {A : Type u_1} [normed_ring A] [normed_algebra 𝕜 A] (m : fin n → A) : coe_fn (continuous_multilinear_map.mk_pi_algebra_fin 𝕜 n A) m = list.prod (list.of_fn m) := rfl theorem norm_mk_pi_algebra_fin_succ_le {𝕜 : Type u} {n : ℕ} [nondiscrete_normed_field 𝕜] {A : Type u_1} [normed_ring A] [normed_algebra 𝕜 A] : norm (continuous_multilinear_map.mk_pi_algebra_fin 𝕜 (Nat.succ n) A) ≤ 1 := multilinear_map.mk_continuous_norm_le (multilinear_map.mk_pi_algebra_fin 𝕜 (Nat.succ n) A) zero_le_one (mk_pi_algebra_fin._proof_1 𝕜 (Nat.succ n) A) theorem norm_mk_pi_algebra_fin_le_of_pos {𝕜 : Type u} {n : ℕ} [nondiscrete_normed_field 𝕜] {A : Type u_1} [normed_ring A] [normed_algebra 𝕜 A] (hn : 0 < n) : norm (continuous_multilinear_map.mk_pi_algebra_fin 𝕜 n A) ≤ 1 := nat.cases_on n (fun (hn : 0 < 0) => false.elim (has_lt.lt.false hn)) (fun (n : ℕ) (hn : 0 < Nat.succ n) => norm_mk_pi_algebra_fin_succ_le) hn theorem norm_mk_pi_algebra_fin_zero {𝕜 : Type u} [nondiscrete_normed_field 𝕜] {A : Type u_1} [normed_ring A] [normed_algebra 𝕜 A] : norm (continuous_multilinear_map.mk_pi_algebra_fin 𝕜 0 A) = norm 1 := sorry theorem norm_mk_pi_algebra_fin {𝕜 : Type u} {n : ℕ} [nondiscrete_normed_field 𝕜] {A : Type u_1} [normed_ring A] [normed_algebra 𝕜 A] [norm_one_class A] : norm (continuous_multilinear_map.mk_pi_algebra_fin 𝕜 n A) = 1 := sorry /-- The canonical continuous multilinear map on `𝕜^ι`, associating to `m` the product of all the `m i` (multiplied by a fixed reference element `z` in the target module) -/ protected def mk_pi_field (𝕜 : Type u) (ι : Type v) {E₂ : Type w₂} [DecidableEq ι] [fintype ι] [nondiscrete_normed_field 𝕜] [normed_group E₂] [normed_space 𝕜 E₂] (z : E₂) : continuous_multilinear_map 𝕜 (fun (i : ι) => 𝕜) E₂ := multilinear_map.mk_continuous (multilinear_map.mk_pi_ring 𝕜 ι z) (norm z) sorry @[simp] theorem mk_pi_field_apply {𝕜 : Type u} {ι : Type v} {E₂ : Type w₂} [DecidableEq ι] [fintype ι] [nondiscrete_normed_field 𝕜] [normed_group E₂] [normed_space 𝕜 E₂] (z : E₂) (m : ι → 𝕜) : coe_fn (continuous_multilinear_map.mk_pi_field 𝕜 ι z) m = (finset.prod finset.univ fun (i : ι) => m i) • z := rfl theorem mk_pi_field_apply_one_eq_self {𝕜 : Type u} {ι : Type v} {E₂ : Type w₂} [DecidableEq ι] [fintype ι] [nondiscrete_normed_field 𝕜] [normed_group E₂] [normed_space 𝕜 E₂] (f : continuous_multilinear_map 𝕜 (fun (i : ι) => 𝕜) E₂) : continuous_multilinear_map.mk_pi_field 𝕜 ι (coe_fn f fun (i : ι) => 1) = f := to_multilinear_map_inj (multilinear_map.mk_pi_ring_apply_one_eq_self (to_multilinear_map f)) /-- Continuous multilinear maps on `𝕜^n` with values in `E₂` are in bijection with `E₂`, as such a continuous multilinear map is completely determined by its value on the constant vector made of ones. We register this bijection as a linear equivalence in `continuous_multilinear_map.pi_field_equiv_aux`. The continuous linear equivalence is `continuous_multilinear_map.pi_field_equiv`. -/ protected def pi_field_equiv_aux (𝕜 : Type u) (ι : Type v) (E₂ : Type w₂) [DecidableEq ι] [fintype ι] [nondiscrete_normed_field 𝕜] [normed_group E₂] [normed_space 𝕜 E₂] : linear_equiv 𝕜 E₂ (continuous_multilinear_map 𝕜 (fun (i : ι) => 𝕜) E₂) := linear_equiv.mk (fun (z : E₂) => continuous_multilinear_map.mk_pi_field 𝕜 ι z) sorry sorry (fun (f : continuous_multilinear_map 𝕜 (fun (i : ι) => 𝕜) E₂) => coe_fn f fun (i : ι) => 1) sorry sorry /-- Continuous multilinear maps on `𝕜^n` with values in `E₂` are in bijection with `E₂`, as such a continuous multilinear map is completely determined by its value on the constant vector made of ones. We register this bijection as a continuous linear equivalence in `continuous_multilinear_map.pi_field_equiv`. -/ protected def pi_field_equiv (𝕜 : Type u) (ι : Type v) (E₂ : Type w₂) [DecidableEq ι] [fintype ι] [nondiscrete_normed_field 𝕜] [normed_group E₂] [normed_space 𝕜 E₂] : continuous_linear_equiv 𝕜 E₂ (continuous_multilinear_map 𝕜 (fun (i : ι) => 𝕜) E₂) := continuous_linear_equiv.mk (linear_equiv.mk (linear_equiv.to_fun (continuous_multilinear_map.pi_field_equiv_aux 𝕜 ι E₂)) sorry sorry (linear_equiv.inv_fun (continuous_multilinear_map.pi_field_equiv_aux 𝕜 ι E₂)) sorry sorry) end continuous_multilinear_map /-! ### Currying We associate to a continuous multilinear map in `n+1` variables (i.e., based on `fin n.succ`) two curried functions, named `f.curry_left` (which is a continuous linear map on `E 0` taking values in continuous multilinear maps in `n` variables) and `f.curry_right` (which is a continuous multilinear map in `n` variables taking values in continuous linear maps on `E (last n)`). The inverse operations are called `uncurry_left` and `uncurry_right`. We also register continuous linear equiv versions of these correspondences, in `continuous_multilinear_curry_left_equiv` and `continuous_multilinear_curry_right_equiv`. -/ theorem continuous_linear_map.norm_map_tail_le {𝕜 : Type u} {n : ℕ} {E : fin (Nat.succ n) → Type w} {E₂ : Type w₂} [nondiscrete_normed_field 𝕜] [(i : fin (Nat.succ n)) → normed_group (E i)] [normed_group E₂] [(i : fin (Nat.succ n)) → normed_space 𝕜 (E i)] [normed_space 𝕜 E₂] (f : continuous_linear_map 𝕜 (E 0) (continuous_multilinear_map 𝕜 (fun (i : fin n) => E (fin.succ i)) E₂)) (m : (i : fin (Nat.succ n)) → E i) : norm (coe_fn (coe_fn f (m 0)) (fin.tail m)) ≤ norm f * finset.prod finset.univ fun (i : fin (Nat.succ n)) => norm (m i) := sorry theorem continuous_multilinear_map.norm_map_init_le {𝕜 : Type u} {n : ℕ} {E : fin (Nat.succ n) → Type w} {E₂ : Type w₂} [nondiscrete_normed_field 𝕜] [(i : fin (Nat.succ n)) → normed_group (E i)] [normed_group E₂] [(i : fin (Nat.succ n)) → normed_space 𝕜 (E i)] [normed_space 𝕜 E₂] (f : continuous_multilinear_map 𝕜 (fun (i : fin n) => E (coe_fn fin.cast_succ i)) (continuous_linear_map 𝕜 (E (fin.last n)) E₂)) (m : (i : fin (Nat.succ n)) → E i) : norm (coe_fn (coe_fn f (fin.init m)) (m (fin.last n))) ≤ norm f * finset.prod finset.univ fun (i : fin (Nat.succ n)) => norm (m i) := sorry theorem continuous_multilinear_map.norm_map_cons_le {𝕜 : Type u} {n : ℕ} {E : fin (Nat.succ n) → Type w} {E₂ : Type w₂} [nondiscrete_normed_field 𝕜] [(i : fin (Nat.succ n)) → normed_group (E i)] [normed_group E₂] [(i : fin (Nat.succ n)) → normed_space 𝕜 (E i)] [normed_space 𝕜 E₂] (f : continuous_multilinear_map 𝕜 E E₂) (x : E 0) (m : (i : fin n) → E (fin.succ i)) : norm (coe_fn f (fin.cons x m)) ≤ norm f * norm x * finset.prod finset.univ fun (i : fin n) => norm (m i) := sorry theorem continuous_multilinear_map.norm_map_snoc_le {𝕜 : Type u} {n : ℕ} {E : fin (Nat.succ n) → Type w} {E₂ : Type w₂} [nondiscrete_normed_field 𝕜] [(i : fin (Nat.succ n)) → normed_group (E i)] [normed_group E₂] [(i : fin (Nat.succ n)) → normed_space 𝕜 (E i)] [normed_space 𝕜 E₂] (f : continuous_multilinear_map 𝕜 E E₂) (m : (i : fin n) → E (coe_fn fin.cast_succ i)) (x : E (fin.last n)) : norm (coe_fn f (fin.snoc m x)) ≤ (norm f * finset.prod finset.univ fun (i : fin n) => norm (m i)) * norm x := sorry /-! #### Left currying -/ /-- Given a continuous linear map `f` from `E 0` to continuous multilinear maps on `n` variables, construct the corresponding continuous multilinear map on `n+1` variables obtained by concatenating the variables, given by `m ↦ f (m 0) (tail m)`-/ def continuous_linear_map.uncurry_left {𝕜 : Type u} {n : ℕ} {E : fin (Nat.succ n) → Type w} {E₂ : Type w₂} [nondiscrete_normed_field 𝕜] [(i : fin (Nat.succ n)) → normed_group (E i)] [normed_group E₂] [(i : fin (Nat.succ n)) → normed_space 𝕜 (E i)] [normed_space 𝕜 E₂] (f : continuous_linear_map 𝕜 (E 0) (continuous_multilinear_map 𝕜 (fun (i : fin n) => E (fin.succ i)) E₂)) : continuous_multilinear_map 𝕜 E E₂ := multilinear_map.mk_continuous (linear_map.uncurry_left (linear_map.comp continuous_multilinear_map.to_multilinear_map_linear (continuous_linear_map.to_linear_map f))) (norm f) sorry @[simp] theorem continuous_linear_map.uncurry_left_apply {𝕜 : Type u} {n : ℕ} {E : fin (Nat.succ n) → Type w} {E₂ : Type w₂} [nondiscrete_normed_field 𝕜] [(i : fin (Nat.succ n)) → normed_group (E i)] [normed_group E₂] [(i : fin (Nat.succ n)) → normed_space 𝕜 (E i)] [normed_space 𝕜 E₂] (f : continuous_linear_map 𝕜 (E 0) (continuous_multilinear_map 𝕜 (fun (i : fin n) => E (fin.succ i)) E₂)) (m : (i : fin (Nat.succ n)) → E i) : coe_fn (continuous_linear_map.uncurry_left f) m = coe_fn (coe_fn f (m 0)) (fin.tail m) := rfl /-- Given a continuous multilinear map `f` in `n+1` variables, split the first variable to obtain a continuous linear map into continuous multilinear maps in `n` variables, given by `x ↦ (m ↦ f (cons x m))`. -/ def continuous_multilinear_map.curry_left {𝕜 : Type u} {n : ℕ} {E : fin (Nat.succ n) → Type w} {E₂ : Type w₂} [nondiscrete_normed_field 𝕜] [(i : fin (Nat.succ n)) → normed_group (E i)] [normed_group E₂] [(i : fin (Nat.succ n)) → normed_space 𝕜 (E i)] [normed_space 𝕜 E₂] (f : continuous_multilinear_map 𝕜 E E₂) : continuous_linear_map 𝕜 (E 0) (continuous_multilinear_map 𝕜 (fun (i : fin n) => E (fin.succ i)) E₂) := linear_map.mk_continuous (linear_map.mk (fun (x : E 0) => multilinear_map.mk_continuous (coe_fn (multilinear_map.curry_left (continuous_multilinear_map.to_multilinear_map f)) x) (norm f * norm x) sorry) sorry sorry) (norm f) sorry @[simp] theorem continuous_multilinear_map.curry_left_apply {𝕜 : Type u} {n : ℕ} {E : fin (Nat.succ n) → Type w} {E₂ : Type w₂} [nondiscrete_normed_field 𝕜] [(i : fin (Nat.succ n)) → normed_group (E i)] [normed_group E₂] [(i : fin (Nat.succ n)) → normed_space 𝕜 (E i)] [normed_space 𝕜 E₂] (f : continuous_multilinear_map 𝕜 E E₂) (x : E 0) (m : (i : fin n) → E (fin.succ i)) : coe_fn (coe_fn (continuous_multilinear_map.curry_left f) x) m = coe_fn f (fin.cons x m) := rfl @[simp] theorem continuous_linear_map.curry_uncurry_left {𝕜 : Type u} {n : ℕ} {E : fin (Nat.succ n) → Type w} {E₂ : Type w₂} [nondiscrete_normed_field 𝕜] [(i : fin (Nat.succ n)) → normed_group (E i)] [normed_group E₂] [(i : fin (Nat.succ n)) → normed_space 𝕜 (E i)] [normed_space 𝕜 E₂] (f : continuous_linear_map 𝕜 (E 0) (continuous_multilinear_map 𝕜 (fun (i : fin n) => E (fin.succ i)) E₂)) : continuous_multilinear_map.curry_left (continuous_linear_map.uncurry_left f) = f := sorry @[simp] theorem continuous_multilinear_map.uncurry_curry_left {𝕜 : Type u} {n : ℕ} {E : fin (Nat.succ n) → Type w} {E₂ : Type w₂} [nondiscrete_normed_field 𝕜] [(i : fin (Nat.succ n)) → normed_group (E i)] [normed_group E₂] [(i : fin (Nat.succ n)) → normed_space 𝕜 (E i)] [normed_space 𝕜 E₂] (f : continuous_multilinear_map 𝕜 E E₂) : continuous_linear_map.uncurry_left (continuous_multilinear_map.curry_left f) = f := sorry @[simp] theorem continuous_multilinear_map.curry_left_norm {𝕜 : Type u} {n : ℕ} {E : fin (Nat.succ n) → Type w} {E₂ : Type w₂} [nondiscrete_normed_field 𝕜] [(i : fin (Nat.succ n)) → normed_group (E i)] [normed_group E₂] [(i : fin (Nat.succ n)) → normed_space 𝕜 (E i)] [normed_space 𝕜 E₂] (f : continuous_multilinear_map 𝕜 E E₂) : norm (continuous_multilinear_map.curry_left f) = norm f := sorry @[simp] theorem continuous_linear_map.uncurry_left_norm {𝕜 : Type u} {n : ℕ} {E : fin (Nat.succ n) → Type w} {E₂ : Type w₂} [nondiscrete_normed_field 𝕜] [(i : fin (Nat.succ n)) → normed_group (E i)] [normed_group E₂] [(i : fin (Nat.succ n)) → normed_space 𝕜 (E i)] [normed_space 𝕜 E₂] (f : continuous_linear_map 𝕜 (E 0) (continuous_multilinear_map 𝕜 (fun (i : fin n) => E (fin.succ i)) E₂)) : norm (continuous_linear_map.uncurry_left f) = norm f := sorry /-- The space of continuous multilinear maps on `Π(i : fin (n+1)), E i` is canonically isomorphic to the space of continuous linear maps from `E 0` to the space of continuous multilinear maps on `Π(i : fin n), E i.succ `, by separating the first variable. We register this isomorphism as a linear isomorphism in `continuous_multilinear_curry_left_equiv_aux 𝕜 E E₂`. The algebraic version (without continuity assumption on the maps) is `multilinear_curry_left_equiv 𝕜 E E₂`, and the topological isomorphism (registering additionally that the isomorphism is continuous) is `continuous_multilinear_curry_left_equiv 𝕜 E E₂`. The direct and inverse maps are given by `f.uncurry_left` and `f.curry_left`. Use these unless you need the full framework of linear equivs. -/ def continuous_multilinear_curry_left_equiv_aux (𝕜 : Type u) {n : ℕ} (E : fin (Nat.succ n) → Type w) (E₂ : Type w₂) [nondiscrete_normed_field 𝕜] [(i : fin (Nat.succ n)) → normed_group (E i)] [normed_group E₂] [(i : fin (Nat.succ n)) → normed_space 𝕜 (E i)] [normed_space 𝕜 E₂] : linear_equiv 𝕜 (continuous_linear_map 𝕜 (E 0) (continuous_multilinear_map 𝕜 (fun (i : fin n) => E (fin.succ i)) E₂)) (continuous_multilinear_map 𝕜 E E₂) := linear_equiv.mk continuous_linear_map.uncurry_left sorry sorry continuous_multilinear_map.curry_left continuous_linear_map.curry_uncurry_left sorry /-- The space of continuous multilinear maps on `Π(i : fin (n+1)), E i` is canonically isomorphic to the space of continuous linear maps from `E 0` to the space of continuous multilinear maps on `Π(i : fin n), E i.succ `, by separating the first variable. We register this isomorphism in `continuous_multilinear_curry_left_equiv 𝕜 E E₂`. The algebraic version (without topology) is given in `multilinear_curry_left_equiv 𝕜 E E₂`. The direct and inverse maps are given by `f.uncurry_left` and `f.curry_left`. Use these unless you need the full framework of continuous linear equivs. -/ def continuous_multilinear_curry_left_equiv (𝕜 : Type u) {n : ℕ} (E : fin (Nat.succ n) → Type w) (E₂ : Type w₂) [nondiscrete_normed_field 𝕜] [(i : fin (Nat.succ n)) → normed_group (E i)] [normed_group E₂] [(i : fin (Nat.succ n)) → normed_space 𝕜 (E i)] [normed_space 𝕜 E₂] : continuous_linear_equiv 𝕜 (continuous_linear_map 𝕜 (E 0) (continuous_multilinear_map 𝕜 (fun (i : fin n) => E (fin.succ i)) E₂)) (continuous_multilinear_map 𝕜 E E₂) := continuous_linear_equiv.mk (linear_equiv.mk (linear_equiv.to_fun (continuous_multilinear_curry_left_equiv_aux 𝕜 E E₂)) sorry sorry (linear_equiv.inv_fun (continuous_multilinear_curry_left_equiv_aux 𝕜 E E₂)) sorry sorry) @[simp] theorem continuous_multilinear_curry_left_equiv_apply {𝕜 : Type u} {n : ℕ} {E : fin (Nat.succ n) → Type w} {E₂ : Type w₂} [nondiscrete_normed_field 𝕜] [(i : fin (Nat.succ n)) → normed_group (E i)] [normed_group E₂] [(i : fin (Nat.succ n)) → normed_space 𝕜 (E i)] [normed_space 𝕜 E₂] (f : continuous_linear_map 𝕜 (E 0) (continuous_multilinear_map 𝕜 (fun (i : fin n) => E (fin.succ i)) E₂)) (v : (i : fin (Nat.succ n)) → E i) : coe_fn (coe_fn (continuous_multilinear_curry_left_equiv 𝕜 E E₂) f) v = coe_fn (coe_fn f (v 0)) (fin.tail v) := rfl @[simp] theorem continuous_multilinear_curry_left_equiv_symm_apply {𝕜 : Type u} {n : ℕ} {E : fin (Nat.succ n) → Type w} {E₂ : Type w₂} [nondiscrete_normed_field 𝕜] [(i : fin (Nat.succ n)) → normed_group (E i)] [normed_group E₂] [(i : fin (Nat.succ n)) → normed_space 𝕜 (E i)] [normed_space 𝕜 E₂] (f : continuous_multilinear_map 𝕜 E E₂) (x : E 0) (v : (i : fin n) → E (fin.succ i)) : coe_fn (coe_fn (coe_fn (continuous_linear_equiv.symm (continuous_multilinear_curry_left_equiv 𝕜 E E₂)) f) x) v = coe_fn f (fin.cons x v) := rfl /-! #### Right currying -/ /-- Given a continuous linear map `f` from continuous multilinear maps on `n` variables to continuous linear maps on `E 0`, construct the corresponding continuous multilinear map on `n+1` variables obtained by concatenating the variables, given by `m ↦ f (init m) (m (last n))`. -/ def continuous_multilinear_map.uncurry_right {𝕜 : Type u} {n : ℕ} {E : fin (Nat.succ n) → Type w} {E₂ : Type w₂} [nondiscrete_normed_field 𝕜] [(i : fin (Nat.succ n)) → normed_group (E i)] [normed_group E₂] [(i : fin (Nat.succ n)) → normed_space 𝕜 (E i)] [normed_space 𝕜 E₂] (f : continuous_multilinear_map 𝕜 (fun (i : fin n) => E (coe_fn fin.cast_succ i)) (continuous_linear_map 𝕜 (E (fin.last n)) E₂)) : continuous_multilinear_map 𝕜 E E₂ := let f' : multilinear_map 𝕜 (fun (i : fin n) => E (coe_fn fin.cast_succ i)) (linear_map 𝕜 (E (fin.last n)) E₂) := multilinear_map.mk (fun (m : (i : fin n) → E (coe_fn fin.cast_succ i)) => continuous_linear_map.to_linear_map (coe_fn f m)) sorry sorry; multilinear_map.mk_continuous (multilinear_map.uncurry_right f') (norm f) sorry @[simp] theorem continuous_multilinear_map.uncurry_right_apply {𝕜 : Type u} {n : ℕ} {E : fin (Nat.succ n) → Type w} {E₂ : Type w₂} [nondiscrete_normed_field 𝕜] [(i : fin (Nat.succ n)) → normed_group (E i)] [normed_group E₂] [(i : fin (Nat.succ n)) → normed_space 𝕜 (E i)] [normed_space 𝕜 E₂] (f : continuous_multilinear_map 𝕜 (fun (i : fin n) => E (coe_fn fin.cast_succ i)) (continuous_linear_map 𝕜 (E (fin.last n)) E₂)) (m : (i : fin (Nat.succ n)) → E i) : coe_fn (continuous_multilinear_map.uncurry_right f) m = coe_fn (coe_fn f (fin.init m)) (m (fin.last n)) := rfl /-- Given a continuous multilinear map `f` in `n+1` variables, split the last variable to obtain a continuous multilinear map in `n` variables into continuous linear maps, given by `m ↦ (x ↦ f (snoc m x))`. -/ def continuous_multilinear_map.curry_right {𝕜 : Type u} {n : ℕ} {E : fin (Nat.succ n) → Type w} {E₂ : Type w₂} [nondiscrete_normed_field 𝕜] [(i : fin (Nat.succ n)) → normed_group (E i)] [normed_group E₂] [(i : fin (Nat.succ n)) → normed_space 𝕜 (E i)] [normed_space 𝕜 E₂] (f : continuous_multilinear_map 𝕜 E E₂) : continuous_multilinear_map 𝕜 (fun (i : fin n) => E (coe_fn fin.cast_succ i)) (continuous_linear_map 𝕜 (E (fin.last n)) E₂) := let f' : multilinear_map 𝕜 (fun (i : fin n) => E (coe_fn fin.cast_succ i)) (continuous_linear_map 𝕜 (E (fin.last n)) E₂) := multilinear_map.mk (fun (m : (i : fin n) → E (coe_fn fin.cast_succ i)) => linear_map.mk_continuous (coe_fn (multilinear_map.curry_right (continuous_multilinear_map.to_multilinear_map f)) m) (norm f * finset.prod finset.univ fun (i : fin n) => norm (m i)) sorry) sorry sorry; multilinear_map.mk_continuous f' (norm f) sorry @[simp] theorem continuous_multilinear_map.curry_right_apply {𝕜 : Type u} {n : ℕ} {E : fin (Nat.succ n) → Type w} {E₂ : Type w₂} [nondiscrete_normed_field 𝕜] [(i : fin (Nat.succ n)) → normed_group (E i)] [normed_group E₂] [(i : fin (Nat.succ n)) → normed_space 𝕜 (E i)] [normed_space 𝕜 E₂] (f : continuous_multilinear_map 𝕜 E E₂) (m : (i : fin n) → E (coe_fn fin.cast_succ i)) (x : E (fin.last n)) : coe_fn (coe_fn (continuous_multilinear_map.curry_right f) m) x = coe_fn f (fin.snoc m x) := rfl @[simp] theorem continuous_multilinear_map.curry_uncurry_right {𝕜 : Type u} {n : ℕ} {E : fin (Nat.succ n) → Type w} {E₂ : Type w₂} [nondiscrete_normed_field 𝕜] [(i : fin (Nat.succ n)) → normed_group (E i)] [normed_group E₂] [(i : fin (Nat.succ n)) → normed_space 𝕜 (E i)] [normed_space 𝕜 E₂] (f : continuous_multilinear_map 𝕜 (fun (i : fin n) => E (coe_fn fin.cast_succ i)) (continuous_linear_map 𝕜 (E (fin.last n)) E₂)) : continuous_multilinear_map.curry_right (continuous_multilinear_map.uncurry_right f) = f := sorry @[simp] theorem continuous_multilinear_map.uncurry_curry_right {𝕜 : Type u} {n : ℕ} {E : fin (Nat.succ n) → Type w} {E₂ : Type w₂} [nondiscrete_normed_field 𝕜] [(i : fin (Nat.succ n)) → normed_group (E i)] [normed_group E₂] [(i : fin (Nat.succ n)) → normed_space 𝕜 (E i)] [normed_space 𝕜 E₂] (f : continuous_multilinear_map 𝕜 E E₂) : continuous_multilinear_map.uncurry_right (continuous_multilinear_map.curry_right f) = f := sorry @[simp] theorem continuous_multilinear_map.curry_right_norm {𝕜 : Type u} {n : ℕ} {E : fin (Nat.succ n) → Type w} {E₂ : Type w₂} [nondiscrete_normed_field 𝕜] [(i : fin (Nat.succ n)) → normed_group (E i)] [normed_group E₂] [(i : fin (Nat.succ n)) → normed_space 𝕜 (E i)] [normed_space 𝕜 E₂] (f : continuous_multilinear_map 𝕜 E E₂) : norm (continuous_multilinear_map.curry_right f) = norm f := sorry @[simp] theorem continuous_multilinear_map.uncurry_right_norm {𝕜 : Type u} {n : ℕ} {E : fin (Nat.succ n) → Type w} {E₂ : Type w₂} [nondiscrete_normed_field 𝕜] [(i : fin (Nat.succ n)) → normed_group (E i)] [normed_group E₂] [(i : fin (Nat.succ n)) → normed_space 𝕜 (E i)] [normed_space 𝕜 E₂] (f : continuous_multilinear_map 𝕜 (fun (i : fin n) => E (coe_fn fin.cast_succ i)) (continuous_linear_map 𝕜 (E (fin.last n)) E₂)) : norm (continuous_multilinear_map.uncurry_right f) = norm f := sorry /-- The space of continuous multilinear maps on `Π(i : fin (n+1)), E i` is canonically isomorphic to the space of continuous multilinear maps on `Π(i : fin n), E i.cast_succ` with values in the space of continuous linear maps on `E (last n)`, by separating the last variable. We register this isomorphism as a linear equiv in `continuous_multilinear_curry_right_equiv_aux 𝕜 E E₂`. The algebraic version (without continuity assumption on the maps) is `multilinear_curry_right_equiv 𝕜 E E₂`, and the topological isomorphism (registering additionally that the isomorphism is continuous) is `continuous_multilinear_curry_right_equiv 𝕜 E E₂`. The direct and inverse maps are given by `f.uncurry_right` and `f.curry_right`. Use these unless you need the full framework of linear equivs. -/ def continuous_multilinear_curry_right_equiv_aux (𝕜 : Type u) {n : ℕ} (E : fin (Nat.succ n) → Type w) (E₂ : Type w₂) [nondiscrete_normed_field 𝕜] [(i : fin (Nat.succ n)) → normed_group (E i)] [normed_group E₂] [(i : fin (Nat.succ n)) → normed_space 𝕜 (E i)] [normed_space 𝕜 E₂] : linear_equiv 𝕜 (continuous_multilinear_map 𝕜 (fun (i : fin n) => E (coe_fn fin.cast_succ i)) (continuous_linear_map 𝕜 (E (fin.last n)) E₂)) (continuous_multilinear_map 𝕜 E E₂) := linear_equiv.mk continuous_multilinear_map.uncurry_right sorry sorry continuous_multilinear_map.curry_right continuous_multilinear_map.curry_uncurry_right sorry /-- The space of continuous multilinear maps on `Π(i : fin (n+1)), E i` is canonically isomorphic to the space of continuous multilinear maps on `Π(i : fin n), E i.cast_succ` with values in the space of continuous linear maps on `E (last n)`, by separating the last variable. We register this isomorphism as a continuous linear equiv in `continuous_multilinear_curry_right_equiv 𝕜 E E₂`. The algebraic version (without topology) is given in `multilinear_curry_right_equiv 𝕜 E E₂`. The direct and inverse maps are given by `f.uncurry_right` and `f.curry_right`. Use these unless you need the full framework of continuous linear equivs. -/ def continuous_multilinear_curry_right_equiv (𝕜 : Type u) {n : ℕ} (E : fin (Nat.succ n) → Type w) (E₂ : Type w₂) [nondiscrete_normed_field 𝕜] [(i : fin (Nat.succ n)) → normed_group (E i)] [normed_group E₂] [(i : fin (Nat.succ n)) → normed_space 𝕜 (E i)] [normed_space 𝕜 E₂] : continuous_linear_equiv 𝕜 (continuous_multilinear_map 𝕜 (fun (i : fin n) => E (coe_fn fin.cast_succ i)) (continuous_linear_map 𝕜 (E (fin.last n)) E₂)) (continuous_multilinear_map 𝕜 E E₂) := continuous_linear_equiv.mk (linear_equiv.mk (linear_equiv.to_fun (continuous_multilinear_curry_right_equiv_aux 𝕜 E E₂)) sorry sorry (linear_equiv.inv_fun (continuous_multilinear_curry_right_equiv_aux 𝕜 E E₂)) sorry sorry) /-- The space of continuous multilinear maps on `Π(i : fin (n+1)), G` is canonically isomorphic to the space of continuous multilinear maps on `Π(i : fin n), G` with values in the space of continuous linear maps on `G`, by separating the last variable. We register this isomorphism as a continuous linear equiv in `continuous_multilinear_curry_right_equiv' 𝕜 n G E₂`. For a version allowing dependent types, see `continuous_multilinear_curry_right_equiv`. When there are no dependent types, use the primed version as it helps Lean a lot for unification. The direct and inverse maps are given by `f.uncurry_right` and `f.curry_right`. Use these unless you need the full framework of continuous linear equivs. -/ def continuous_multilinear_curry_right_equiv' (𝕜 : Type u) (n : ℕ) (G : Type wG) (E₂ : Type w₂) [nondiscrete_normed_field 𝕜] [normed_group G] [normed_group E₂] [normed_space 𝕜 G] [normed_space 𝕜 E₂] : continuous_linear_equiv 𝕜 (continuous_multilinear_map 𝕜 (fun (i : fin n) => G) (continuous_linear_map 𝕜 G E₂)) (continuous_multilinear_map 𝕜 (fun (i : fin (Nat.succ n)) => G) E₂) := continuous_multilinear_curry_right_equiv 𝕜 (fun (i : fin (Nat.succ n)) => G) E₂ @[simp] theorem continuous_multilinear_curry_right_equiv_apply {𝕜 : Type u} {n : ℕ} {E : fin (Nat.succ n) → Type w} {E₂ : Type w₂} [nondiscrete_normed_field 𝕜] [(i : fin (Nat.succ n)) → normed_group (E i)] [normed_group E₂] [(i : fin (Nat.succ n)) → normed_space 𝕜 (E i)] [normed_space 𝕜 E₂] (f : continuous_multilinear_map 𝕜 (fun (i : fin n) => E (coe_fn fin.cast_succ i)) (continuous_linear_map 𝕜 (E (fin.last n)) E₂)) (v : (i : fin (Nat.succ n)) → E i) : coe_fn (coe_fn (continuous_multilinear_curry_right_equiv 𝕜 E E₂) f) v = coe_fn (coe_fn f (fin.init v)) (v (fin.last n)) := rfl @[simp] theorem continuous_multilinear_curry_right_equiv_symm_apply {𝕜 : Type u} {n : ℕ} {E : fin (Nat.succ n) → Type w} {E₂ : Type w₂} [nondiscrete_normed_field 𝕜] [(i : fin (Nat.succ n)) → normed_group (E i)] [normed_group E₂] [(i : fin (Nat.succ n)) → normed_space 𝕜 (E i)] [normed_space 𝕜 E₂] (f : continuous_multilinear_map 𝕜 E E₂) (v : (i : fin n) → E (coe_fn fin.cast_succ i)) (x : E (fin.last n)) : coe_fn (coe_fn (coe_fn (continuous_linear_equiv.symm (continuous_multilinear_curry_right_equiv 𝕜 E E₂)) f) v) x = coe_fn f (fin.snoc v x) := rfl @[simp] theorem continuous_multilinear_curry_right_equiv_apply' {𝕜 : Type u} {n : ℕ} {G : Type wG} {E₂ : Type w₂} [nondiscrete_normed_field 𝕜] [normed_group G] [normed_group E₂] [normed_space 𝕜 G] [normed_space 𝕜 E₂] (f : continuous_multilinear_map 𝕜 (fun (i : fin n) => G) (continuous_linear_map 𝕜 G E₂)) (v : fin (Nat.succ n) → G) : coe_fn (coe_fn (continuous_multilinear_curry_right_equiv' 𝕜 n G E₂) f) v = coe_fn (coe_fn f (fin.init v)) (v (fin.last n)) := rfl @[simp] theorem continuous_multilinear_curry_right_equiv_symm_apply' {𝕜 : Type u} {n : ℕ} {G : Type wG} {E₂ : Type w₂} [nondiscrete_normed_field 𝕜] [normed_group G] [normed_group E₂] [normed_space 𝕜 G] [normed_space 𝕜 E₂] (f : continuous_multilinear_map 𝕜 (fun (i : fin (Nat.succ n)) => G) E₂) (v : fin n → G) (x : G) : coe_fn (coe_fn (coe_fn (continuous_linear_equiv.symm (continuous_multilinear_curry_right_equiv' 𝕜 n G E₂)) f) v) x = coe_fn f (fin.snoc v x) := rfl /-! #### Currying with `0` variables The space of multilinear maps with `0` variables is trivial: such a multilinear map is just an arbitrary constant (note that multilinear maps in `0` variables need not map `0` to `0`!). Therefore, the space of continuous multilinear maps on `(fin 0) → G` with values in `E₂` is isomorphic (and even isometric) to `E₂`. As this is the zeroth step in the construction of iterated derivatives, we register this isomorphism. -/ /-- Associating to a continuous multilinear map in `0` variables the unique value it takes. -/ def continuous_multilinear_map.uncurry0 {𝕜 : Type u} {G : Type wG} {E₂ : Type w₂} [nondiscrete_normed_field 𝕜] [normed_group G] [normed_group E₂] [normed_space 𝕜 G] [normed_space 𝕜 E₂] (f : continuous_multilinear_map 𝕜 (fun (i : fin 0) => G) E₂) : E₂ := coe_fn f 0 /-- Associating to an element `x` of a vector space `E₂` the continuous multilinear map in `0` variables taking the (unique) value `x` -/ def continuous_multilinear_map.curry0 (𝕜 : Type u) (G : Type wG) {E₂ : Type w₂} [nondiscrete_normed_field 𝕜] [normed_group G] [normed_group E₂] [normed_space 𝕜 G] [normed_space 𝕜 E₂] (x : E₂) : continuous_multilinear_map 𝕜 (fun (i : fin 0) => G) E₂ := continuous_multilinear_map.mk (multilinear_map.mk (fun (m : fin 0 → G) => x) sorry sorry) sorry @[simp] theorem continuous_multilinear_map.curry0_apply (𝕜 : Type u) {G : Type wG} {E₂ : Type w₂} [nondiscrete_normed_field 𝕜] [normed_group G] [normed_group E₂] [normed_space 𝕜 G] [normed_space 𝕜 E₂] (x : E₂) (m : fin 0 → G) : coe_fn (continuous_multilinear_map.curry0 𝕜 G x) m = x := rfl @[simp] theorem continuous_multilinear_map.uncurry0_apply {𝕜 : Type u} {G : Type wG} {E₂ : Type w₂} [nondiscrete_normed_field 𝕜] [normed_group G] [normed_group E₂] [normed_space 𝕜 G] [normed_space 𝕜 E₂] (f : continuous_multilinear_map 𝕜 (fun (i : fin 0) => G) E₂) : continuous_multilinear_map.uncurry0 f = coe_fn f 0 := rfl @[simp] theorem continuous_multilinear_map.apply_zero_curry0 {𝕜 : Type u} {G : Type wG} {E₂ : Type w₂} [nondiscrete_normed_field 𝕜] [normed_group G] [normed_group E₂] [normed_space 𝕜 G] [normed_space 𝕜 E₂] (f : continuous_multilinear_map 𝕜 (fun (i : fin 0) => G) E₂) {x : fin 0 → G} : continuous_multilinear_map.curry0 𝕜 G (coe_fn f x) = f := sorry theorem continuous_multilinear_map.uncurry0_curry0 {𝕜 : Type u} {G : Type wG} {E₂ : Type w₂} [nondiscrete_normed_field 𝕜] [normed_group G] [normed_group E₂] [normed_space 𝕜 G] [normed_space 𝕜 E₂] (f : continuous_multilinear_map 𝕜 (fun (i : fin 0) => G) E₂) : continuous_multilinear_map.curry0 𝕜 G (continuous_multilinear_map.uncurry0 f) = f := sorry @[simp] theorem continuous_multilinear_map.curry0_uncurry0 (𝕜 : Type u) (G : Type wG) {E₂ : Type w₂} [nondiscrete_normed_field 𝕜] [normed_group G] [normed_group E₂] [normed_space 𝕜 G] [normed_space 𝕜 E₂] (x : E₂) : continuous_multilinear_map.uncurry0 (continuous_multilinear_map.curry0 𝕜 G x) = x := rfl @[simp] theorem continuous_multilinear_map.uncurry0_norm (𝕜 : Type u) (G : Type wG) {E₂ : Type w₂} [nondiscrete_normed_field 𝕜] [normed_group G] [normed_group E₂] [normed_space 𝕜 G] [normed_space 𝕜 E₂] (x : E₂) : norm (continuous_multilinear_map.curry0 𝕜 G x) = norm x := sorry @[simp] theorem continuous_multilinear_map.fin0_apply_norm {𝕜 : Type u} {G : Type wG} {E₂ : Type w₂} [nondiscrete_normed_field 𝕜] [normed_group G] [normed_group E₂] [normed_space 𝕜 G] [normed_space 𝕜 E₂] (f : continuous_multilinear_map 𝕜 (fun (i : fin 0) => G) E₂) {x : fin 0 → G} : norm (coe_fn f x) = norm f := sorry theorem continuous_multilinear_map.curry0_norm {𝕜 : Type u} {G : Type wG} {E₂ : Type w₂} [nondiscrete_normed_field 𝕜] [normed_group G] [normed_group E₂] [normed_space 𝕜 G] [normed_space 𝕜 E₂] (f : continuous_multilinear_map 𝕜 (fun (i : fin 0) => G) E₂) : norm (continuous_multilinear_map.uncurry0 f) = norm f := sorry /-- The linear isomorphism between elements of a normed space, and continuous multilinear maps in `0` variables with values in this normed space. The continuous version is given in `continuous_multilinear_curry_fin0`. The direct and inverse maps are `uncurry0` and `curry0`. Use these unless you need the full framework of linear equivs. -/ def continuous_multilinear_curry_fin0_aux (𝕜 : Type u) (G : Type wG) (E₂ : Type w₂) [nondiscrete_normed_field 𝕜] [normed_group G] [normed_group E₂] [normed_space 𝕜 G] [normed_space 𝕜 E₂] : linear_equiv 𝕜 (continuous_multilinear_map 𝕜 (fun (i : fin 0) => G) E₂) E₂ := linear_equiv.mk (fun (f : continuous_multilinear_map 𝕜 (fun (i : fin 0) => G) E₂) => continuous_multilinear_map.uncurry0 f) sorry sorry (fun (f : E₂) => continuous_multilinear_map.curry0 𝕜 G f) continuous_multilinear_map.uncurry0_curry0 (continuous_multilinear_map.curry0_uncurry0 𝕜 G) /-- The continuous linear isomorphism between elements of a normed space, and continuous multilinear maps in `0` variables with values in this normed space. The direct and inverse maps are `uncurry0` and `curry0`. Use these unless you need the full framework of continuous linear equivs. -/ def continuous_multilinear_curry_fin0 (𝕜 : Type u) (G : Type wG) (E₂ : Type w₂) [nondiscrete_normed_field 𝕜] [normed_group G] [normed_group E₂] [normed_space 𝕜 G] [normed_space 𝕜 E₂] : continuous_linear_equiv 𝕜 (continuous_multilinear_map 𝕜 (fun (i : fin 0) => G) E₂) E₂ := continuous_linear_equiv.mk (linear_equiv.mk (linear_equiv.to_fun (continuous_multilinear_curry_fin0_aux 𝕜 G E₂)) sorry sorry (linear_equiv.inv_fun (continuous_multilinear_curry_fin0_aux 𝕜 G E₂)) sorry sorry) @[simp] theorem continuous_multilinear_curry_fin0_apply {𝕜 : Type u} {G : Type wG} {E₂ : Type w₂} [nondiscrete_normed_field 𝕜] [normed_group G] [normed_group E₂] [normed_space 𝕜 G] [normed_space 𝕜 E₂] (f : continuous_multilinear_map 𝕜 (fun (i : fin 0) => G) E₂) : coe_fn (continuous_multilinear_curry_fin0 𝕜 G E₂) f = coe_fn f 0 := rfl @[simp] theorem continuous_multilinear_curry_fin0_symm_apply {𝕜 : Type u} {G : Type wG} {E₂ : Type w₂} [nondiscrete_normed_field 𝕜] [normed_group G] [normed_group E₂] [normed_space 𝕜 G] [normed_space 𝕜 E₂] (x : E₂) (v : fin 0 → G) : coe_fn (coe_fn (continuous_linear_equiv.symm (continuous_multilinear_curry_fin0 𝕜 G E₂)) x) v = x := rfl /-! #### With 1 variable -/ /-- Continuous multilinear maps from `G^1` to `E₂` are isomorphic with continuous linear maps from `G` to `E₂`. -/ def continuous_multilinear_curry_fin1 (𝕜 : Type u) (G : Type wG) (E₂ : Type w₂) [nondiscrete_normed_field 𝕜] [normed_group G] [normed_group E₂] [normed_space 𝕜 G] [normed_space 𝕜 E₂] : continuous_linear_equiv 𝕜 (continuous_multilinear_map 𝕜 (fun (i : fin 1) => G) E₂) (continuous_linear_map 𝕜 G E₂) := continuous_linear_equiv.trans (continuous_linear_equiv.symm (continuous_multilinear_curry_right_equiv 𝕜 (fun (i : fin 1) => G) E₂)) (continuous_multilinear_curry_fin0 𝕜 G (continuous_linear_map 𝕜 G E₂)) @[simp] theorem continuous_multilinear_curry_fin1_apply {𝕜 : Type u} {G : Type wG} {E₂ : Type w₂} [nondiscrete_normed_field 𝕜] [normed_group G] [normed_group E₂] [normed_space 𝕜 G] [normed_space 𝕜 E₂] (f : continuous_multilinear_map 𝕜 (fun (i : fin 1) => G) E₂) (x : G) : coe_fn (coe_fn (continuous_multilinear_curry_fin1 𝕜 G E₂) f) x = coe_fn f (fin.snoc 0 x) := rfl @[simp] theorem continuous_multilinear_curry_fin1_symm_apply {𝕜 : Type u} {G : Type wG} {E₂ : Type w₂} [nondiscrete_normed_field 𝕜] [normed_group G] [normed_group E₂] [normed_space 𝕜 G] [normed_space 𝕜 E₂] (f : continuous_linear_map 𝕜 G E₂) (v : fin 1 → G) : coe_fn (coe_fn (continuous_linear_equiv.symm (continuous_multilinear_curry_fin1 𝕜 G E₂)) f) v = coe_fn f (v 0) := rfl
fc57dfae34fa5b177f9c2651903898a085870dec
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/interactive/complete_tactic.lean
c71884676b0241d9569febac1fd65d9e5648dc46
[ "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
175
lean
example := by assumption --^ "command": "complete", "skip_completions": true example := begin --^ "command": "complete", "skip_completions": true
04ce2feae3523f77bddd4abfebd4ecf382a82484
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/ring_theory/algebraic_independent.lean
e6dbfbfd6aaaae83b9036c26a47886c94ac58464
[ "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
21,998
lean
/- Copyright (c) 2021 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import ring_theory.adjoin.basic import linear_algebra.linear_independent import ring_theory.mv_polynomial.basic import data.mv_polynomial.supported import ring_theory.algebraic import data.mv_polynomial.equiv /-! # Algebraic Independence > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines algebraic independence of a family of element of an `R` algebra ## Main definitions * `algebraic_independent` - `algebraic_independent R x` states the family of elements `x` is algebraically independent over `R`, meaning that the canonical map out of the multivariable polynomial ring is injective. * `algebraic_independent.repr` - The canonical map from the subalgebra generated by an algebraic independent family into the polynomial ring. ## References * [Stacks: Transcendence](https://stacks.math.columbia.edu/tag/030D) ## TODO Prove that a ring is an algebraic extension of the subalgebra generated by a transcendence basis. ## Tags transcendence basis, transcendence degree, transcendence -/ noncomputable theory open function set subalgebra mv_polynomial algebra open_locale classical big_operators universes x u v w variables {ι : Type*} {ι' : Type*} (R : Type*) {K : Type*} variables {A : Type*} {A' A'' : Type*} {V : Type u} {V' : Type*} variables (x : ι → A) variables [comm_ring R] [comm_ring A] [comm_ring A'] [comm_ring A''] variables [algebra R A] [algebra R A'] [algebra R A''] variables {a b : R} /-- `algebraic_independent R x` states the family of elements `x` is algebraically independent over `R`, meaning that the canonical map out of the multivariable polynomial ring is injective. -/ def algebraic_independent : Prop := injective (mv_polynomial.aeval x : mv_polynomial ι R →ₐ[R] A) variables {R} {x} theorem algebraic_independent_iff_ker_eq_bot : algebraic_independent R x ↔ (mv_polynomial.aeval x : mv_polynomial ι R →ₐ[R] A).to_ring_hom.ker = ⊥ := ring_hom.injective_iff_ker_eq_bot _ theorem algebraic_independent_iff : algebraic_independent R x ↔ ∀p : mv_polynomial ι R, mv_polynomial.aeval (x : ι → A) p = 0 → p = 0 := injective_iff_map_eq_zero _ theorem algebraic_independent.eq_zero_of_aeval_eq_zero (h : algebraic_independent R x) : ∀p : mv_polynomial ι R, mv_polynomial.aeval (x : ι → A) p = 0 → p = 0 := algebraic_independent_iff.1 h theorem algebraic_independent_iff_injective_aeval : algebraic_independent R x ↔ injective (mv_polynomial.aeval x : mv_polynomial ι R →ₐ[R] A) := iff.rfl @[simp] lemma algebraic_independent_empty_type_iff [is_empty ι] : algebraic_independent R x ↔ injective (algebra_map R A) := have aeval x = (algebra.of_id R A).comp (@is_empty_alg_equiv R ι _ _).to_alg_hom, by { ext i, exact is_empty.elim' ‹is_empty ι› i }, begin rw [algebraic_independent, this, ← injective.of_comp_iff' _ (@is_empty_alg_equiv R ι _ _).bijective], refl end namespace algebraic_independent variables (hx : algebraic_independent R x) include hx lemma algebra_map_injective : injective (algebra_map R A) := by simpa [← mv_polynomial.algebra_map_eq, function.comp] using (injective.of_comp_iff (algebraic_independent_iff_injective_aeval.1 hx) (mv_polynomial.C)).2 (mv_polynomial.C_injective _ _) lemma linear_independent : linear_independent R x := begin rw [linear_independent_iff_injective_total], have : finsupp.total ι A R x = (mv_polynomial.aeval x).to_linear_map.comp (finsupp.total ι _ R X), { ext, simp }, rw this, refine hx.comp _, rw [← linear_independent_iff_injective_total], exact linear_independent_X _ _ end protected lemma injective [nontrivial R] : injective x := hx.linear_independent.injective lemma ne_zero [nontrivial R] (i : ι) : x i ≠ 0 := hx.linear_independent.ne_zero i lemma comp (f : ι' → ι) (hf : function.injective f) : algebraic_independent R (x ∘ f) := λ p q, by simpa [aeval_rename, (rename_injective f hf).eq_iff] using @hx (rename f p) (rename f q) lemma coe_range : algebraic_independent R (coe : range x → A) := by simpa using hx.comp _ (range_splitting_injective x) lemma map {f : A →ₐ[R] A'} (hf_inj : set.inj_on f (adjoin R (range x))) : algebraic_independent R (f ∘ x) := have aeval (f ∘ x) = f.comp (aeval x), by ext; simp, have h : ∀ p : mv_polynomial ι R, aeval x p ∈ (@aeval R _ _ _ _ _ (coe : range x → A)).range, { intro p, rw [alg_hom.mem_range], refine ⟨mv_polynomial.rename (cod_restrict x (range x) (mem_range_self)) p, _⟩, simp [function.comp, aeval_rename] }, begin intros x y hxy, rw [this] at hxy, rw [adjoin_eq_range] at hf_inj, exact hx (hf_inj (h x) (h y) hxy) end lemma map' {f : A →ₐ[R] A'} (hf_inj : injective f) : algebraic_independent R (f ∘ x) := hx.map (inj_on_of_injective hf_inj _) omit hx lemma of_comp (f : A →ₐ[R] A') (hfv : algebraic_independent R (f ∘ x)) : algebraic_independent R x := have aeval (f ∘ x) = f.comp (aeval x), by ext; simp, by rw [algebraic_independent, this] at hfv; exact hfv.of_comp end algebraic_independent open algebraic_independent lemma alg_hom.algebraic_independent_iff (f : A →ₐ[R] A') (hf : injective f) : algebraic_independent R (f ∘ x) ↔ algebraic_independent R x := ⟨λ h, h.of_comp f, λ h, h.map (inj_on_of_injective hf _)⟩ @[nontriviality] lemma algebraic_independent_of_subsingleton [subsingleton R] : algebraic_independent R x := algebraic_independent_iff.2 (λ l hl, subsingleton.elim _ _) theorem algebraic_independent_equiv (e : ι ≃ ι') {f : ι' → A} : algebraic_independent R (f ∘ e) ↔ algebraic_independent R f := ⟨λ h, function.comp.right_id f ▸ e.self_comp_symm ▸ h.comp _ e.symm.injective, λ h, h.comp _ e.injective⟩ theorem algebraic_independent_equiv' (e : ι ≃ ι') {f : ι' → A} {g : ι → A} (h : f ∘ e = g) : algebraic_independent R g ↔ algebraic_independent R f := h ▸ algebraic_independent_equiv e theorem algebraic_independent_subtype_range {ι} {f : ι → A} (hf : injective f) : algebraic_independent R (coe : range f → A) ↔ algebraic_independent R f := iff.symm $ algebraic_independent_equiv' (equiv.of_injective f hf) rfl alias algebraic_independent_subtype_range ↔ algebraic_independent.of_subtype_range _ theorem algebraic_independent_image {ι} {s : set ι} {f : ι → A} (hf : set.inj_on f s) : algebraic_independent R (λ x : s, f x) ↔ algebraic_independent R (λ x : f '' s, (x : A)) := algebraic_independent_equiv' (equiv.set.image_of_inj_on _ _ hf) rfl lemma algebraic_independent_adjoin (hs : algebraic_independent R x) : @algebraic_independent ι R (adjoin R (range x)) (λ i : ι, ⟨x i, subset_adjoin (mem_range_self i)⟩) _ _ _ := algebraic_independent.of_comp (adjoin R (range x)).val hs /-- A set of algebraically independent elements in an algebra `A` over a ring `K` is also algebraically independent over a subring `R` of `K`. -/ lemma algebraic_independent.restrict_scalars {K : Type*} [comm_ring K] [algebra R K] [algebra K A] [is_scalar_tower R K A] (hinj : function.injective (algebra_map R K)) (ai : algebraic_independent K x) : algebraic_independent R x := have (aeval x : mv_polynomial ι K →ₐ[K] A).to_ring_hom.comp (mv_polynomial.map (algebra_map R K)) = (aeval x : mv_polynomial ι R →ₐ[R] A).to_ring_hom, by { ext; simp [algebra_map_eq_smul_one] }, begin show injective (aeval x).to_ring_hom, rw [← this], exact injective.comp ai (mv_polynomial.map_injective _ hinj) end /-- Every finite subset of an algebraically independent set is algebraically independent. -/ lemma algebraic_independent_finset_map_embedding_subtype (s : set A) (li : algebraic_independent R (coe : s → A)) (t : finset s) : algebraic_independent R (coe : (finset.map (embedding.subtype s) t) → A) := begin let f : t.map (embedding.subtype s) → s := λ x, ⟨x.1, begin obtain ⟨x, h⟩ := x, rw [finset.mem_map] at h, obtain ⟨a, ha, rfl⟩ := h, simp only [subtype.coe_prop, embedding.coe_subtype], end⟩, convert algebraic_independent.comp li f _, rintros ⟨x, hx⟩ ⟨y, hy⟩, rw [finset.mem_map] at hx hy, obtain ⟨a, ha, rfl⟩ := hx, obtain ⟨b, hb, rfl⟩ := hy, simp only [imp_self, subtype.mk_eq_mk], end /-- If every finite set of algebraically independent element has cardinality at most `n`, then the same is true for arbitrary sets of algebraically independent elements. -/ lemma algebraic_independent_bounded_of_finset_algebraic_independent_bounded {n : ℕ} (H : ∀ s : finset A, algebraic_independent R (λ i : s, (i : A)) → s.card ≤ n) : ∀ s : set A, algebraic_independent R (coe : s → A) → cardinal.mk s ≤ n := begin intros s li, apply cardinal.card_le_of, intro t, rw ← finset.card_map (embedding.subtype s), apply H, apply algebraic_independent_finset_map_embedding_subtype _ li, end section subtype lemma algebraic_independent.restrict_of_comp_subtype {s : set ι} (hs : algebraic_independent R (x ∘ coe : s → A)) : algebraic_independent R (s.restrict x) := hs variables (R A) lemma algebraic_independent_empty_iff : algebraic_independent R (λ x, x : (∅ : set A) → A) ↔ injective (algebra_map R A) := by simp variables {R A} lemma algebraic_independent.mono {t s : set A} (h : t ⊆ s) (hx : algebraic_independent R (λ x, x : s → A)) : algebraic_independent R (λ x, x : t → A) := by simpa [function.comp] using hx.comp (inclusion h) (inclusion_injective h) end subtype theorem algebraic_independent.to_subtype_range {ι} {f : ι → A} (hf : algebraic_independent R f) : algebraic_independent R (coe : range f → A) := begin nontriviality R, { rwa algebraic_independent_subtype_range hf.injective } end theorem algebraic_independent.to_subtype_range' {ι} {f : ι → A} (hf : algebraic_independent R f) {t} (ht : range f = t) : algebraic_independent R (coe : t → A) := ht ▸ hf.to_subtype_range theorem algebraic_independent_comp_subtype {s : set ι} : algebraic_independent R (x ∘ coe : s → A) ↔ ∀ p ∈ (mv_polynomial.supported R s), aeval x p = 0 → p = 0 := have (aeval (x ∘ coe : s → A) : _ →ₐ[R] _) = (aeval x).comp (rename coe), by ext; simp, have ∀ p : mv_polynomial s R, rename (coe : s → ι) p = 0 ↔ p = 0, from (injective_iff_map_eq_zero' (rename (coe : s → ι) : mv_polynomial s R →ₐ[R] _).to_ring_hom).1 (rename_injective _ subtype.val_injective), by simp [algebraic_independent_iff, supported_eq_range_rename, *] theorem algebraic_independent_subtype {s : set A} : algebraic_independent R (λ x, x : s → A) ↔ ∀ (p : mv_polynomial A R), p ∈ mv_polynomial.supported R s → aeval id p = 0 → p = 0 := by apply @algebraic_independent_comp_subtype _ _ _ id lemma algebraic_independent_of_finite (s : set A) (H : ∀ t ⊆ s, t.finite → algebraic_independent R (λ x, x : t → A)) : algebraic_independent R (λ x, x : s → A) := algebraic_independent_subtype.2 $ λ p hp, algebraic_independent_subtype.1 (H _ (mem_supported.1 hp) (finset.finite_to_set _)) _ (by simp) theorem algebraic_independent.image_of_comp {ι ι'} (s : set ι) (f : ι → ι') (g : ι' → A) (hs : algebraic_independent R (λ x : s, g (f x))) : algebraic_independent R (λ x : f '' s, g x) := begin nontriviality R, have : inj_on f s, from inj_on_iff_injective.2 hs.injective.of_comp, exact (algebraic_independent_equiv' (equiv.set.image_of_inj_on f s this) rfl).1 hs end theorem algebraic_independent.image {ι} {s : set ι} {f : ι → A} (hs : algebraic_independent R (λ x : s, f x)) : algebraic_independent R (λ x : f '' s, (x : A)) := by convert algebraic_independent.image_of_comp s f id hs lemma algebraic_independent_Union_of_directed {η : Type*} [nonempty η] {s : η → set A} (hs : directed (⊆) s) (h : ∀ i, algebraic_independent R (λ x, x : s i → A)) : algebraic_independent R (λ x, x : (⋃ i, s i) → A) := begin refine algebraic_independent_of_finite (⋃ i, s i) (λ t ht ft, _), rcases finite_subset_Union ft ht with ⟨I, fi, hI⟩, rcases hs.finset_le fi.to_finset with ⟨i, hi⟩, exact (h i).mono (subset.trans hI $ Union₂_subset $ λ j hj, hi j (fi.mem_to_finset.2 hj)) end lemma algebraic_independent_sUnion_of_directed {s : set (set A)} (hsn : s.nonempty) (hs : directed_on (⊆) s) (h : ∀ a ∈ s, algebraic_independent R (λ x, x : (a : set A) → A)) : algebraic_independent R (λ x, x : (⋃₀ s) → A) := by letI : nonempty s := nonempty.to_subtype hsn; rw sUnion_eq_Union; exact algebraic_independent_Union_of_directed hs.directed_coe (by simpa using h) lemma exists_maximal_algebraic_independent (s t : set A) (hst : s ⊆ t) (hs : algebraic_independent R (coe : s → A)) : ∃ u : set A, algebraic_independent R (coe : u → A) ∧ s ⊆ u ∧ u ⊆ t ∧ ∀ x : set A, algebraic_independent R (coe : x → A) → u ⊆ x → x ⊆ t → x = u := begin rcases zorn_subset_nonempty { u : set A | algebraic_independent R (coe : u → A) ∧ s ⊆ u ∧ u ⊆ t } (λ c hc chainc hcn, ⟨⋃₀ c, begin refine ⟨⟨algebraic_independent_sUnion_of_directed hcn chainc.directed_on (λ a ha, (hc ha).1), _, _⟩, _⟩, { cases hcn with x hx, exact subset_sUnion_of_subset _ x (hc hx).2.1 hx }, { exact sUnion_subset (λ x hx, (hc hx).2.2) }, { intros s, exact subset_sUnion_of_mem } end⟩) s ⟨hs, set.subset.refl s, hst⟩ with ⟨u, ⟨huai, hsu, hut⟩, hsu, hx⟩, use [u, huai, hsu, hut], intros x hxai huv hxt, exact hx _ ⟨hxai, trans hsu huv, hxt⟩ huv, end section repr variables (hx : algebraic_independent R x) /-- Canonical isomorphism between polynomials and the subalgebra generated by algebraically independent elements. -/ @[simps] def algebraic_independent.aeval_equiv (hx : algebraic_independent R x) : (mv_polynomial ι R) ≃ₐ[R] algebra.adjoin R (range x) := begin apply alg_equiv.of_bijective (alg_hom.cod_restrict (@aeval R A ι _ _ _ x) (algebra.adjoin R (range x)) _), swap, { intros x, rw [adjoin_range_eq_range_aeval], exact alg_hom.mem_range_self _ _ }, { split, { exact (alg_hom.injective_cod_restrict _ _ _).2 hx }, { rintros ⟨x, hx⟩, rw [adjoin_range_eq_range_aeval] at hx, rcases hx with ⟨y, rfl⟩, use y, ext, simp } } end @[simp] lemma algebraic_independent.algebra_map_aeval_equiv (hx : algebraic_independent R x) (p : mv_polynomial ι R) : algebra_map (algebra.adjoin R (range x)) A (hx.aeval_equiv p) = aeval x p := rfl /-- The canonical map from the subalgebra generated by an algebraic independent family into the polynomial ring. -/ def algebraic_independent.repr (hx : algebraic_independent R x) : algebra.adjoin R (range x) →ₐ[R] mv_polynomial ι R := hx.aeval_equiv.symm @[simp] lemma algebraic_independent.aeval_repr (p) : aeval x (hx.repr p) = p := subtype.ext_iff.1 (alg_equiv.apply_symm_apply hx.aeval_equiv p) lemma algebraic_independent.aeval_comp_repr : (aeval x).comp hx.repr = subalgebra.val _ := alg_hom.ext $ hx.aeval_repr lemma algebraic_independent.repr_ker : (hx.repr : adjoin R (range x) →+* mv_polynomial ι R).ker = ⊥ := (ring_hom.injective_iff_ker_eq_bot _).1 (alg_equiv.injective _) end repr -- TODO - make this an `alg_equiv` /-- The isomorphism between `mv_polynomial (option ι) R` and the polynomial ring over the algebra generated by an algebraically independent family. -/ def algebraic_independent.mv_polynomial_option_equiv_polynomial_adjoin (hx : algebraic_independent R x) : mv_polynomial (option ι) R ≃+* polynomial (adjoin R (set.range x)) := (mv_polynomial.option_equiv_left _ _).to_ring_equiv.trans (polynomial.map_equiv hx.aeval_equiv.to_ring_equiv) @[simp] lemma algebraic_independent.mv_polynomial_option_equiv_polynomial_adjoin_apply (hx : algebraic_independent R x) (y) : hx.mv_polynomial_option_equiv_polynomial_adjoin y = polynomial.map (hx.aeval_equiv : mv_polynomial ι R →+* adjoin R (range x)) (aeval (λ (o : option ι), o.elim polynomial.X (λ (s : ι), polynomial.C (X s))) y) := rfl @[simp] lemma algebraic_independent.mv_polynomial_option_equiv_polynomial_adjoin_C (hx : algebraic_independent R x) (r) : hx.mv_polynomial_option_equiv_polynomial_adjoin (C r) = polynomial.C (algebra_map _ _ r) := begin rw [algebraic_independent.mv_polynomial_option_equiv_polynomial_adjoin_apply, aeval_C, is_scalar_tower.algebra_map_apply R (mv_polynomial ι R), ← polynomial.C_eq_algebra_map, polynomial.map_C, ring_hom.coe_coe, alg_equiv.commutes] end @[simp] lemma algebraic_independent.mv_polynomial_option_equiv_polynomial_adjoin_X_none (hx : algebraic_independent R x) : hx.mv_polynomial_option_equiv_polynomial_adjoin (X none) = polynomial.X := by rw [algebraic_independent.mv_polynomial_option_equiv_polynomial_adjoin_apply, aeval_X, option.elim, polynomial.map_X] @[simp] lemma algebraic_independent.mv_polynomial_option_equiv_polynomial_adjoin_X_some (hx : algebraic_independent R x) (i) : hx.mv_polynomial_option_equiv_polynomial_adjoin (X (some i)) = polynomial.C (hx.aeval_equiv (X i)) := by rw [algebraic_independent.mv_polynomial_option_equiv_polynomial_adjoin_apply, aeval_X, option.elim, polynomial.map_C, ring_hom.coe_coe] lemma algebraic_independent.aeval_comp_mv_polynomial_option_equiv_polynomial_adjoin (hx : algebraic_independent R x) (a : A) : (ring_hom.comp (↑(polynomial.aeval a : polynomial (adjoin R (set.range x)) →ₐ[_] A) : polynomial (adjoin R (set.range x)) →+* A) hx.mv_polynomial_option_equiv_polynomial_adjoin.to_ring_hom) = ↑((mv_polynomial.aeval (λ o : option ι, o.elim a x)) : mv_polynomial (option ι) R →ₐ[R] A) := begin refine mv_polynomial.ring_hom_ext _ _; simp only [ring_hom.comp_apply, ring_equiv.to_ring_hom_eq_coe, ring_equiv.coe_to_ring_hom, alg_hom.coe_to_ring_hom, alg_hom.coe_to_ring_hom], { intro r, rw [hx.mv_polynomial_option_equiv_polynomial_adjoin_C, aeval_C, polynomial.aeval_C, is_scalar_tower.algebra_map_apply R (adjoin R (range x)) A] }, { rintro (⟨⟩|⟨i⟩), { rw [hx.mv_polynomial_option_equiv_polynomial_adjoin_X_none, aeval_X, polynomial.aeval_X, option.elim] }, { rw [hx.mv_polynomial_option_equiv_polynomial_adjoin_X_some, polynomial.aeval_C, hx.algebra_map_aeval_equiv, aeval_X, aeval_X, option.elim] } }, end theorem algebraic_independent.option_iff (hx : algebraic_independent R x) (a : A) : (algebraic_independent R (λ o : option ι, o.elim a x)) ↔ ¬ is_algebraic (adjoin R (set.range x)) a := by erw [algebraic_independent_iff_injective_aeval, is_algebraic_iff_not_injective, not_not, ← alg_hom.coe_to_ring_hom, ← hx.aeval_comp_mv_polynomial_option_equiv_polynomial_adjoin, ring_hom.coe_comp, injective.of_comp_iff' _ (ring_equiv.bijective _), alg_hom.coe_to_ring_hom] variable (R) /-- A family is a transcendence basis if it is a maximal algebraically independent subset. -/ def is_transcendence_basis (x : ι → A) : Prop := algebraic_independent R x ∧ ∀ (s : set A) (i' : algebraic_independent R (coe : s → A)) (h : range x ≤ s), range x = s lemma exists_is_transcendence_basis (h : injective (algebra_map R A)) : ∃ s : set A, is_transcendence_basis R (coe : s → A) := begin cases exists_maximal_algebraic_independent (∅ : set A) set.univ (set.subset_univ _) ((algebraic_independent_empty_iff R A).2 h) with s hs, use [s, hs.1], intros t ht hr, simp only [subtype.range_coe_subtype, set_of_mem_eq] at *, exact eq.symm (hs.2.2.2 t ht hr (set.subset_univ _)) end variable {R} lemma algebraic_independent.is_transcendence_basis_iff {ι : Type w} {R : Type u} [comm_ring R] [nontrivial R] {A : Type v} [comm_ring A] [algebra R A] {x : ι → A} (i : algebraic_independent R x) : is_transcendence_basis R x ↔ ∀ (κ : Type v) (w : κ → A) (i' : algebraic_independent R w) (j : ι → κ) (h : w ∘ j = x), surjective j := begin fsplit, { rintros p κ w i' j rfl, have p := p.2 (range w) i'.coe_range (range_comp_subset_range _ _), rw [range_comp, ←@image_univ _ _ w] at p, exact range_iff_surjective.mp (image_injective.mpr i'.injective p) }, { intros p, use i, intros w i' h, specialize p w (coe : w → A) i' (λ i, ⟨x i, range_subset_iff.mp h i⟩) (by { ext, simp, }), have q := congr_arg (λ s, (coe : w → A) '' s) p.range_eq, dsimp at q, rw [←image_univ, image_image] at q, simpa using q, }, end lemma is_transcendence_basis.is_algebraic [nontrivial R] (hx : is_transcendence_basis R x) : is_algebraic (adjoin R (range x)) A := begin intro a, rw [← not_iff_comm.1 (hx.1.option_iff _).symm], intro ai, have h₁ : range x ⊆ range (λ o : option ι, o.elim a x), { rintros x ⟨y, rfl⟩, exact ⟨some y, rfl⟩ }, have h₂ : range x ≠ range (λ o : option ι, o.elim a x), { intro h, have : a ∈ range x, { rw h, exact ⟨none, rfl⟩ }, rcases this with ⟨b, rfl⟩, have : some b = none := ai.injective rfl, simpa }, exact h₂ (hx.2 (set.range (λ o : option ι, o.elim a x)) ((algebraic_independent_subtype_range ai.injective).2 ai) h₁) end section field variables [field K] [algebra K A] @[simp] lemma algebraic_independent_empty_type [is_empty ι] [nontrivial A] : algebraic_independent K x := begin rw [algebraic_independent_empty_type_iff], exact ring_hom.injective _, end lemma algebraic_independent_empty [nontrivial A] : algebraic_independent K (coe : ((∅ : set A) → A)) := algebraic_independent_empty_type end field
f2f76eeaa67c45ab23f4c769b0e2693467a8776f
36938939954e91f23dec66a02728db08a7acfcf9
/lean/deps/typed_smt2/src/galois/smt2/cmd.lean
acf6ddf71f43fda92c1cc6584e2adeab46af8c10
[ "Apache-2.0" ]
permissive
pnwamk/reopt-vcg
f8b56dd0279392a5e1c6aee721be8138e6b558d3
c9f9f185fbefc25c36c4b506bbc85fd1a03c3b6d
refs/heads/master
1,631,145,017,772
1,593,549,019,000
1,593,549,143,000
254,191,418
0
0
null
1,586,377,077,000
1,586,377,077,000
null
UTF-8
Lean
false
false
1,285
lean
import .basic namespace smt2 /-- An SMT command -/ structure cmd := (expr : sexpr atom) namespace cmd open sort /-- Write command to a handle. -/ protected def write (c:cmd) (h:io.handle) : io punit := sexpr.write h (c.expr) /-- Construct assert command. -/ protected def assert (p:term Bool) : cmd := ⟨sexpr.app (reserved_word.of_string "assert") [p]⟩ /-- Construct check-sat command. -/ protected def check_sat : cmd := ⟨sexpr.parens [reserved_word.of_string "check-sat"]⟩ /-- Declare a constant -/ protected def declare_const (nm:symbol) (res:sort) : cmd := ⟨sexpr.app (reserved_word.of_string "declare-const") [nm, res]⟩ /-- Declare a function -/ protected def declare_fun (nm:symbol) (args:list sort) (res:sort) : cmd := ⟨sexpr.app (reserved_word.of_string "declare-fun") [nm, sexpr.parens (args.map sort.to_sexpr), res]⟩ /-- Map a symbol and sort pair from a function declaration to an s-expression -/ def arg_pair : symbol × sort → sexpr atom | ⟨nm,s⟩ := sexpr.app nm [s] /-- Define a function in terms of inputs -/ protected def define_fun (nm:symbol) (args:list (symbol × sort)) {res:sort} (rhs : term res) : cmd := do ⟨sexpr.app (sexpr.of_string "define-fun") [ nm, sexpr.parens (args.map arg_pair), res, rhs ]⟩ end cmd end smt2
21936329dedfc9e89ac8e4692d6cc26f450766d1
9dc8cecdf3c4634764a18254e94d43da07142918
/src/control/traversable/basic.lean
e11e66dba7c9bb85c9cfa4bb5c268092d42ddb08
[ "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
9,542
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import control.functor /-! # Traversable type class Type classes for traversing collections. The concepts and laws are taken from <http://hackage.haskell.org/package/base-4.11.1.0/docs/Data-Traversable.html> Traversable collections are a generalization of functors. Whereas functors (such as `list`) allow us to apply a function to every element, it does not allow functions which external effects encoded in a monad. Consider for instance a functor `invite : email → io response` that takes an email address, sends an email and waits for a response. If we have a list `guests : list email`, using calling `invite` using `map` gives us the following: `map invite guests : list (io response)`. It is not what we need. We need something of type `io (list response)`. Instead of using `map`, we can use `traverse` to send all the invites: `traverse invite guests : io (list response)`. `traverse` applies `invite` to every element of `guests` and combines all the resulting effects. In the example, the effect is encoded in the monad `io` but any applicative functor is accepted by `traverse`. For more on how to use traversable, consider the Haskell tutorial: <https://en.wikibooks.org/wiki/Haskell/Traversable> ## Main definitions * `traversable` type class - exposes the `traverse` function * `sequence` - based on `traverse`, turns a collection of effects into an effect returning a collection * `is_lawful_traversable` - laws for a traversable functor * `applicative_transformation` - the notion of a natural transformation for applicative functors ## Tags traversable iterator functor applicative ## References * "Applicative Programming with Effects", by Conor McBride and Ross Paterson, Journal of Functional Programming 18:1 (2008) 1-13, online at <http://www.soi.city.ac.uk/~ross/papers/Applicative.html> * "The Essence of the Iterator Pattern", by Jeremy Gibbons and Bruno Oliveira, in Mathematically-Structured Functional Programming, 2006, online at <http://web.comlab.ox.ac.uk/oucl/work/jeremy.gibbons/publications/#iterator> * "An Investigation of the Laws of Traversals", by Mauro Jaskelioff and Ondrej Rypacek, in Mathematically-Structured Functional Programming, 2012, online at <http://arxiv.org/pdf/1202.2919> -/ open function (hiding comp) universes u v w section applicative_transformation variables (F : Type u → Type v) [applicative F] [is_lawful_applicative F] variables (G : Type u → Type w) [applicative G] [is_lawful_applicative G] /-- A transformation between applicative functors. It is a natural transformation such that `app` preserves the `has_pure.pure` and `functor.map` (`<*>`) operations. See `applicative_transformation.preserves_map` for naturality. -/ structure applicative_transformation : Type (max (u+1) v w) := (app : Π α : Type u, F α → G α) (preserves_pure' : ∀ {α : Type u} (x : α), app _ (pure x) = pure x) (preserves_seq' : ∀ {α β : Type u} (x : F (α → β)) (y : F α), app _ (x <*> y) = app _ x <*> app _ y) end applicative_transformation namespace applicative_transformation variables (F : Type u → Type v) [applicative F] [is_lawful_applicative F] variables (G : Type u → Type w) [applicative G] [is_lawful_applicative G] instance : has_coe_to_fun (applicative_transformation F G) (λ _, Π {α}, F α → G α) := ⟨applicative_transformation.app⟩ variables {F G} @[simp] lemma app_eq_coe (η : applicative_transformation F G) : η.app = η := rfl @[simp] lemma coe_mk (f : Π (α : Type u), F α → G α) (pp ps) : ⇑(applicative_transformation.mk f pp ps) = f := rfl protected lemma congr_fun (η η' : applicative_transformation F G) (h : η = η') {α : Type u} (x : F α) : η x = η' x := congr_arg (λ η'' : applicative_transformation F G, η'' x) h protected lemma congr_arg (η : applicative_transformation F G) {α : Type u} {x y : F α} (h : x = y) : η x = η y := congr_arg (λ z : F α, η z) h lemma coe_inj ⦃η η' : applicative_transformation F G⦄ (h : (η : Π α, F α → G α) = η') : η = η' := by { cases η, cases η', congr, exact h } @[ext] lemma ext ⦃η η' : applicative_transformation F G⦄ (h : ∀ (α : Type u) (x : F α), η x = η' x) : η = η' := by { apply coe_inj, ext1 α, exact funext (h α) } lemma ext_iff {η η' : applicative_transformation F G} : η = η' ↔ ∀ (α : Type u) (x : F α), η x = η' x := ⟨λ h α x, h ▸ rfl, λ h, ext h⟩ section preserves variables (η : applicative_transformation F G) @[functor_norm] lemma preserves_pure {α} : ∀ (x : α), η (pure x) = pure x := η.preserves_pure' @[functor_norm] lemma preserves_seq {α β : Type u} : ∀ (x : F (α → β)) (y : F α), η (x <*> y) = η x <*> η y := η.preserves_seq' @[functor_norm] lemma preserves_map {α β} (x : α → β) (y : F α) : η (x <$> y) = x <$> η y := by rw [← pure_seq_eq_map, η.preserves_seq]; simp with functor_norm lemma preserves_map' {α β} (x : α → β) : @η _ ∘ functor.map x = functor.map x ∘ @η _ := by { ext y, exact preserves_map η x y } end preserves /-- The identity applicative transformation from an applicative functor to itself. -/ def id_transformation : applicative_transformation F F := { app := λ α, id, preserves_pure' := by simp, preserves_seq' := λ α β x y, by simp } instance : inhabited (applicative_transformation F F) := ⟨id_transformation⟩ universes s t variables {H : Type u → Type s} [applicative H] [is_lawful_applicative H] /-- The composition of applicative transformations. -/ def comp (η' : applicative_transformation G H) (η : applicative_transformation F G) : applicative_transformation F H := { app := λ α x, η' (η x), preserves_pure' := λ α x, by simp with functor_norm, preserves_seq' := λ α β x y, by simp with functor_norm } @[simp] lemma comp_apply (η' : applicative_transformation G H) (η : applicative_transformation F G) {α : Type u} (x : F α) : η'.comp η x = η' (η x) := rfl lemma comp_assoc {I : Type u → Type t} [applicative I] [is_lawful_applicative I] (η'' : applicative_transformation H I) (η' : applicative_transformation G H) (η : applicative_transformation F G) : (η''.comp η').comp η = η''.comp (η'.comp η) := rfl @[simp] lemma comp_id (η : applicative_transformation F G) : η.comp id_transformation = η := ext $ λ α x, rfl @[simp] lemma id_comp (η : applicative_transformation F G) : id_transformation.comp η = η := ext $ λ α x, rfl end applicative_transformation open applicative_transformation /-- A traversable functor is a functor along with a way to commute with all applicative functors (see `sequence`). For example, if `t` is the traversable functor `list` and `m` is the applicative functor `io`, then given a function `f : α → io β`, the function `functor.map f` is `list α → list (io β)`, but `traverse f` is `list α → io (list β)`. -/ class traversable (t : Type u → Type u) extends functor t := (traverse : Π {m : Type u → Type u} [applicative m] {α β}, (α → m β) → t α → m (t β)) open functor export traversable (traverse) section functions variables {t : Type u → Type u} variables {m : Type u → Type v} [applicative m] variables {α β : Type u} variables {f : Type u → Type u} [applicative f] /-- A traversable functor commutes with all applicative functors. -/ def sequence [traversable t] : t (f α) → f (t α) := traverse id end functions /-- A traversable functor is lawful if its `traverse` satisfies a number of additional properties. It must send `id.mk` to `id.mk`, send the composition of applicative functors to the composition of the `traverse` of each, send each function `f` to `λ x, f <$> x`, and satisfy a naturality condition with respect to applicative transformations. -/ class is_lawful_traversable (t : Type u → Type u) [traversable t] extends is_lawful_functor t : Type (u+1) := (id_traverse : ∀ {α} (x : t α), traverse id.mk x = x ) (comp_traverse : ∀ {F G} [applicative F] [applicative G] [is_lawful_applicative F] [is_lawful_applicative G] {α β γ} (f : β → F γ) (g : α → G β) (x : t α), traverse (comp.mk ∘ map f ∘ g) x = comp.mk (map (traverse f) (traverse g x))) (traverse_eq_map_id : ∀ {α β} (f : α → β) (x : t α), traverse (id.mk ∘ f) x = id.mk (f <$> x)) (naturality : ∀ {F G} [applicative F] [applicative G] [is_lawful_applicative F] [is_lawful_applicative G] (η : applicative_transformation F G) {α β} (f : α → F β) (x : t α), η (traverse f x) = traverse (@η _ ∘ f) x) instance : traversable id := ⟨λ _ _ _ _, id⟩ instance : is_lawful_traversable id := by refine {..}; intros; refl section variables {F : Type u → Type v} [applicative F] instance : traversable option := ⟨@option.traverse⟩ instance : traversable list := ⟨@list.traverse⟩ end namespace sum variables {σ : Type u} variables {F : Type u → Type u} variables [applicative F] /-- Defines a `traverse` function on the second component of a sum type. This is used to give a `traversable` instance for the functor `σ ⊕ -`. -/ protected def traverse {α β} (f : α → F β) : σ ⊕ α → F (σ ⊕ β) | (sum.inl x) := pure (sum.inl x) | (sum.inr x) := sum.inr <$> f x end sum instance {σ : Type u} : traversable.{u} (sum σ) := ⟨@sum.traverse _⟩
e72973d0e56e430d612f9124de0b03138e223076
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/normed_space/hahn_banach/extension.lean
74898d0c531cac01c2b561b36db4ab26d34ce40e
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
6,818
lean
/- Copyright (c) 2020 Yury Kudryashov All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Heather Macbeth -/ import analysis.convex.cone.basic import analysis.normed_space.is_R_or_C import analysis.normed_space.extend /-! # Extension Hahn-Banach theorem In this file we prove the analytic Hahn-Banach theorem. For any continuous linear function on a subspace, we can extend it to a function on the entire space without changing its norm. We prove * `real.exists_extension_norm_eq`: Hahn-Banach theorem for continuous linear functions on normed spaces over `ℝ`. * `exists_extension_norm_eq`: Hahn-Banach theorem for continuous linear functions on normed spaces over `ℝ` or `ℂ`. In order to state and prove the corollaries uniformly, we prove the statements for a field `𝕜` satisfying `is_R_or_C 𝕜`. In this setting, `exists_dual_vector` states that, for any nonzero `x`, there exists a continuous linear form `g` of norm `1` with `g x = ‖x‖` (where the norm has to be interpreted as an element of `𝕜`). -/ universes u v namespace real variables {E : Type*} [seminormed_add_comm_group E] [normed_space ℝ E] /-- Hahn-Banach theorem for continuous linear functions over `ℝ`. -/ theorem exists_extension_norm_eq (p : subspace ℝ E) (f : p →L[ℝ] ℝ) : ∃ g : E →L[ℝ] ℝ, (∀ x : p, g x = f x) ∧ ‖g‖ = ‖f‖ := begin rcases exists_extension_of_le_sublinear ⟨p, f⟩ (λ x, ‖f‖ * ‖x‖) (λ c hc x, by simp only [norm_smul c x, real.norm_eq_abs, abs_of_pos hc, mul_left_comm]) (λ x y, _) (λ x, le_trans (le_abs_self _) (f.le_op_norm _)) with ⟨g, g_eq, g_le⟩, set g' := g.mk_continuous (‖f‖) (λ x, abs_le.2 ⟨neg_le.1 $ g.map_neg x ▸ norm_neg x ▸ g_le (-x), g_le x⟩), { refine ⟨g', g_eq, _⟩, { apply le_antisymm (g.mk_continuous_norm_le (norm_nonneg f) _), refine f.op_norm_le_bound (norm_nonneg _) (λ x, _), dsimp at g_eq, rw ← g_eq, apply g'.le_op_norm } }, { simp only [← mul_add], exact mul_le_mul_of_nonneg_left (norm_add_le x y) (norm_nonneg f) } end end real section is_R_or_C open is_R_or_C variables {𝕜 : Type*} [is_R_or_C 𝕜] {F : Type*} [seminormed_add_comm_group F] [normed_space 𝕜 F] /-- Hahn-Banach theorem for continuous linear functions over `𝕜` satisyfing `is_R_or_C 𝕜`. -/ theorem exists_extension_norm_eq (p : subspace 𝕜 F) (f : p →L[𝕜] 𝕜) : ∃ g : F →L[𝕜] 𝕜, (∀ x : p, g x = f x) ∧ ‖g‖ = ‖f‖ := begin letI : module ℝ F := restrict_scalars.module ℝ 𝕜 F, letI : is_scalar_tower ℝ 𝕜 F := restrict_scalars.is_scalar_tower _ _ _, letI : normed_space ℝ F := normed_space.restrict_scalars _ 𝕜 _, -- Let `fr: p →L[ℝ] ℝ` be the real part of `f`. let fr := re_clm.comp (f.restrict_scalars ℝ), have fr_apply : ∀ x, fr x = re (f x), by { assume x, refl }, -- Use the real version to get a norm-preserving extension of `fr`, which -- we'll call `g : F →L[ℝ] ℝ`. rcases real.exists_extension_norm_eq (p.restrict_scalars ℝ) fr with ⟨g, ⟨hextends, hnormeq⟩⟩, -- Now `g` can be extended to the `F →L[𝕜] 𝕜` we need. refine ⟨g.extend_to_𝕜, _⟩, -- It is an extension of `f`. have h : ∀ x : p, g.extend_to_𝕜 x = f x, { assume x, rw [continuous_linear_map.extend_to_𝕜_apply, ←submodule.coe_smul, hextends, hextends], have : (fr x : 𝕜) - I * ↑(fr (I • x)) = (re (f x) : 𝕜) - (I : 𝕜) * (re (f ((I : 𝕜) • x))), by refl, rw this, apply ext, { simp only [add_zero, algebra.id.smul_eq_mul, I_re, of_real_im, add_monoid_hom.map_add, zero_sub, I_im', zero_mul, of_real_re, eq_self_iff_true, sub_zero, mul_neg, of_real_neg, mul_re, mul_zero, sub_neg_eq_add, continuous_linear_map.map_smul] }, { simp only [algebra.id.smul_eq_mul, I_re, of_real_im, add_monoid_hom.map_add, zero_sub, I_im', zero_mul, of_real_re, mul_neg, mul_im, zero_add, of_real_neg, mul_re, sub_neg_eq_add, continuous_linear_map.map_smul] } }, -- And we derive the equality of the norms by bounding on both sides. refine ⟨h, le_antisymm _ _⟩, { calc ‖g.extend_to_𝕜‖ ≤ ‖g‖ : g.extend_to_𝕜.op_norm_le_bound g.op_norm_nonneg (norm_bound _) ... = ‖fr‖ : hnormeq ... ≤ ‖re_clm‖ * ‖f‖ : continuous_linear_map.op_norm_comp_le _ _ ... = ‖f‖ : by rw [re_clm_norm, one_mul] }, { exact f.op_norm_le_bound g.extend_to_𝕜.op_norm_nonneg (λ x, h x ▸ g.extend_to_𝕜.le_op_norm x) } end end is_R_or_C section dual_vector variables (𝕜 : Type v) [is_R_or_C 𝕜] variables {E : Type u} [normed_add_comm_group E] [normed_space 𝕜 E] open continuous_linear_equiv submodule open_locale classical lemma coord_norm' {x : E} (h : x ≠ 0) : ‖(‖x‖ : 𝕜) • coord 𝕜 x h‖ = 1 := by rw [norm_smul, is_R_or_C.norm_coe_norm, coord_norm, mul_inv_cancel (mt norm_eq_zero.mp h)] /-- Corollary of Hahn-Banach. Given a nonzero element `x` of a normed space, there exists an element of the dual space, of norm `1`, whose value on `x` is `‖x‖`. -/ theorem exists_dual_vector (x : E) (h : x ≠ 0) : ∃ g : E →L[𝕜] 𝕜, ‖g‖ = 1 ∧ g x = ‖x‖ := begin let p : submodule 𝕜 E := 𝕜 ∙ x, let f := (‖x‖ : 𝕜) • coord 𝕜 x h, obtain ⟨g, hg⟩ := exists_extension_norm_eq p f, refine ⟨g, _, _⟩, { rw [hg.2, coord_norm'] }, { calc g x = g (⟨x, mem_span_singleton_self x⟩ : 𝕜 ∙ x) : by rw coe_mk ... = ((‖x‖ : 𝕜) • coord 𝕜 x h) (⟨x, mem_span_singleton_self x⟩ : 𝕜 ∙ x) : by rw ← hg.1 ... = ‖x‖ : by simp } end /-- Variant of Hahn-Banach, eliminating the hypothesis that `x` be nonzero, and choosing the dual element arbitrarily when `x = 0`. -/ theorem exists_dual_vector' [nontrivial E] (x : E) : ∃ g : E →L[𝕜] 𝕜, ‖g‖ = 1 ∧ g x = ‖x‖ := begin by_cases hx : x = 0, { obtain ⟨y, hy⟩ := exists_ne (0 : E), obtain ⟨g, hg⟩ : ∃ g : E →L[𝕜] 𝕜, ‖g‖ = 1 ∧ g y = ‖y‖ := exists_dual_vector 𝕜 y hy, refine ⟨g, hg.left, _⟩, simp [hx] }, { exact exists_dual_vector 𝕜 x hx } end /-- Variant of Hahn-Banach, eliminating the hypothesis that `x` be nonzero, but only ensuring that the dual element has norm at most `1` (this can not be improved for the trivial vector space). -/ theorem exists_dual_vector'' (x : E) : ∃ g : E →L[𝕜] 𝕜, ‖g‖ ≤ 1 ∧ g x = ‖x‖ := begin by_cases hx : x = 0, { refine ⟨0, by simp, _⟩, symmetry, simp [hx], }, { rcases exists_dual_vector 𝕜 x hx with ⟨g, g_norm, g_eq⟩, exact ⟨g, g_norm.le, g_eq⟩ } end end dual_vector
ba968699b967c3b4298926ad6efca71746d01c9b
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/ring/ulift.lean
c16e7a9fcac81fb17dc370fd5f72de89fdb1901d
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
5,177
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.group.ulift import algebra.field.defs import algebra.ring.equiv /-! # `ulift` instances for ring This file defines instances for ring, semiring and related structures on `ulift` types. (Recall `ulift α` is just a "copy" of a type `α` in a higher universe.) We also provide `ulift.ring_equiv : ulift R ≃+* R`. -/ universes u v variables {α : Type u} {x y : ulift.{v} α} namespace ulift instance mul_zero_class [mul_zero_class α] : mul_zero_class (ulift α) := by refine_struct { zero := (0 : ulift α), mul := (*), .. }; tactic.pi_instance_derive_field instance distrib [distrib α] : distrib (ulift α) := by refine_struct { add := (+), mul := (*), .. }; tactic.pi_instance_derive_field instance non_unital_non_assoc_semiring [non_unital_non_assoc_semiring α] : non_unital_non_assoc_semiring (ulift α) := by refine_struct { zero := (0 : ulift α), add := (+), mul := (*), nsmul := add_monoid.nsmul, }; tactic.pi_instance_derive_field instance non_assoc_semiring [non_assoc_semiring α] : non_assoc_semiring (ulift α) := by refine_struct { zero := (0 : ulift α), one := 1, add := (+), mul := (*), nsmul := add_monoid.nsmul, .. ulift.add_monoid_with_one }; tactic.pi_instance_derive_field instance non_unital_semiring [non_unital_semiring α] : non_unital_semiring (ulift α) := by refine_struct { zero := (0 : ulift α), add := (+), mul := (*), nsmul := add_monoid.nsmul, }; tactic.pi_instance_derive_field instance semiring [semiring α] : semiring (ulift α) := by refine_struct { zero := (0 : ulift α), one := 1, add := (+), mul := (*), nsmul := add_monoid.nsmul, npow := monoid.npow, .. ulift.add_monoid_with_one }; tactic.pi_instance_derive_field /-- The ring equivalence between `ulift α` and `α`. -/ def ring_equiv [non_unital_non_assoc_semiring α] : ulift α ≃+* α := { to_fun := ulift.down, inv_fun := ulift.up, map_mul' := λ x y, rfl, map_add' := λ x y, rfl, left_inv := by tidy, right_inv := by tidy, } instance non_unital_comm_semiring [non_unital_comm_semiring α] : non_unital_comm_semiring (ulift α) := by refine_struct { zero := (0 : ulift α), add := (+), mul := (*), nsmul := add_monoid.nsmul }; tactic.pi_instance_derive_field instance comm_semiring [comm_semiring α] : comm_semiring (ulift α) := by refine_struct { zero := (0 : ulift α), one := 1, add := (+), mul := (*), nsmul := add_monoid.nsmul, npow := monoid.npow, .. ulift.semiring }; tactic.pi_instance_derive_field instance non_unital_non_assoc_ring [non_unital_non_assoc_ring α] : non_unital_non_assoc_ring (ulift α) := by refine_struct { zero := (0 : ulift α), add := (+), mul := (*), sub := has_sub.sub, neg := has_neg.neg, nsmul := add_monoid.nsmul, zsmul := sub_neg_monoid.zsmul }; tactic.pi_instance_derive_field instance non_unital_ring [non_unital_ring α] : non_unital_ring (ulift α) := by refine_struct { zero := (0 : ulift α), add := (+), mul := (*), sub := has_sub.sub, neg := has_neg.neg, nsmul := add_monoid.nsmul, zsmul := sub_neg_monoid.zsmul }; tactic.pi_instance_derive_field instance non_assoc_ring [non_assoc_ring α] : non_assoc_ring (ulift α) := by refine_struct { zero := (0 : ulift α), one := 1, add := (+), mul := (*), sub := has_sub.sub, neg := has_neg.neg, nsmul := add_monoid.nsmul, zsmul := sub_neg_monoid.zsmul, .. ulift.add_group_with_one }; tactic.pi_instance_derive_field instance ring [ring α] : ring (ulift α) := by refine_struct { zero := (0 : ulift α), one := 1, add := (+), mul := (*), sub := has_sub.sub, neg := has_neg.neg, nsmul := add_monoid.nsmul, npow := monoid.npow, zsmul := sub_neg_monoid.zsmul, .. ulift.semiring, .. ulift.add_group_with_one }; tactic.pi_instance_derive_field instance non_unital_comm_ring [non_unital_comm_ring α] : non_unital_comm_ring (ulift α) := by refine_struct { zero := (0 : ulift α), add := (+), mul := (*), sub := has_sub.sub, neg := has_neg.neg, nsmul := add_monoid.nsmul, zsmul := sub_neg_monoid.zsmul }; tactic.pi_instance_derive_field instance comm_ring [comm_ring α] : comm_ring (ulift α) := by refine_struct { .. ulift.ring }; tactic.pi_instance_derive_field instance [has_rat_cast α] : has_rat_cast (ulift α) := ⟨λ a, ulift.up (coe a)⟩ @[simp] lemma rat_cast_down [has_rat_cast α] (n : ℚ) : ulift.down (n : ulift α) = n := rfl instance field [field α] : field (ulift α) := begin have of_rat_mk : ∀ a b h1 h2, ((⟨a, b, h1, h2⟩ : ℚ) : ulift α) = ↑a * (↑b)⁻¹, { intros a b h1 h2, ext, rw [rat_cast_down, mul_down, inv_down, nat_cast_down, int_cast_down], exact field.rat_cast_mk a b h1 h2 }, refine_struct { zero := (0 : ulift α), inv := has_inv.inv, div := has_div.div, zpow := λ n a, ulift.up (a.down ^ n), rat_cast := coe, rat_cast_mk := of_rat_mk, qsmul := (•), .. @ulift.nontrivial α _, .. ulift.comm_ring }; tactic.pi_instance_derive_field, -- `mul_inv_cancel` requires special attention: it leaves the goal `∀ {a}, a ≠ 0 → a * a⁻¹ = 1`. cases a, tauto end end ulift
49c84a0f507abc7f02aa5336d2b89a2c5d112dfb
5412d79aa1dc0b521605c38bef9f0d4557b5a29d
/src/Lean/Server/FileWorker.lean
186cbf59e48c4bf18246e07d07039217c9fe3f6e
[ "Apache-2.0" ]
permissive
smunix/lean4
a450ec0927dc1c74816a1bf2818bf8600c9fc9bf
3407202436c141e3243eafbecb4b8720599b970a
refs/heads/master
1,676,334,875,188
1,610,128,510,000
1,610,128,521,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
21,177
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 Std.Data.RBMap import Lean.Environment import Lean.PrettyPrinter import Lean.Data.Lsp import Lean.Data.Json.FromToJson import Lean.Server.Snapshots import Lean.Server.Utils import Lean.Server.AsyncList /-! For general server architecture, see `README.md`. For details of IPC communication, see `Watchdog.lean`. This module implements per-file worker processes. File processing and requests+notifications against a file should be concurrent for two reasons: - By the LSP standard, requests should be cancellable. - Since Lean allows arbitrary user code to be executed during elaboration via the tactic framework, elaboration can be extremely slow and even not halt in some cases. Users should be able to work with the file while this is happening, e.g. make new changes to the file or send requests. To achieve these goals, elaboration is executed in a chain of tasks, where each task corresponds to the elaboration of one command. When the elaboration of one command is done, the next task is spawned. On didChange notifications, we search for the task in which the change occured. If we stumble across a task that has not yet finished before finding the task we're looking for, we terminate it and start the elaboration there, otherwise we start the elaboration at the task where the change occured. Requests iterate over tasks until they find the command that they need to answer the request. In order to not block the main thread, this is done in a request task. If a task that the request task waits for is terminated, a change occured somewhere before the command that the request is looking for and the request sends a "content changed" error. -/ namespace Lean.Server.FileWorker open Lsp open IO open Snapshots open Lean.Parser.Command section Utils private def logSnapContent (s : Snapshot) (text : FileMap) : IO Unit := IO.eprintln s!"[{s.beginPos}, {s.endPos}]: `{text.source.extract s.beginPos (s.endPos-1)}`" inductive TaskError where | aborted | eof | ioError (e : IO.Error) instance : Coe IO.Error TaskError := ⟨TaskError.ioError⟩ structure CancelToken where ref : IO.Ref Bool deriving Inhabited namespace CancelToken def new : IO CancelToken := CancelToken.mk <$> IO.mkRef false def check [MonadExceptOf TaskError m] [MonadLiftT (ST RealWorld) m] [Monad m] (tk : CancelToken) : m Unit := do let c ← tk.ref.get if c = true then throw TaskError.aborted def set (tk : CancelToken) : IO Unit := tk.ref.set true end CancelToken /-- A document editable in the sense that we track the environment and parser state after each command so that edits can be applied without recompiling code appearing earlier in the file. -/ structure EditableDocument where meta : DocumentMeta /- The first snapshot is that after the header. -/ headerSnap : Snapshot /- Subsequent snapshots occur after each command. -/ cmdSnaps : AsyncList TaskError Snapshot cancelTk : CancelToken deriving Inhabited end Utils open IO open Std (RBMap RBMap.empty) open JsonRpc section ServerM -- Pending requests are tracked so that requests can be cancelled by cancelling the corresponding task, -- which would be cancelled by the GC if we did not track these requests. abbrev PendingRequestMap := RBMap RequestID (Task (Except IO.Error Unit)) (fun a b => Decidable.decide (a < b)) structure ServerContext where hIn : FS.Stream hOut : FS.Stream docRef : IO.Ref EditableDocument pendingRequestsRef : IO.Ref PendingRequestMap abbrev ServerM := ReaderT ServerContext IO def updatePendingRequests (map : PendingRequestMap → PendingRequestMap) : ServerM Unit := do (←read).pendingRequestsRef.modify map /-- Elaborates the next command after `parentSnap` and emits diagnostics. -/ private def nextCmdSnap (m : DocumentMeta) (parentSnap : Snapshot) (cancelTk : CancelToken) : ExceptT TaskError ServerM Snapshot := do cancelTk.check let st ← read let maybeSnap ← compileNextCmd m.text.source parentSnap cancelTk.check let sendDiagnostics (msgLog : MessageLog) : IO Unit := do let diagnostics ← msgLog.msgs.mapM (msgToDiagnostic m.text) st.hOut.writeLspNotification { method := "textDocument/publishDiagnostics" param := { uri := m.uri version? := m.version diagnostics := diagnostics.toArray : PublishDiagnosticsParams } } match maybeSnap with | Sum.inl snap => /- NOTE(MH): This relies on the client discarding old diagnostics upon receiving new ones while prefering newer versions over old ones. The former is necessary because we do not explicitly clear older diagnostics, while the latter is necessary because we do not guarantee that diagnostics are emitted in order. Specifically, it may happen that we interrupted this elaboration task right at this point and a newer elaboration task emits diagnostics, after which we emit old diagnostics because we did not yet detect the interrupt. Explicitly clearing diagnostics is difficult for a similar reason, because we cannot guarantee that no further diagnostics are emitted after clearing them. -/ sendDiagnostics <| snap.msgLog.add { fileName := "<ignored>" pos := m.text.toPosition snap.endPos severity := MessageSeverity.information data := "processing..." } snap | Sum.inr msgLog => sendDiagnostics msgLog throw TaskError.eof /-- Elaborates all commands after `initSnap`, emitting the diagnostics. -/ def unfoldCmdSnaps (m : DocumentMeta) (initSnap : Snapshot) (cancelTk : CancelToken) : ServerM (AsyncList TaskError Snapshot) := do -- TODO(MH): check for interrupt with increased precision AsyncList.unfoldAsync (nextCmdSnap m . cancelTk (←read)) initSnap (some fun _ => pure TaskError.aborted) /-- Compiles the contents of a Lean file. -/ def compileDocument (m : DocumentMeta) : ServerM Unit := do let headerSnap@⟨_, _, _, SnapshotData.headerData env msgLog opts⟩ ← Snapshots.compileHeader m.text.source | throwServerError "Internal server error: invalid header snapshot" let cancelTk ← CancelToken.new let cmdSnaps ← unfoldCmdSnaps m headerSnap cancelTk (←read).docRef.set ⟨m, headerSnap, cmdSnaps, cancelTk⟩ /-- Given the new document and `changePos`, the UTF-8 offset of a change into the pre-change source, updates editable doc state. -/ def updateDocument (newMeta : DocumentMeta) (changePos : String.Pos) : ServerM Unit := do -- The watchdog only restarts the file worker when the syntax tree of the header changes. -- If e.g. a newline is deleted, it will not restart this file worker, but we still -- need to reparse the header so that the offsets are correct. let st ← read let oldDoc ← st.docRef.get let newHeaderSnap ← reparseHeader newMeta.text.source oldDoc.headerSnap if newHeaderSnap.stx != oldDoc.headerSnap.stx then throwServerError "Internal server error: header changed but worker wasn't restarted." let ⟨cmdSnaps, e?⟩ ← oldDoc.cmdSnaps.updateFinishedPrefix match e? with -- This case should not be possible. only the main task aborts tasks and ensures that aborted tasks -- do not show up in `snapshots` of an EditableDocument. | some TaskError.aborted => throwServerError "Internal server error: elab task was aborted while still in use." | some (TaskError.ioError ioError) => throw ioError | _ => -- No error or EOF oldDoc.cancelTk.set -- NOTE(WN): we invalidate eagerly as `endPos` consumes input greedily. To re-elaborate only -- when really necessary, we could do a whitespace-aware `Syntax` comparison instead. let mut validSnaps := cmdSnaps.finishedPrefix.takeWhile (fun s => s.endPos < changePos) if validSnaps.length = 0 then let cancelTk ← CancelToken.new let newCmdSnaps ← unfoldCmdSnaps newMeta newHeaderSnap cancelTk st.docRef.set ⟨newMeta, newHeaderSnap, newCmdSnaps, cancelTk⟩ else /- When at least one valid non-header snap exists, it may happen that a change does not fall within the syntactic range of that last snap but still modifies it by appending tokens. We check for this here. We do not currently handle crazy grammars in which an appended token can merge two or more previous commands into one. To do so would require reparsing the entire file. -/ let mut lastSnap := validSnaps.getLast! let preLastSnap := if validSnaps.length ≥ 2 then validSnaps.get! (validSnaps.length - 2) else newHeaderSnap let newLastStx ← parseNextCmd newMeta.text.source preLastSnap if newLastStx != lastSnap.stx then validSnaps ← validSnaps.dropLast lastSnap ← preLastSnap let cancelTk ← CancelToken.new let newSnaps ← unfoldCmdSnaps newMeta lastSnap cancelTk let newCmdSnaps := AsyncList.ofList validSnaps ++ newSnaps st.docRef.set ⟨newMeta, newHeaderSnap, newCmdSnaps, cancelTk⟩ end ServerM /- Notifications are handled in the main thread. They may change global worker state such as the current file contents. -/ 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. -/ compileDocument ⟨doc.uri, doc.version, doc.text.toFileMap⟩ def handleDidChange (p : DidChangeTextDocumentParams) : ServerM Unit := do let docId := p.textDocument let changes := p.contentChanges let oldDoc ← (←read).docRef.get let some newVersion ← pure docId.version? | throwServerError "Expected version number" if newVersion ≤ oldDoc.meta.version then -- TODO(WN): This happens on restart sometimes. IO.eprintln s!"Got outdated version number: {newVersion} ≤ {oldDoc.meta.version}" else if ¬ changes.isEmpty then let (newDocText, minStartOff) := foldDocumentChanges changes oldDoc.meta.text updateDocument ⟨docId.uri, newVersion, newDocText⟩ minStartOff -- TODO(WN): cancel pending requests? def handleCancelRequest (p : CancelParams) : ServerM Unit := do updatePendingRequests (fun pendingRequests => pendingRequests.erase p.id) end NotificationHandling /- Request handlers are given by `Task`s executed asynchronously. They may be cancelled at any time, so they should check the cancellation token when possible to handle this cooperatively. Any exceptions thrown in a handler will be reported to the client as LSP error responses. -/ section RequestHandling structure RequestError where code : ErrorCode message : String -- TODO(WN): the type is too complicated abbrev RequestM α := ServerM $ Task $ Except IO.Error $ Except RequestError α /- Requests that need data from a certain command should traverse the snapshots by successively getting the next task, meaning that we might need to wait for elaboration. When that happens, the request should send a "content changed" error to the user (this way, the server doesn't get bogged down in requests for an old state of the document). Requests need to manually check for whether their task has been cancelled, so that they can reply with a RequestCancelled error. -/ partial def handleHover (id : RequestID) (p : HoverParams) : ServerM (Task (Except IO.Error (Except RequestError (Option Hover)))) := do let doc ← (←read).docRef.get let text := doc.meta.text let hoverPos := text.lspPosToUtf8Pos p.position let findTask ← doc.cmdSnaps.waitFind? (fun s => s.endPos > hoverPos) (IO.mapTask · findTask) fun | Except.error TaskError.aborted => pure $ Except.error { code := ErrorCode.contentModified, message := "File changed." } | Except.error (TaskError.ioError e) => throwThe IO.Error e | Except.error TaskError.eof => pure $ Except.ok none | Except.ok snap? => do let snap? := snap?.filter (fun s => s.beginPos ≤ hoverPos) if let some snap := snap? then if snap.stx.getKind == ``Lean.Parser.Command.declaration then -- TODO(WN): 1. get at the right subexpression -- 2. reply with delaborated type return Except.ok $ some { contents := { kind := MarkupKind.plaintext value := s!"Declaration." } range? := some { start := text.utf8PosToLspPos snap.beginPos «end» := text.utf8PosToLspPos snap.endPos } } return Except.ok none def handleWaitForDiagnostics (id : RequestID) (p : WaitForDiagnosticsParam) : ServerM (Task (Except IO.Error (Except RequestError WaitForDiagnostics))) := do let st ← read let e ← st.docRef.get let t ← e.cmdSnaps.waitAll t.map fun _ => Except.ok $ Except.ok WaitForDiagnostics.mk def rangeOfSyntax (text : FileMap) (stx : Syntax) : Range := ⟨text.utf8PosToLspPos <| stx.getHeadInfo.get!.pos.get!, text.utf8PosToLspPos <| stx.getTailPos.get!⟩ partial def handleDocumentSymbol (id : RequestID) (p : DocumentSymbolParams) : ServerM (Task (Except IO.Error (Except RequestError DocumentSymbolResult))) := do let st ← read asTask do let doc ← st.docRef.get let ⟨cmdSnaps, end?⟩ ← doc.cmdSnaps.updateFinishedPrefix let mut stxs := cmdSnaps.finishedPrefix.map (·.stx) if end?.isNone then let lastSnap := cmdSnaps.finishedPrefix.getLastD doc.headerSnap stxs := stxs ++ (← parseAhead doc.meta.text.source lastSnap).toList let (syms, _) := toDocumentSymbols doc.meta.text stxs return Except.ok { syms := syms.toArray } where toDocumentSymbols (text : FileMap) | [] => ([], []) | stx::stxs => match stx with | `(namespace $id) => sectionLikeToDocumentSymbols text stx stxs (id.getId.toString) SymbolKind.namespace id | `(section $(id)?) => sectionLikeToDocumentSymbols text stx stxs ((·.getId.toString) <$> id |>.getD "<section>") SymbolKind.namespace (id.getD stx) | `(end $(id)?) => ([], stx::stxs) | _ => let (syms, stxs') := toDocumentSymbols text stxs if stx.isOfKind ``Lean.Parser.Command.declaration then let (name, selection) := match stx with | `($dm:declModifiers $ak:attrKind instance $[$np:namedPrio]? $[$id:ident$[.{$ls,*}]?]? $sig:declSig $val) => ((·.getId.toString) <$> id |>.getD s!"instance {sig.reprint.getD ""}", id.getD sig) | _ => match stx[1][1] with | `(declId|$id:ident$[.{$ls,*}]?) => (id.getId.toString, id) | _ => (stx[1][0].isIdOrAtom?.getD "<unknown>", stx[1][0]) (DocumentSymbol.mk { name := name kind := SymbolKind.method range := rangeOfSyntax text stx selectionRange := rangeOfSyntax text selection } :: syms, stxs') else (syms, stxs') sectionLikeToDocumentSymbols (text : FileMap) (stx : Syntax) (stxs : List Syntax) (name : String) (kind : SymbolKind) (selection : Syntax) := let (syms, stxs') := toDocumentSymbols text stxs -- discard `end` let (syms', stxs'') := toDocumentSymbols text (stxs'.drop 1) let endStx := match stxs' with | endStx::_ => endStx | [] => (stx::stxs').getLast! (DocumentSymbol.mk { name := name kind := kind range := ⟨(rangeOfSyntax text stx).start, (rangeOfSyntax text endStx).«end»⟩ selectionRange := rangeOfSyntax text selection children? := syms.toArray } :: syms', stxs'') end RequestHandling section MessageHandling def parseParams (paramType : Type) [FromJson paramType] (params : Json) : ServerM paramType := match fromJson? params with | some parsed => pure parsed | none => throwServerError s!"Got param with wrong structure: {params.compress}" def handleNotification (method : String) (params : Json) : ServerM Unit := do let handle := fun paramType [FromJson paramType] (handler : paramType → ServerM Unit) => parseParams paramType params >>= handler match method with | "textDocument/didChange" => handle DidChangeTextDocumentParams handleDidChange | "$/cancelRequest" => handle CancelParams handleCancelRequest | _ => throwServerError s!"Got unsupported notification method: {method}" def queueRequest (id : RequestID) (requestTask : Task (Except IO.Error Unit)) : ServerM Unit := do updatePendingRequests (fun pendingRequests => pendingRequests.insert id requestTask) def handleRequest (id : RequestID) (method : String) (params : Json) : ServerM Unit := do let handle := fun paramType [FromJson paramType] respType [ToJson respType] (handler : RequestID → paramType → RequestM respType) => do let st ← read let p ← parseParams paramType params let t ← handler id p let t₁ ← (IO.mapTask · t) fun | Except.ok (Except.ok resp) => st.hOut.writeLspResponse ⟨id, resp⟩ | Except.ok (Except.error e) => st.hOut.writeLspResponseError { id := id, code := e.code, message := e.message } | Except.error e => st.hOut.writeLspResponseError { id := id, code := ErrorCode.internalError, message := toString e } queueRequest id t₁ match method with | "textDocument/waitForDiagnostics" => handle WaitForDiagnosticsParam WaitForDiagnostics handleWaitForDiagnostics | "textDocument/hover" => handle HoverParams (Option Hover) handleHover | "textDocument/documentSymbol" => handle DocumentSymbolParams DocumentSymbolResult handleDocumentSymbol | _ => throwServerError s!"Got unsupported request: {method}" end MessageHandling section MainLoop partial def mainLoop : ServerM Unit := do let st ← read let msg ← st.hIn.readLspMessage let pendingRequests ← st.pendingRequestsRef.get let filterFinishedTasks (acc : PendingRequestMap) (id : RequestID) (task : Task (Except IO.Error Unit)) : ServerM PendingRequestMap := do if (←hasFinished task) then /- Handler tasks are constructed so that the only possible errors here are failures of writing a response into the stream. -/ if let Except.error e := task.get then throwServerError s!"Failed responding to request {id}: {e}" acc.erase id else acc let pendingRequests ← pendingRequests.foldM filterFinishedTasks pendingRequests st.pendingRequestsRef.set pendingRequests match msg with | Message.request id method (some params) => handleRequest id method (toJson params) mainLoop | Message.notification "exit" none => -- should be sufficient to shut down the file worker. -- references are lost => tasks are marked as cancelled -- => all tasks eventually quit () | Message.notification method (some params) => handleNotification method (toJson params) mainLoop | _ => throwServerError "Got invalid JSON-RPC message" end MainLoop def initAndRunWorker (i o e : FS.Stream) : IO Unit := do let i ← maybeTee "fwIn.txt" false i let o ← maybeTee "fwOut.txt" true o -- TODO(WN): act in accordance with InitializeParams let _ ← i.readLspRequestAs "initialize" InitializeParams let ⟨_, param⟩ ← i.readLspNotificationAs "textDocument/didOpen" DidOpenTextDocumentParams let e ← e.withPrefix s!"[{param.textDocument.uri}] " let _ ← IO.setStderr e let ctx : ServerContext := { hIn := i hOut := o -- `openDocument` will not access `docRef`, but set it docRef := ←IO.mkRef arbitrary pendingRequestsRef := ←IO.mkRef (RBMap.empty : PendingRequestMap) } ReaderT.run (do handleDidOpen param; mainLoop) ctx @[export lean_server_worker_main] def workerMain : IO UInt32 := do let i ← IO.getStdin let o ← IO.getStdout let e ← IO.getStderr try initAndRunWorker i o e return 0 catch err => e.putStrLn s!"Worker error: {err}" return 1 end Lean.Server.FileWorker
cb1c3d137518b9875b4d4629783edf0c1190b795
94935fb4ab68d4ce640296d02911624a93282575
/src/solutions/wednesday/morning/structures.lean
3650dc12cf2f3fb04e0be7fd8bf1f4fe68352470
[]
permissive
marius-leonhardt/lftcm2020
41c0d7fe3457c1cf3b72cbb1c312b48fc94b85d2
a3eb53f18d9be9a5be748dfe8fe74d0d31a0c1f7
refs/heads/master
1,668,623,789,936
1,594,710,949,000
1,594,710,949,000
279,514,936
0
0
MIT
1,594,711,916,000
1,594,711,916,000
null
UTF-8
Lean
false
false
11,761
lean
import data.rat.basic import algebra.group.prod import tactic.basic /-! Lecture 1: * Use one structure as a running example, probably `equiv` or `embedding`. * Declaring a structure * name, arguments, type, fields * Using a structure * Using projections (without and with the `open` command) * projection notation * `.1`, `.2` Lecture 2: * The `extends` keyword * Declaring objects of a structure * Using the structure notation `{ field1 := _ }` and the `..` notation (and hole commands) * Using the anonymous constructor * maybe: using the constructor `foo.mk` Lecture 3: Classes * Difference between structures and classes * How to use classes * When to use classes Lecture 4: "advanced" topics * Proving equalities between objects of a structure * ext * Subtypes and prod (& existential & sigma types) * maybe: declaring coercions * ... -/ noncomputable theory section bijections open function variables {A B : Type*} /- potential examples / exercises / solutions to exercises -/ structure bijection (A B : Type*) := (to_fun : A → B) (injective : injective to_fun) (surjective : surjective to_fun) /- after lecture 2, though it's mostly an exercise in searching the library (or proving something nontrivial) -/ instance : has_coe_to_fun (bijection A B) := ⟨_, λ f, f.to_fun⟩ /- There is a lemma in the library that almost states this. Try using `suggest`. -/ def equiv_of_bijection (f : bijection A B) : A ≃ B := /- inline sorry -/ equiv.of_bijective f ⟨f.injective, f.surjective⟩ /- inline sorry -/ def bijection_of_equiv (f : A ≃ B) : bijection A B := -- sorry { to_fun := f, injective := f.injective, surjective := f.surjective } -- sorry /- after lecture 4 -/ @[ext] def bijection.ext {f g : bijection A B} (hfg : ∀ x, f x = g x) : f = g := /- inline sorry -/ by { cases f, cases g, congr, ext, exact hfg x } /- inline sorry -/ @[simp] lemma coe_mk {f : A → B} {h1f : injective f} {h2f : surjective f} {x : A} : { bijection . to_fun := f, injective := h1f, surjective := h2f } x = f x := rfl def bijection_equiv_equiv : bijection A B ≃ (A ≃ B) := -- sorry { to_fun := equiv_of_bijection, inv_fun := bijection_of_equiv, left_inv := by { intro f, ext, simp [bijection_of_equiv, equiv_of_bijection] }, right_inv := by { intro f, ext, simp [bijection_of_equiv, equiv_of_bijection] } } -- sorry end bijections /- Below is a possible definition of a group in Lean. It's not the definition we use use in mathlib, which will explained in detail in the next session. -/ structure Group := (G : Type*) (op : G → G → G) (infix * := op) -- temporary notation `*` for `op`, just inside this structure declaration (op_assoc' : ∀ (x y z : G), (x * y) * z = x * (y * z)) (id : G) (notation 1 := id) -- temporary notation `1` for `id`, just inside this structure declaration (id_op' : ∀ (x : G), 1 * x = x) (inv : G → G) (postfix ⁻¹ := inv) -- temporary notation `⁻¹` for `inv`, just inside this structure declaration (op_left_inv' : ∀ (x : G), x⁻¹ * x = 1) namespace Group variables {G : Group} /- Let `G` be a group -/ /- The following line declares that if `G : Group`, then we can also view `G` as a type. -/ instance : has_coe_to_sort Group := ⟨_, Group.G⟩ /- The following lines declare the notation `*`, `⁻¹` and `1` for the fields of `Group`. -/ instance : has_mul G := ⟨G.op⟩ instance : has_inv G := ⟨G.inv⟩ instance : has_one G := ⟨G.id⟩ /- the axioms for groups are satisfied -/ lemma op_assoc (x y z : G) : (x * y) * z = x * (y * z) := G.op_assoc' x y z lemma id_op (x : G) : 1 * x = x := G.id_op' x lemma op_left_inv (x : G) : x⁻¹ * x = 1 := G.op_left_inv' x /- Use the axioms `op_assoc`, `id_op` and `op_left_inv` to prove the following lemma. The fields `op_assoc'`, `id_op'` and `op_left_inv'` should not be used directly, nor can you use any lemmas from the library about `mul`. -/ lemma eq_id_of_op_eq_self {G : Group} {x : G} : x * x = x → x = 1 := begin -- sorry intro hx, rw [←id_op x, ← op_left_inv x, op_assoc, hx] -- sorry end /- Apply the previous lemma to show that `⁻¹` is also a right-sided inverse. -/ lemma op_right_inv {G : Group} (x : G) : x * x⁻¹ = 1 := begin -- sorry apply eq_id_of_op_eq_self, rw [op_assoc x x⁻¹ (x * x⁻¹), ← op_assoc x⁻¹ x x⁻¹, op_left_inv, id_op] -- sorry end /- we can prove that `1` is also a right identity. -/ lemma op_id {G : Group} (x : G) : x * 1 = x := begin -- sorry rw [← op_left_inv x, ← op_assoc, op_right_inv, id_op] -- sorry end /- show that the rationals under addition form a group. The underlying type will be `ℚ`. Use `library_search` for the proofs. -/ def rat_Group : Group := -- sorry { G := ℚ, op := (+), op_assoc' := add_assoc, id := 0, id_op' := zero_add, inv := λ x, -x, op_left_inv' := neg_add_self } -- sorry /- However, it is inconvenient to use this group instance directly. One reason is that to use these group operations we now have to write `(x y : rat_Group)` instead of `(x y : ℚ)`. That's why in Lean we do something else, explained in the next lecture. -/ /- show that the cartesian product of two groups is a group. The underlying type will be `G × H`. -/ -- sorry def prod_Group (G H : Group) : Group := { G := G × H, op := λ x y, (x.1 * y.1, x.2 * y.2), op_assoc' := by { intros, ext; simp; rw [op_assoc] }, id := (1, 1), id_op' := by { intros, ext; simp; rw [id_op] }, inv := λ x, (x.1⁻¹, x.2⁻¹), op_left_inv' := by { intros, ext; simp; rw [op_left_inv] } } -- sorry end Group /-- We can use classes to implement a "safe" square root on natural numbers. -/ @[class] def is_square (n : ℕ) : Prop := ∃k : ℕ, k^2 = n namespace is_square def sqrt (n : ℕ) [hn : is_square n] := classical.some hn prefix `√`:(max+1) := sqrt @[simp] lemma sqrt_square (n : ℕ) [hn : is_square n] : (√n) ^ 2 = n := classical.some_spec hn @[simp] lemma sqrt_eq_iff (n k : ℕ) [hn : is_square n] : √n = k ↔ n = k^2 := -- sorry ⟨λ h, by simp [← h], λ hk, pow_left_inj (nat.zero_le _) (nat.zero_le k) two_pos (by simp [hk])⟩ -- sorry instance square_square (n : ℕ) : is_square (n^2) := /- inline sorry -/ ⟨n, rfl⟩ /- inline sorry -/ instance square_mul_self (n : ℕ) : is_square (n*n) := /- inline sorry -/ ⟨n, by simp [nat.pow_two]⟩ /- inline sorry -/ instance square_mul (n m : ℕ) [is_square n] [is_square m] : is_square (n*m) := /- inline sorry -/ ⟨√n * √m, by simp [nat.mul_pow]⟩ /- inline sorry -/ lemma sqrt_mul (n m : ℕ) [is_square n] [is_square m] : √(n * m) = √n * √m := /- inline sorry -/ by simp [nat.mul_pow] /- inline sorry -/ /- hint: use `nat.le_mul_self` -/ lemma sqrt_le (n : ℕ) [is_square n] : √n ≤ n := /- inline sorry -/ by { conv_rhs { rw [← sqrt_square n, nat.pow_two] }, apply nat.le_mul_self } /- inline sorry -/ end is_square structure pointed_type := (type : Type*) (point : type) namespace pointed_type variables {A B : pointed_type} /- The following line declares that if `A : pointed_type`, then we can also view `A` as a type. -/ instance : has_coe_to_sort pointed_type := ⟨_, pointed_type.type⟩ /- Show that the product of two pointed types is a pointed type. The underyling type will be `A × B`. -/ @[simps point] def prod (A B : pointed_type) : pointed_type := -- sorry { type := A × B, point := (A.point, B.point) } -- sorry end pointed_type structure pointed_map (A B : pointed_type) := (to_fun : A → B) (to_fun_point : to_fun A.point = B.point) namespace pointed_map infix ` →. `:25 := pointed_map variables {A B C D : pointed_type} variables {h : C →. D} {g : B →. C} {f f₁ f₂ : A →. B} instance : has_coe_to_fun (A →. B) := ⟨λ _, A → B, pointed_map.to_fun⟩ @[simp] lemma coe_mk {f : A → B} {hf : f A.point = B.point} {x : A} : { pointed_map . to_fun := f, to_fun_point := hf } x = f x := rfl @[simp] lemma coe_point : f A.point = B.point := f.to_fun_point @[ext] protected lemma ext (hf₁₂ : ∀ x, f₁ x = f₂ x) : f₁ = f₂ := begin -- sorry cases f₁ with f₁ hf₁, cases f₂ with f₂ hf₂, congr, ext x, exact hf₁₂ x -- sorry end def comp (g : B →. C) (f : A →. B) : A →. C := -- sorry { to_fun := g ∘ f, to_fun_point := by simp } -- sorry def id : A →. A := -- sorry { to_fun := id, to_fun_point := by simp } -- sorry lemma comp_assoc : h.comp (g.comp f) = (h.comp g).comp f := -- sorry by { ext x, refl } -- sorry lemma id_comp : f.comp id = f := -- sorry by { ext x, refl } -- sorry lemma comp_id : id.comp f = f := -- sorry by { ext x, refl } -- sorry def fst : A.prod B →. A := -- sorry { to_fun := prod.fst, to_fun_point := rfl } -- sorry def snd : A.prod B →. B := -- sorry { to_fun := prod.snd, to_fun_point := rfl } -- sorry def pair (f : C →. A) (g : C →. B) : C →. A.prod B := -- sorry { to_fun := λ c, (f c, g c), to_fun_point := by simp } -- sorry lemma fst_pair (f : C →. A) (g : C →. B) : fst.comp (f.pair g) = f := -- sorry by { ext, simp [pair, fst, comp] } -- sorry lemma snd_pair (f : C →. A) (g : C →. B) : snd.comp (f.pair g) = g := -- sorry by { ext, simp [pair, snd, comp] } -- sorry lemma pair_unique (f : C →. A) (g : C →. B) (u : C →. A.prod B) (h1u : fst.comp u = f) (h2u : snd.comp u = g) : u = f.pair g := begin -- sorry ext, { have : fst (u x) = f x, { rw [←h1u], simp [comp] }, simpa using this }, { have : snd (u x) = g x, { rw [←h2u], simp [comp] }, simpa using this } -- sorry end end pointed_map /- As an advanced exercise, you can show that the category of pointed type has coproducts. For this we need quotients, the basic interface is given with the declarations `quot r`: the quotient of the equivalence relation generated by relation `r` on `A` `quot.mk r : A → quot r`, `quot.sound` `quot.lift` (see below) -/ #print quot #print quot.mk #print quot.sound #print quot.lift open sum /- We want to define the coproduct of pointed types `A` and `B` as the coproduct `A ⊕ B` of the underlying type, identifying the two basepoints. First define a relation that *only* relates `inl A.point ~ inr B.point`. -/ def coprod_rel (A B : pointed_type) : (A ⊕ B) → (A ⊕ B) → Prop := -- sorry λ x y, x = inl A.point ∧ y = inr B.point -- sorry namespace pointed_type @[simps point] def coprod (A B : pointed_type) : pointed_type := -- sorry { type := quot (coprod_rel A B), point := quot.mk _ (inl A.point) } -- sorry end pointed_type namespace pointed_map variables {A B C D : pointed_type} def inl : A →. A.coprod B := -- sorry { to_fun := quot.mk _ ∘ sum.inl, to_fun_point := rfl } -- sorry def inr : B →. A.coprod B := -- sorry { to_fun := quot.mk _ ∘ sum.inr, to_fun_point := by { refine (quot.sound _).symm, exact ⟨rfl, rfl⟩ } } -- sorry def elim (f : A →. C) (g : B →. C) : A.coprod B →. C := -- sorry { to_fun := quot.lift (sum.elim f g) (by { rintro _ _ ⟨rfl, rfl⟩, simp }), to_fun_point := by simp } -- sorry lemma elim_comp_inl (f : A →. C) (g : B →. C) : (f.elim g).comp inl = f := -- sorry by { ext, simp [elim, inl, comp] } -- sorry lemma elim_comp_inr (f : A →. C) (g : B →. C) : (f.elim g).comp inr = g := -- sorry by { ext, simp [elim, inr, comp] } -- sorry lemma elim_unique (f : A →. C) (g : B →. C) (u : A.coprod B →. C) (h1u : u.comp inl = f) (h2u : u.comp inr = g) : u = f.elim g := begin -- sorry ext (x|y), { have : u (inl x) = f x, { rw [←h1u], simp [comp] }, simpa [elim, inl] using this }, { have : u (inr y) = g y, { rw [←h2u], simp [comp] }, simpa [elim, inl] using this } -- sorry end end pointed_map
42d30a556e1d44f38b37ac8195dae361ac85e765
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/analysis/calculus/iterated_deriv.lean
0697e0d563d291b6b79a4408dc99482a3f01c199
[ "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
14,614
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.calculus.deriv import analysis.calculus.times_cont_diff /-! # One-dimensional iterated derivatives We define the `n`-th derivative of a function `f : 𝕜 → F` as a function `iterated_deriv n f : 𝕜 → F`, as well as a version on domains `iterated_deriv_within n f s : 𝕜 → F`, and prove their basic properties. ## Main definitions and results Let `𝕜` be a nondiscrete normed field, and `F` a normed vector space over `𝕜`. Let `f : 𝕜 → F`. * `iterated_deriv n f` is the `n`-th derivative of `f`, seen as a function from `𝕜` to `F`. It is defined as the `n`-th Fréchet derivative (which is a multilinear map) applied to the vector `(1, ..., 1)`, to take advantage of all the existing framework, but we show that it coincides with the naive iterative definition. * `iterated_deriv_eq_iterate` states that the `n`-th derivative of `f` is obtained by starting from `f` and differentiating it `n` times. * `iterated_deriv_within n f s` is the `n`-th derivative of `f` within the domain `s`. It only behaves well when `s` has the unique derivative property. * `iterated_deriv_within_eq_iterate` states that the `n`-th derivative of `f` in the domain `s` is obtained by starting from `f` and differentiating it `n` times within `s`. This only holds when `s` has the unique derivative property. ## Implementation details The results are deduced from the corresponding results for the more general (multilinear) iterated Fréchet derivative. For this, we write `iterated_deriv n f` as the composition of `iterated_fderiv 𝕜 n f` and a continuous linear equiv. As continuous linear equivs respect differentiability and commute with differentiation, this makes it possible to prove readily that the derivative of the `n`-th derivative is the `n+1`-th derivative in `iterated_deriv_within_succ`, by translating the corresponding result `iterated_fderiv_within_succ_apply_left` for the iterated Fréchet derivative. -/ noncomputable theory open_locale classical topological_space big_operators open filter asymptotics set variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] variables {F : Type*} [normed_group F] [normed_space 𝕜 F] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] /-- The `n`-th iterated derivative of a function from `𝕜` to `F`, as a function from `𝕜` to `F`. -/ def iterated_deriv (n : ℕ) (f : 𝕜 → F) (x : 𝕜) : F := (iterated_fderiv 𝕜 n f x : ((fin n) → 𝕜) → F) (λ(i : fin n), 1) /-- The `n`-th iterated derivative of a function from `𝕜` to `F` within a set `s`, as a function from `𝕜` to `F`. -/ def iterated_deriv_within (n : ℕ) (f : 𝕜 → F) (s : set 𝕜) (x : 𝕜) : F := (iterated_fderiv_within 𝕜 n f s x : ((fin n) → 𝕜) → F) (λ(i : fin n), 1) variables {n : ℕ} {f : 𝕜 → F} {s : set 𝕜} {x : 𝕜} lemma iterated_deriv_within_univ : iterated_deriv_within n f univ = iterated_deriv n f := by { ext x, rw [iterated_deriv_within, iterated_deriv, iterated_fderiv_within_univ] } /-! ### Properties of the iterated derivative within a set -/ lemma iterated_deriv_within_eq_iterated_fderiv_within : iterated_deriv_within n f s x = (iterated_fderiv_within 𝕜 n f s x : ((fin n) → 𝕜) → F) (λ(i : fin n), 1) := rfl /-- Write the iterated derivative as the composition of a continuous linear equiv and the iterated Fréchet derivative -/ lemma iterated_deriv_within_eq_equiv_comp : iterated_deriv_within n f s = (continuous_multilinear_map.pi_field_equiv 𝕜 (fin n) F).symm ∘ (iterated_fderiv_within 𝕜 n f s) := by { ext x, refl } /-- Write the iterated Fréchet derivative as the composition of a continuous linear equiv and the iterated derivative. -/ lemma iterated_fderiv_within_eq_equiv_comp : iterated_fderiv_within 𝕜 n f s = (continuous_multilinear_map.pi_field_equiv 𝕜 (fin n) F) ∘ (iterated_deriv_within n f s) := by rw [iterated_deriv_within_eq_equiv_comp, ← function.comp.assoc, linear_isometry_equiv.self_comp_symm, function.left_id] /-- The `n`-th Fréchet derivative applied to a vector `(m 0, ..., m (n-1))` is the derivative multiplied by the product of the `m i`s. -/ lemma iterated_fderiv_within_apply_eq_iterated_deriv_within_mul_prod {m : (fin n) → 𝕜} : (iterated_fderiv_within 𝕜 n f s x : ((fin n) → 𝕜) → F) m = (∏ i, m i) • iterated_deriv_within n f s x := begin rw [iterated_deriv_within_eq_iterated_fderiv_within, ← continuous_multilinear_map.map_smul_univ], simp end @[simp] lemma iterated_deriv_within_zero : iterated_deriv_within 0 f s = f := by { ext x, simp [iterated_deriv_within] } @[simp] lemma iterated_deriv_within_one (hs : unique_diff_on 𝕜 s) {x : 𝕜} (hx : x ∈ s): iterated_deriv_within 1 f s x = deriv_within f s x := by { simp [iterated_deriv_within, iterated_fderiv_within_one_apply hs hx], refl } /-- If the first `n` derivatives within a set of a function are continuous, and its first `n-1` derivatives are differentiable, then the function is `C^n`. This is not an equivalence in general, but this is an equivalence when the set has unique derivatives, see `times_cont_diff_on_iff_continuous_on_differentiable_on_deriv`. -/ lemma times_cont_diff_on_of_continuous_on_differentiable_on_deriv {n : with_top ℕ} (Hcont : ∀ (m : ℕ), (m : with_top ℕ) ≤ n → continuous_on (λ x, iterated_deriv_within m f s x) s) (Hdiff : ∀ (m : ℕ), (m : with_top ℕ) < n → differentiable_on 𝕜 (λ x, iterated_deriv_within m f s x) s) : times_cont_diff_on 𝕜 n f s := begin apply times_cont_diff_on_of_continuous_on_differentiable_on, { simpa [iterated_fderiv_within_eq_equiv_comp, linear_isometry_equiv.comp_continuous_on_iff] }, { simpa [iterated_fderiv_within_eq_equiv_comp, linear_isometry_equiv.comp_differentiable_on_iff] } end /-- To check that a function is `n` times continuously differentiable, it suffices to check that its first `n` derivatives are differentiable. This is slightly too strong as the condition we require on the `n`-th derivative is differentiability instead of continuity, but it has the advantage of avoiding the discussion of continuity in the proof (and for `n = ∞` this is optimal). -/ lemma times_cont_diff_on_of_differentiable_on_deriv {n : with_top ℕ} (h : ∀(m : ℕ), (m : with_top ℕ) ≤ n → differentiable_on 𝕜 (iterated_deriv_within m f s) s) : times_cont_diff_on 𝕜 n f s := begin apply times_cont_diff_on_of_differentiable_on, simpa only [iterated_fderiv_within_eq_equiv_comp, linear_isometry_equiv.comp_differentiable_on_iff] end /-- On a set with unique derivatives, a `C^n` function has derivatives up to `n` which are continuous. -/ lemma times_cont_diff_on.continuous_on_iterated_deriv_within {n : with_top ℕ} {m : ℕ} (h : times_cont_diff_on 𝕜 n f s) (hmn : (m : with_top ℕ) ≤ n) (hs : unique_diff_on 𝕜 s) : continuous_on (iterated_deriv_within m f s) s := by simpa only [iterated_deriv_within_eq_equiv_comp, linear_isometry_equiv.comp_continuous_on_iff] using h.continuous_on_iterated_fderiv_within hmn hs /-- On a set with unique derivatives, a `C^n` function has derivatives less than `n` which are differentiable. -/ lemma times_cont_diff_on.differentiable_on_iterated_deriv_within {n : with_top ℕ} {m : ℕ} (h : times_cont_diff_on 𝕜 n f s) (hmn : (m : with_top ℕ) < n) (hs : unique_diff_on 𝕜 s) : differentiable_on 𝕜 (iterated_deriv_within m f s) s := by simpa only [iterated_deriv_within_eq_equiv_comp, linear_isometry_equiv.comp_differentiable_on_iff] using h.differentiable_on_iterated_fderiv_within hmn hs /-- The property of being `C^n`, initially defined in terms of the Fréchet derivative, can be reformulated in terms of the one-dimensional derivative on sets with unique derivatives. -/ lemma times_cont_diff_on_iff_continuous_on_differentiable_on_deriv {n : with_top ℕ} (hs : unique_diff_on 𝕜 s) : times_cont_diff_on 𝕜 n f s ↔ (∀m:ℕ, (m : with_top ℕ) ≤ n → continuous_on (iterated_deriv_within m f s) s) ∧ (∀m:ℕ, (m : with_top ℕ) < n → differentiable_on 𝕜 (iterated_deriv_within m f s) s) := by simp only [times_cont_diff_on_iff_continuous_on_differentiable_on hs, iterated_fderiv_within_eq_equiv_comp, linear_isometry_equiv.comp_continuous_on_iff, linear_isometry_equiv.comp_differentiable_on_iff] /-- The `n+1`-th iterated derivative within a set with unique derivatives can be obtained by differentiating the `n`-th iterated derivative. -/ lemma iterated_deriv_within_succ {x : 𝕜} (hxs : unique_diff_within_at 𝕜 s x) : iterated_deriv_within (n + 1) f s x = deriv_within (iterated_deriv_within n f s) s x := begin rw [iterated_deriv_within_eq_iterated_fderiv_within, iterated_fderiv_within_succ_apply_left, iterated_fderiv_within_eq_equiv_comp, linear_isometry_equiv.comp_fderiv_within _ hxs, deriv_within], change ((continuous_multilinear_map.mk_pi_field 𝕜 (fin n) ((fderiv_within 𝕜 (iterated_deriv_within n f s) s x : 𝕜 → F) 1)) : (fin n → 𝕜 ) → F) (λ (i : fin n), 1) = (fderiv_within 𝕜 (iterated_deriv_within n f s) s x : 𝕜 → F) 1, simp end /-- The `n`-th iterated derivative within a set with unique derivatives can be obtained by iterating `n` times the differentiation operation. -/ lemma iterated_deriv_within_eq_iterate {x : 𝕜} (hs : unique_diff_on 𝕜 s) (hx : x ∈ s) : iterated_deriv_within n f s x = ((λ (g : 𝕜 → F), deriv_within g s)^[n]) f x := begin induction n with n IH generalizing x, { simp }, { rw [iterated_deriv_within_succ (hs x hx), function.iterate_succ'], exact deriv_within_congr (hs x hx) (λ y hy, IH hy) (IH hx) } end /-- The `n+1`-th iterated derivative within a set with unique derivatives can be obtained by taking the `n`-th derivative of the derivative. -/ lemma iterated_deriv_within_succ' {x : 𝕜} (hxs : unique_diff_on 𝕜 s) (hx : x ∈ s) : iterated_deriv_within (n + 1) f s x = (iterated_deriv_within n (deriv_within f s) s) x := by { rw [iterated_deriv_within_eq_iterate hxs hx, iterated_deriv_within_eq_iterate hxs hx], refl } /-! ### Properties of the iterated derivative on the whole space -/ lemma iterated_deriv_eq_iterated_fderiv : iterated_deriv n f x = (iterated_fderiv 𝕜 n f x : ((fin n) → 𝕜) → F) (λ(i : fin n), 1) := rfl /-- Write the iterated derivative as the composition of a continuous linear equiv and the iterated Fréchet derivative -/ lemma iterated_deriv_eq_equiv_comp : iterated_deriv n f = (continuous_multilinear_map.pi_field_equiv 𝕜 (fin n) F).symm ∘ (iterated_fderiv 𝕜 n f) := by { ext x, refl } /-- Write the iterated Fréchet derivative as the composition of a continuous linear equiv and the iterated derivative. -/ lemma iterated_fderiv_eq_equiv_comp : iterated_fderiv 𝕜 n f = (continuous_multilinear_map.pi_field_equiv 𝕜 (fin n) F) ∘ (iterated_deriv n f) := by rw [iterated_deriv_eq_equiv_comp, ← function.comp.assoc, linear_isometry_equiv.self_comp_symm, function.left_id] /-- The `n`-th Fréchet derivative applied to a vector `(m 0, ..., m (n-1))` is the derivative multiplied by the product of the `m i`s. -/ lemma iterated_fderiv_apply_eq_iterated_deriv_mul_prod {m : (fin n) → 𝕜} : (iterated_fderiv 𝕜 n f x : ((fin n) → 𝕜) → F) m = (∏ i, m i) • iterated_deriv n f x := by { rw [iterated_deriv_eq_iterated_fderiv, ← continuous_multilinear_map.map_smul_univ], simp } @[simp] lemma iterated_deriv_zero : iterated_deriv 0 f = f := by { ext x, simp [iterated_deriv] } @[simp] lemma iterated_deriv_one : iterated_deriv 1 f = deriv f := by { ext x, simp [iterated_deriv], refl } /-- The property of being `C^n`, initially defined in terms of the Fréchet derivative, can be reformulated in terms of the one-dimensional derivative. -/ lemma times_cont_diff_iff_iterated_deriv {n : with_top ℕ} : times_cont_diff 𝕜 n f ↔ (∀m:ℕ, (m : with_top ℕ) ≤ n → continuous (iterated_deriv m f)) ∧ (∀m:ℕ, (m : with_top ℕ) < n → differentiable 𝕜 (iterated_deriv m f)) := by simp only [times_cont_diff_iff_continuous_differentiable, iterated_fderiv_eq_equiv_comp, linear_isometry_equiv.comp_continuous_iff, linear_isometry_equiv.comp_differentiable_iff] /-- To check that a function is `n` times continuously differentiable, it suffices to check that its first `n` derivatives are differentiable. This is slightly too strong as the condition we require on the `n`-th derivative is differentiability instead of continuity, but it has the advantage of avoiding the discussion of continuity in the proof (and for `n = ∞` this is optimal). -/ lemma times_cont_diff_of_differentiable_iterated_deriv {n : with_top ℕ} (h : ∀(m : ℕ), (m : with_top ℕ) ≤ n → differentiable 𝕜 (iterated_deriv m f)) : times_cont_diff 𝕜 n f := times_cont_diff_iff_iterated_deriv.2 ⟨λ m hm, (h m hm).continuous, λ m hm, (h m (le_of_lt hm))⟩ lemma times_cont_diff.continuous_iterated_deriv {n : with_top ℕ} (m : ℕ) (h : times_cont_diff 𝕜 n f) (hmn : (m : with_top ℕ) ≤ n) : continuous (iterated_deriv m f) := (times_cont_diff_iff_iterated_deriv.1 h).1 m hmn lemma times_cont_diff.differentiable_iterated_deriv {n : with_top ℕ} (m : ℕ) (h : times_cont_diff 𝕜 n f) (hmn : (m : with_top ℕ) < n) : differentiable 𝕜 (iterated_deriv m f) := (times_cont_diff_iff_iterated_deriv.1 h).2 m hmn /-- The `n+1`-th iterated derivative can be obtained by differentiating the `n`-th iterated derivative. -/ lemma iterated_deriv_succ : iterated_deriv (n + 1) f = deriv (iterated_deriv n f) := begin ext x, rw [← iterated_deriv_within_univ, ← iterated_deriv_within_univ, ← deriv_within_univ], exact iterated_deriv_within_succ unique_diff_within_at_univ, end /-- The `n`-th iterated derivative can be obtained by iterating `n` times the differentiation operation. -/ lemma iterated_deriv_eq_iterate : iterated_deriv n f = (deriv^[n]) f := begin ext x, rw [← iterated_deriv_within_univ], convert iterated_deriv_within_eq_iterate unique_diff_on_univ (mem_univ x), simp [deriv_within_univ] end /-- The `n+1`-th iterated derivative can be obtained by taking the `n`-th derivative of the derivative. -/ lemma iterated_deriv_succ' : iterated_deriv (n + 1) f = iterated_deriv n (deriv f) := by { rw [iterated_deriv_eq_iterate, iterated_deriv_eq_iterate], refl }
8e750e0e96ff3a5f83c06aa4ed83d81c1a2fffd6
1a61aba1b67cddccce19532a9596efe44be4285f
/hott/types/trunc.hlean
f35de985d9fb25c6bae871c96f10ae2d12c2435a
[ "Apache-2.0" ]
permissive
eigengrau/lean
07986a0f2548688c13ba36231f6cdbee82abf4c6
f8a773be1112015e2d232661ce616d23f12874d0
refs/heads/master
1,610,939,198,566
1,441,352,386,000
1,441,352,494,000
41,903,576
0
0
null
1,441,352,210,000
1,441,352,210,000
null
UTF-8
Lean
false
false
9,917
hlean
/- Copyright (c) 2015 Jakob von Raumer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn Properties of is_trunc and trunctype -/ -- NOTE: the fact that (is_trunc n A) is a mere proposition is proved in .hprop_trunc import types.pi types.eq types.equiv ..function open eq sigma sigma.ops pi function equiv is_trunc.trunctype is_equiv prod is_trunc.trunc_index pointed nat namespace is_trunc variables {A B : Type} {n : trunc_index} /- theorems about trunctype -/ protected definition trunctype.sigma_char.{l} (n : trunc_index) : (trunctype.{l} n) ≃ (Σ (A : Type.{l}), is_trunc n A) := begin fapply equiv.MK, { intro A, exact (⟨carrier A, struct A⟩)}, { intro S, exact (trunctype.mk S.1 S.2)}, { intro S, induction S with S1 S2, reflexivity}, { intro A, induction A with A1 A2, reflexivity}, end definition trunctype_eq_equiv (n : trunc_index) (A B : n-Type) : (A = B) ≃ (carrier A = carrier B) := calc (A = B) ≃ (to_fun (trunctype.sigma_char n) A = to_fun (trunctype.sigma_char n) B) : eq_equiv_fn_eq_of_equiv ... ≃ ((to_fun (trunctype.sigma_char n) A).1 = (to_fun (trunctype.sigma_char n) B).1) : equiv.symm (!equiv_subtype) ... ≃ (carrier A = carrier B) : equiv.refl definition is_trunc_is_embedding_closed (f : A → B) [Hf : is_embedding f] [HB : is_trunc n B] (Hn : -1 ≤ n) : is_trunc n A := begin induction n with n, {exact !empty.elim Hn}, {apply is_trunc_succ_intro, intro a a', fapply @is_trunc_is_equiv_closed_rev _ _ n (ap f)} end definition is_trunc_is_retraction_closed (f : A → B) [Hf : is_retraction f] (n : trunc_index) [HA : is_trunc n A] : is_trunc n B := begin revert A B f Hf HA, induction n with n IH, { intro A B f Hf HA, induction Hf with g ε, fapply is_contr.mk, { exact f (center A)}, { intro b, apply concat, { apply (ap f), exact (center_eq (g b))}, { apply ε}}}, { intro A B f Hf HA, induction Hf with g ε, apply is_trunc_succ_intro, intro b b', fapply (IH (g b = g b')), { intro q, exact ((ε b)⁻¹ ⬝ ap f q ⬝ ε b')}, { apply (is_retraction.mk (ap g)), { intro p, induction p, {rewrite [↑ap, con.left_inv]}}}, { apply is_trunc_eq}} end definition is_embedding_to_fun (A B : Type) : is_embedding (@to_fun A B) := is_embedding.mk (λf f', !is_equiv_ap_to_fun) definition is_trunc_trunctype [instance] (n : trunc_index) : is_trunc n.+1 (n-Type) := begin apply is_trunc_succ_intro, intro X Y, fapply is_trunc_equiv_closed, {apply equiv.symm, apply trunctype_eq_equiv}, fapply is_trunc_equiv_closed, {apply equiv.symm, apply eq_equiv_equiv}, induction n, {apply @is_contr_of_inhabited_hprop, {apply is_trunc_is_embedding_closed, {apply is_embedding_to_fun} , {exact unit.star}}, {apply equiv_of_is_contr_of_is_contr}}, {apply is_trunc_is_embedding_closed, {apply is_embedding_to_fun}, {exact unit.star}} end /- theorems about decidable equality and axiom K -/ definition is_hset_of_axiom_K {A : Type} (K : Π{a : A} (p : a = a), p = idp) : is_hset A := is_hset.mk _ (λa b p q, eq.rec_on q K p) theorem is_hset_of_relation.{u} {A : Type.{u}} (R : A → A → Type.{u}) (mere : Π(a b : A), is_hprop (R a b)) (refl : Π(a : A), R a a) (imp : Π{a b : A}, R a b → a = b) : is_hset A := is_hset_of_axiom_K (λa p, have H2 : transport (λx, R a x → a = x) p (@imp a a) = @imp a a, from !apd, have H3 : Π(r : R a a), transport (λx, a = x) p (imp r) = imp (transport (λx, R a x) p r), from to_fun (equiv.symm !heq_pi) H2, have H4 : imp (refl a) ⬝ p = imp (refl a), from calc imp (refl a) ⬝ p = transport (λx, a = x) p (imp (refl a)) : transport_eq_r ... = imp (transport (λx, R a x) p (refl a)) : H3 ... = imp (refl a) : is_hprop.elim, cancel_left H4) definition relation_equiv_eq {A : Type} (R : A → A → Type) (mere : Π(a b : A), is_hprop (R a b)) (refl : Π(a : A), R a a) (imp : Π{a b : A}, R a b → a = b) (a b : A) : R a b ≃ a = b := @equiv_of_is_hprop _ _ _ (@is_trunc_eq _ _ (is_hset_of_relation R mere refl @imp) a b) imp (λp, p ▸ refl a) local attribute not [reducible] definition is_hset_of_double_neg_elim {A : Type} (H : Π(a b : A), ¬¬a = b → a = b) : is_hset A := is_hset_of_relation (λa b, ¬¬a = b) _ (λa n, n idp) H section open decidable --this is proven differently in init.hedberg definition is_hset_of_decidable_eq (A : Type) [H : decidable_eq A] : is_hset A := is_hset_of_double_neg_elim (λa b, by_contradiction) end definition is_trunc_of_axiom_K_of_leq {A : Type} (n : trunc_index) (H : -1 ≤ n) (K : Π(a : A), is_trunc n (a = a)) : is_trunc (n.+1) A := @is_trunc_succ_intro _ _ (λa b, is_trunc_of_imp_is_trunc_of_leq H (λp, eq.rec_on p !K)) definition is_trunc_succ_of_is_trunc_loop (Hn : -1 ≤ n) (Hp : Π(a : A), is_trunc n (a = a)) : is_trunc (n.+1) A := begin apply is_trunc_succ_intro, intros a a', apply is_trunc_of_imp_is_trunc_of_leq Hn, intro p, induction p, apply Hp end definition is_trunc_succ_iff_is_trunc_loop (A : Type) (Hn : -1 ≤ n) : is_trunc (n.+1) A ↔ Π(a : A), is_trunc n (a = a) := iff.intro _ (is_trunc_succ_of_is_trunc_loop Hn) definition is_trunc_iff_is_contr_loop_succ (n : ℕ) (A : Type) : is_trunc n A ↔ Π(a : A), is_contr (Ω[succ n](Pointed.mk a)) := begin revert A, induction n with n IH, { intros, esimp [Iterated_loop_space], apply iff.intro, { intros H a, apply is_contr.mk idp, apply is_hprop.elim}, { intro H, apply is_hset_of_axiom_K, intros, apply is_hprop.elim}}, { intros, transitivity _, apply @is_trunc_succ_iff_is_trunc_loop n, constructor, apply iff.pi_iff_pi, intros, transitivity _, apply IH, assert H : Πp : a = a, Ω(Pointed.mk p) = Ω(Pointed.mk (idpath a)), { intros, fapply Pointed_eq, { esimp, transitivity _, apply eq_equiv_fn_eq_of_equiv (equiv_eq_closed_right _ p⁻¹), esimp, apply eq_equiv_eq_closed, apply con.right_inv, apply con.right_inv}, { esimp, apply con.left_inv}}, transitivity _, apply iff.pi_iff_pi, intro p, rewrite [↑Iterated_loop_space,H], apply iff.refl, apply iff.imp_iff, reflexivity} end definition is_trunc_iff_is_contr_loop (n : ℕ) (A : Type) : is_trunc (n.-2.+1) A ↔ (Π(a : A), is_contr (Ω[n](pointed.Mk a))) := begin induction n with n, { esimp [sub_two,Iterated_loop_space], apply iff.intro, intro H a, exact is_contr_of_inhabited_hprop a, intro H, apply is_hprop_of_imp_is_contr, exact H}, { apply is_trunc_iff_is_contr_loop_succ}, end end is_trunc open is_trunc namespace trunc variable {A : Type} protected definition code (n : trunc_index) (aa aa' : trunc n.+1 A) : n-Type := trunc.rec_on aa (λa, trunc.rec_on aa' (λa', trunctype.mk' n (trunc n (a = a')))) protected definition encode (n : trunc_index) (aa aa' : trunc n.+1 A) : aa = aa' → trunc.code n aa aa' := begin intro p, induction p, apply (trunc.rec_on aa), intro a, esimp [trunc.code,trunc.rec_on], exact (tr idp) end protected definition decode (n : trunc_index) (aa aa' : trunc n.+1 A) : trunc.code n aa aa' → aa = aa' := begin eapply (trunc.rec_on aa'), eapply (trunc.rec_on aa), intro a a' x, esimp [trunc.code, trunc.rec_on] at x, apply (trunc.rec_on x), intro p, exact (ap tr p) end definition trunc_eq_equiv (n : trunc_index) (aa aa' : trunc n.+1 A) : aa = aa' ≃ trunc.code n aa aa' := begin fapply equiv.MK, { apply trunc.encode}, { apply trunc.decode}, { eapply (trunc.rec_on aa'), eapply (trunc.rec_on aa), intro a a' x, esimp [trunc.code, trunc.rec_on] at x, refine (@trunc.rec_on n _ _ x _ _), intro x, apply is_trunc_eq, intro p, induction p, reflexivity}, { intro p, induction p, apply (trunc.rec_on aa), intro a, exact idp}, end definition tr_eq_tr_equiv (n : trunc_index) (a a' : A) : (tr a = tr a' :> trunc n.+1 A) ≃ trunc n (a = a') := !trunc_eq_equiv definition is_trunc_trunc_of_is_trunc [instance] [priority 500] (A : Type) (n m : trunc_index) [H : is_trunc n A] : is_trunc n (trunc m A) := begin revert A m H, eapply (trunc_index.rec_on n), { clear n, intro A m H, apply is_contr_equiv_closed, { apply equiv.symm, apply trunc_equiv, apply (@is_trunc_of_leq _ -2), exact unit.star} }, { clear n, intro n IH A m H, induction m with m, { apply (@is_trunc_of_leq _ -2), exact unit.star}, { apply is_trunc_succ_intro, intro aa aa', apply (@trunc.rec_on _ _ _ aa (λy, !is_trunc_succ_of_is_hprop)), eapply (@trunc.rec_on _ _ _ aa' (λy, !is_trunc_succ_of_is_hprop)), intro a a', apply (is_trunc_equiv_closed_rev), { apply tr_eq_tr_equiv}, { exact (IH _ _ _)}}} end open equiv.ops definition unique_choice {P : A → Type} [H : Πa, is_hprop (P a)] (f : Πa, ∥ P a ∥) (a : A) : P a := !trunc_equiv (f a) end trunc open trunc namespace function variables {A B : Type} definition is_surjective_of_is_equiv [instance] (f : A → B) [H : is_equiv f] : is_surjective f := is_surjective.mk (λb, !center) definition is_equiv_equiv_is_embedding_times_is_surjective (f : A → B) : is_equiv f ≃ (is_embedding f × is_surjective f) := equiv_of_is_hprop (λH, (_, _)) (λP, prod.rec_on P (λH₁ H₂, !is_equiv_of_is_surjective_of_is_embedding)) end function
149df414d17b25170b052ee483f3aaf1f5e831bc
c777c32c8e484e195053731103c5e52af26a25d1
/src/ring_theory/perfection.lean
61ace5ec6eb2258855e3286a4a4975bccd79db09
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
25,477
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.char_p.pi import algebra.char_p.quotient import algebra.char_p.subring import algebra.ring.pi import analysis.special_functions.pow import field_theory.perfect_closure import ring_theory.localization.fraction_ring import ring_theory.subring.basic import ring_theory.valuation.integers /-! # Ring Perfection and Tilt In this file we define the perfection of a ring of characteristic p, and the tilt of a field given a valuation to `ℝ≥0`. ## TODO Define the valuation on the tilt, and define a characteristic predicate for the tilt. -/ universes u₁ u₂ u₃ u₄ open_locale nnreal /-- The perfection of a monoid `M`, defined to be the projective limit of `M` using the `p`-th power maps `M → M` indexed by the natural numbers, implemented as `{ f : ℕ → M | ∀ n, f (n + 1) ^ p = f n }`. -/ def monoid.perfection (M : Type u₁) [comm_monoid M] (p : ℕ) : submonoid (ℕ → M) := { carrier := { f | ∀ n, f (n + 1) ^ p = f n }, one_mem' := λ n, one_pow _, mul_mem' := λ f g hf hg n, (mul_pow _ _ _).trans $ congr_arg2 _ (hf n) (hg n) } /-- The perfection of a ring `R` with characteristic `p`, as a subsemiring, defined to be the projective limit of `R` using the Frobenius maps `R → R` indexed by the natural numbers, implemented as `{ f : ℕ → R | ∀ n, f (n + 1) ^ p = f n }`. -/ def ring.perfection_subsemiring (R : Type u₁) [comm_semiring R] (p : ℕ) [hp : fact p.prime] [char_p R p] : subsemiring (ℕ → R) := { zero_mem' := λ n, zero_pow $ hp.1.pos, add_mem' := λ f g hf hg n, (frobenius_add R p _ _).trans $ congr_arg2 _ (hf n) (hg n), .. monoid.perfection R p } /-- The perfection of a ring `R` with characteristic `p`, as a subring, defined to be the projective limit of `R` using the Frobenius maps `R → R` indexed by the natural numbers, implemented as `{ f : ℕ → R | ∀ n, f (n + 1) ^ p = f n }`. -/ def ring.perfection_subring (R : Type u₁) [comm_ring R] (p : ℕ) [hp : fact p.prime] [char_p R p] : subring (ℕ → R) := (ring.perfection_subsemiring R p).to_subring $ λ n, by simp_rw [← frobenius_def, pi.neg_apply, pi.one_apply, ring_hom.map_neg, ring_hom.map_one] /-- The perfection of a ring `R` with characteristic `p`, defined to be the projective limit of `R` using the Frobenius maps `R → R` indexed by the natural numbers, implemented as `{f : ℕ → R // ∀ n, f (n + 1) ^ p = f n}`. -/ def ring.perfection (R : Type u₁) [comm_semiring R] (p : ℕ) : Type u₁ := {f // ∀ (n : ℕ), (f : ℕ → R) (n + 1) ^ p = f n} namespace perfection variables (R : Type u₁) [comm_semiring R] (p : ℕ) [hp : fact p.prime] [char_p R p] include hp instance : comm_semiring (ring.perfection R p) := (ring.perfection_subsemiring R p).to_comm_semiring instance : char_p (ring.perfection R p) p := char_p.subsemiring (ℕ → R) p (ring.perfection_subsemiring R p) instance ring (R : Type u₁) [comm_ring R] [char_p R p] : ring (ring.perfection R p) := (ring.perfection_subring R p).to_ring instance comm_ring (R : Type u₁) [comm_ring R] [char_p R p] : comm_ring (ring.perfection R p) := (ring.perfection_subring R p).to_comm_ring instance : inhabited (ring.perfection R p) := ⟨0⟩ /-- The `n`-th coefficient of an element of the perfection. -/ def coeff (n : ℕ) : ring.perfection R p →+* R := { to_fun := λ f, f.1 n, map_one' := rfl, map_mul' := λ f g, rfl, map_zero' := rfl, map_add' := λ f g, rfl } variables {R p} @[ext] lemma ext {f g : ring.perfection R p} (h : ∀ n, coeff R p n f = coeff R p n g) : f = g := subtype.eq $ funext h variables (R p) /-- The `p`-th root of an element of the perfection. -/ def pth_root : ring.perfection R p →+* ring.perfection R p := { to_fun := λ f, ⟨λ n, coeff R p (n + 1) f, λ n, f.2 _⟩, map_one' := rfl, map_mul' := λ f g, rfl, map_zero' := rfl, map_add' := λ f g, rfl } variables {R p} @[simp] lemma coeff_mk (f : ℕ → R) (hf) (n : ℕ) : coeff R p n ⟨f, hf⟩ = f n := rfl lemma coeff_pth_root (f : ring.perfection R p) (n : ℕ) : coeff R p n (pth_root R p f) = coeff R p (n + 1) f := rfl lemma coeff_pow_p (f : ring.perfection R p) (n : ℕ) : coeff R p (n + 1) (f ^ p) = coeff R p n f := by { rw ring_hom.map_pow, exact f.2 n } lemma coeff_pow_p' (f : ring.perfection R p) (n : ℕ) : coeff R p (n + 1) f ^ p = coeff R p n f := f.2 n lemma coeff_frobenius (f : ring.perfection R p) (n : ℕ) : coeff R p (n + 1) (frobenius _ p f) = coeff R p n f := by apply coeff_pow_p f n -- `coeff_pow_p f n` also works but is slow! lemma coeff_iterate_frobenius (f : ring.perfection R p) (n m : ℕ) : coeff R p (n + m) (frobenius _ p ^[m] f) = coeff R p n f := nat.rec_on m rfl $ λ m ih, by erw [function.iterate_succ_apply', coeff_frobenius, ih] lemma coeff_iterate_frobenius' (f : ring.perfection R p) (n m : ℕ) (hmn : m ≤ n) : coeff R p n (frobenius _ p ^[m] f) = coeff R p (n - m) f := eq.symm $ (coeff_iterate_frobenius _ _ m).symm.trans $ (tsub_add_cancel_of_le hmn).symm ▸ rfl lemma pth_root_frobenius : (pth_root R p).comp (frobenius _ p) = ring_hom.id _ := ring_hom.ext $ λ x, ext $ λ n, by rw [ring_hom.comp_apply, ring_hom.id_apply, coeff_pth_root, coeff_frobenius] lemma frobenius_pth_root : (frobenius _ p).comp (pth_root R p) = ring_hom.id _ := ring_hom.ext $ λ x, ext $ λ n, by rw [ring_hom.comp_apply, ring_hom.id_apply, ring_hom.map_frobenius, coeff_pth_root, ← ring_hom.map_frobenius, coeff_frobenius] lemma coeff_add_ne_zero {f : ring.perfection R p} {n : ℕ} (hfn : coeff R p n f ≠ 0) (k : ℕ) : coeff R p (n + k) f ≠ 0 := nat.rec_on k hfn $ λ k ih h, ih $ by erw [← coeff_pow_p, ring_hom.map_pow, h, zero_pow hp.1.pos] lemma coeff_ne_zero_of_le {f : ring.perfection R p} {m n : ℕ} (hfm : coeff R p m f ≠ 0) (hmn : m ≤ n) : coeff R p n f ≠ 0 := let ⟨k, hk⟩ := nat.exists_eq_add_of_le hmn in hk.symm ▸ coeff_add_ne_zero hfm k variables (R p) instance perfect_ring : perfect_ring (ring.perfection R p) p := { pth_root' := pth_root R p, frobenius_pth_root' := congr_fun $ congr_arg ring_hom.to_fun $ @frobenius_pth_root R _ p _ _, pth_root_frobenius' := congr_fun $ congr_arg ring_hom.to_fun $ @pth_root_frobenius R _ p _ _ } /-- Given rings `R` and `S` of characteristic `p`, with `R` being perfect, any homomorphism `R →+* S` can be lifted to a homomorphism `R →+* perfection S p`. -/ @[simps] def lift (R : Type u₁) [comm_semiring R] [char_p R p] [perfect_ring R p] (S : Type u₂) [comm_semiring S] [char_p S p] : (R →+* S) ≃ (R →+* ring.perfection S p) := { to_fun := λ f, { to_fun := λ r, ⟨λ n, f $ _root_.pth_root R p ^[n] r, λ n, by rw [← f.map_pow, function.iterate_succ_apply', pth_root_pow_p]⟩, map_one' := ext $ λ n, (congr_arg f $ ring_hom.iterate_map_one _ _).trans f.map_one, map_mul' := λ x y, ext $ λ n, (congr_arg f $ ring_hom.iterate_map_mul _ _ _ _).trans $ f.map_mul _ _, map_zero' := ext $ λ n, (congr_arg f $ ring_hom.iterate_map_zero _ _).trans f.map_zero, map_add' := λ x y, ext $ λ n, (congr_arg f $ ring_hom.iterate_map_add _ _ _ _).trans $ f.map_add _ _ }, inv_fun := ring_hom.comp $ coeff S p 0, left_inv := λ f, ring_hom.ext $ λ r, rfl, right_inv := λ f, ring_hom.ext $ λ r, ext $ λ n, show coeff S p 0 (f (_root_.pth_root R p ^[n] r)) = coeff S p n (f r), by rw [← coeff_iterate_frobenius _ 0 n, zero_add, ← ring_hom.map_iterate_frobenius, right_inverse_pth_root_frobenius.iterate] } lemma hom_ext {R : Type u₁} [comm_semiring R] [char_p R p] [perfect_ring R p] {S : Type u₂} [comm_semiring S] [char_p S p] {f g : R →+* ring.perfection S p} (hfg : ∀ x, coeff S p 0 (f x) = coeff S p 0 (g x)) : f = g := (lift p R S).symm.injective $ ring_hom.ext hfg variables {R} {S : Type u₂} [comm_semiring S] [char_p S p] /-- A ring homomorphism `R →+* S` induces `perfection R p →+* perfection S p` -/ @[simps] def map (φ : R →+* S) : ring.perfection R p →+* ring.perfection S p := { to_fun := λ f, ⟨λ n, φ (coeff R p n f), λ n, by rw [← φ.map_pow, coeff_pow_p']⟩, map_one' := subtype.eq $ funext $ λ n, φ.map_one, map_mul' := λ f g, subtype.eq $ funext $ λ n, φ.map_mul _ _, map_zero' := subtype.eq $ funext $ λ n, φ.map_zero, map_add' := λ f g, subtype.eq $ funext $ λ n, φ.map_add _ _ } lemma coeff_map (φ : R →+* S) (f : ring.perfection R p) (n : ℕ) : coeff S p n (map p φ f) = φ (coeff R p n f) := rfl end perfection /-- A perfection map to a ring of characteristic `p` is a map that is isomorphic to its perfection. -/ @[nolint has_nonempty_instance] structure perfection_map (p : ℕ) [fact p.prime] {R : Type u₁} [comm_semiring R] [char_p R p] {P : Type u₂} [comm_semiring P] [char_p P p] [perfect_ring P p] (π : P →+* R) : Prop := (injective : ∀ ⦃x y : P⦄, (∀ n, π (pth_root P p ^[n] x) = π (pth_root P p ^[n] y)) → x = y) (surjective : ∀ f : ℕ → R, (∀ n, f (n + 1) ^ p = f n) → ∃ x : P, ∀ n, π (pth_root P p ^[n] x) = f n) namespace perfection_map variables {p : ℕ} [fact p.prime] variables {R : Type u₁} [comm_semiring R] [char_p R p] variables {P : Type u₃} [comm_semiring P] [char_p P p] [perfect_ring P p] /-- Create a `perfection_map` from an isomorphism to the perfection. -/ @[simps] lemma mk' {f : P →+* R} (g : P ≃+* ring.perfection R p) (hfg : perfection.lift p P R f = g) : perfection_map p f := { injective := λ x y hxy, g.injective $ (ring_hom.ext_iff.1 hfg x).symm.trans $ eq.symm $ (ring_hom.ext_iff.1 hfg y).symm.trans $ perfection.ext $ λ n, (hxy n).symm, surjective := λ y hy, let ⟨x, hx⟩ := g.surjective ⟨y, hy⟩ in ⟨x, λ n, show perfection.coeff R p n (perfection.lift p P R f x) = perfection.coeff R p n ⟨y, hy⟩, by rw [hfg, ← coe_fn_coe_base, hx]⟩ } variables (p R P) /-- The canonical perfection map from the perfection of a ring. -/ lemma of : perfection_map p (perfection.coeff R p 0) := mk' (ring_equiv.refl _) $ (equiv.apply_eq_iff_eq_symm_apply _).2 rfl /-- For a perfect ring, it itself is the perfection. -/ lemma id [perfect_ring R p] : perfection_map p (ring_hom.id R) := { injective := λ x y hxy, hxy 0, surjective := λ f hf, ⟨f 0, λ n, show pth_root R p ^[n] (f 0) = f n, from nat.rec_on n rfl $ λ n ih, injective_pow_p p $ by rw [function.iterate_succ_apply', pth_root_pow_p _, ih, hf]⟩ } variables {p R P} /-- A perfection map induces an isomorphism to the prefection. -/ noncomputable def equiv {π : P →+* R} (m : perfection_map p π) : P ≃+* ring.perfection R p := ring_equiv.of_bijective (perfection.lift p P R π) ⟨λ x y hxy, m.injective $ λ n, (congr_arg (perfection.coeff R p n) hxy : _), λ f, let ⟨x, hx⟩ := m.surjective f.1 f.2 in ⟨x, perfection.ext $ hx⟩⟩ lemma equiv_apply {π : P →+* R} (m : perfection_map p π) (x : P) : m.equiv x = perfection.lift p P R π x := rfl lemma comp_equiv {π : P →+* R} (m : perfection_map p π) (x : P) : perfection.coeff R p 0 (m.equiv x) = π x := rfl lemma comp_equiv' {π : P →+* R} (m : perfection_map p π) : (perfection.coeff R p 0).comp ↑m.equiv = π := ring_hom.ext $ λ x, rfl lemma comp_symm_equiv {π : P →+* R} (m : perfection_map p π) (f : ring.perfection R p) : π (m.equiv.symm f) = perfection.coeff R p 0 f := (m.comp_equiv _).symm.trans $ congr_arg _ $ m.equiv.apply_symm_apply f lemma comp_symm_equiv' {π : P →+* R} (m : perfection_map p π) : π.comp ↑m.equiv.symm = perfection.coeff R p 0 := ring_hom.ext m.comp_symm_equiv variables (p R P) /-- Given rings `R` and `S` of characteristic `p`, with `R` being perfect, any homomorphism `R →+* S` can be lifted to a homomorphism `R →+* P`, where `P` is any perfection of `S`. -/ @[simps] noncomputable def lift [perfect_ring R p] (S : Type u₂) [comm_semiring S] [char_p S p] (P : Type u₃) [comm_semiring P] [char_p P p] [perfect_ring P p] (π : P →+* S) (m : perfection_map p π) : (R →+* S) ≃ (R →+* P) := { to_fun := λ f, ring_hom.comp ↑m.equiv.symm $ perfection.lift p R S f, inv_fun := λ f, π.comp f, left_inv := λ f, by { simp_rw [← ring_hom.comp_assoc, comp_symm_equiv'], exact (perfection.lift p R S).symm_apply_apply f }, right_inv := λ f, ring_hom.ext $ λ x, m.equiv.injective $ (m.equiv.apply_symm_apply _).trans $ show perfection.lift p R S (π.comp f) x = ring_hom.comp ↑m.equiv f x, from ring_hom.ext_iff.1 ((perfection.lift p R S).apply_eq_iff_eq_symm_apply.2 rfl) _ } variables {R p} lemma hom_ext [perfect_ring R p] {S : Type u₂} [comm_semiring S] [char_p S p] {P : Type u₃} [comm_semiring P] [char_p P p] [perfect_ring P p] (π : P →+* S) (m : perfection_map p π) {f g : R →+* P} (hfg : ∀ x, π (f x) = π (g x)) : f = g := (lift p R S P π m).symm.injective $ ring_hom.ext hfg variables {R P} (p) {S : Type u₂} [comm_semiring S] [char_p S p] variables {Q : Type u₄} [comm_semiring Q] [char_p Q p] [perfect_ring Q p] /-- A ring homomorphism `R →+* S` induces `P →+* Q`, a map of the respective perfections. -/ @[nolint unused_arguments] noncomputable def map {π : P →+* R} (m : perfection_map p π) {σ : Q →+* S} (n : perfection_map p σ) (φ : R →+* S) : P →+* Q := lift p P S Q σ n $ φ.comp π lemma comp_map {π : P →+* R} (m : perfection_map p π) {σ : Q →+* S} (n : perfection_map p σ) (φ : R →+* S) : σ.comp (map p m n φ) = φ.comp π := (lift p P S Q σ n).symm_apply_apply _ lemma map_map {π : P →+* R} (m : perfection_map p π) {σ : Q →+* S} (n : perfection_map p σ) (φ : R →+* S) (x : P) : σ (map p m n φ x) = φ (π x) := ring_hom.ext_iff.1 (comp_map p m n φ) x -- Why is this slow? lemma map_eq_map (φ : R →+* S) : @map p _ R _ _ _ _ _ _ S _ _ _ _ _ _ _ (of p R) _ (of p S) φ = perfection.map p φ := hom_ext _ (of p S) $ λ f, by rw [map_map, perfection.coeff_map] end perfection_map section perfectoid variables (K : Type u₁) [field K] (v : valuation K ℝ≥0) variables (O : Type u₂) [comm_ring O] [algebra O K] (hv : v.integers O) variables (p : ℕ) include hv /-- `O/(p)` for `O`, ring of integers of `K`. -/ @[nolint unused_arguments has_nonempty_instance] def mod_p := O ⧸ (ideal.span {p} : ideal O) variables [hp : fact p.prime] [hvp : fact (v p ≠ 1)] namespace mod_p instance : comm_ring (mod_p K v O hv p) := ideal.quotient.comm_ring _ include hp hvp instance : char_p (mod_p K v O hv p) p := char_p.quotient O p $ mt hv.one_of_is_unit $ (map_nat_cast (algebra_map O K) p).symm ▸ hvp.1 instance : nontrivial (mod_p K v O hv p) := char_p.nontrivial_of_char_ne_one hp.1.ne_one section classical local attribute [instance] classical.dec omit hp hvp /-- For a field `K` with valuation `v : K → ℝ≥0` and ring of integers `O`, a function `O/(p) → ℝ≥0` that sends `0` to `0` and `x + (p)` to `v(x)` as long as `x ∉ (p)`. -/ noncomputable def pre_val (x : mod_p K v O hv p) : ℝ≥0 := if x = 0 then 0 else v (algebra_map O K x.out') variables {K v O hv p} lemma pre_val_mk {x : O} (hx : (ideal.quotient.mk _ x : mod_p K v O hv p) ≠ 0) : pre_val K v O hv p (ideal.quotient.mk _ x) = v (algebra_map O K x) := begin obtain ⟨r, hr⟩ := ideal.mem_span_singleton'.1 (ideal.quotient.eq.1 $ quotient.sound' $ @quotient.mk_out' O (ideal.span {p} : ideal O).quotient_rel x), refine (if_neg hx).trans (v.map_eq_of_sub_lt $ lt_of_not_le _), erw [← ring_hom.map_sub, ← hr, hv.le_iff_dvd], exact λ hprx, hx (ideal.quotient.eq_zero_iff_mem.2 $ ideal.mem_span_singleton.2 $ dvd_of_mul_left_dvd hprx), end lemma pre_val_zero : pre_val K v O hv p 0 = 0 := if_pos rfl lemma pre_val_mul {x y : mod_p K v O hv p} (hxy0 : x * y ≠ 0) : pre_val K v O hv p (x * y) = pre_val K v O hv p x * pre_val K v O hv p y := begin have hx0 : x ≠ 0 := mt (by { rintro rfl, rw zero_mul }) hxy0, have hy0 : y ≠ 0 := mt (by { rintro rfl, rw mul_zero }) hxy0, obtain ⟨r, rfl⟩ := ideal.quotient.mk_surjective x, obtain ⟨s, rfl⟩ := ideal.quotient.mk_surjective y, rw ← ring_hom.map_mul at hxy0 ⊢, rw [pre_val_mk hx0, pre_val_mk hy0, pre_val_mk hxy0, ring_hom.map_mul, v.map_mul] end lemma pre_val_add (x y : mod_p K v O hv p) : pre_val K v O hv p (x + y) ≤ max (pre_val K v O hv p x) (pre_val K v O hv p y) := begin by_cases hx0 : x = 0, { rw [hx0, zero_add], exact le_max_right _ _ }, by_cases hy0 : y = 0, { rw [hy0, add_zero], exact le_max_left _ _ }, by_cases hxy0 : x + y = 0, { rw [hxy0, pre_val_zero], exact zero_le _ }, obtain ⟨r, rfl⟩ := ideal.quotient.mk_surjective x, obtain ⟨s, rfl⟩ := ideal.quotient.mk_surjective y, rw ← ring_hom.map_add at hxy0 ⊢, rw [pre_val_mk hx0, pre_val_mk hy0, pre_val_mk hxy0, ring_hom.map_add], exact v.map_add _ _ end lemma v_p_lt_pre_val {x : mod_p K v O hv p} : v p < pre_val K v O hv p x ↔ x ≠ 0 := begin refine ⟨λ h hx, by { rw [hx, pre_val_zero] at h, exact not_lt_zero' h }, λ h, lt_of_not_le $ λ hp, h _⟩, obtain ⟨r, rfl⟩ := ideal.quotient.mk_surjective x, rw [pre_val_mk h, ← map_nat_cast (algebra_map O K) p, hv.le_iff_dvd] at hp, rw [ideal.quotient.eq_zero_iff_mem, ideal.mem_span_singleton], exact hp end lemma pre_val_eq_zero {x : mod_p K v O hv p} : pre_val K v O hv p x = 0 ↔ x = 0 := ⟨λ hvx, classical.by_contradiction $ λ hx0 : x ≠ 0, by { rw [← v_p_lt_pre_val, hvx] at hx0, exact not_lt_zero' hx0 }, λ hx, hx.symm ▸ pre_val_zero⟩ variables (hv hvp) lemma v_p_lt_val {x : O} : v p < v (algebra_map O K x) ↔ (ideal.quotient.mk _ x : mod_p K v O hv p) ≠ 0 := by rw [lt_iff_not_le, not_iff_not, ← map_nat_cast (algebra_map O K) p, hv.le_iff_dvd, ideal.quotient.eq_zero_iff_mem, ideal.mem_span_singleton] open nnreal variables {hv} [hvp] include hp lemma mul_ne_zero_of_pow_p_ne_zero {x y : mod_p K v O hv p} (hx : x ^ p ≠ 0) (hy : y ^ p ≠ 0) : x * y ≠ 0 := begin obtain ⟨r, rfl⟩ := ideal.quotient.mk_surjective x, obtain ⟨s, rfl⟩ := ideal.quotient.mk_surjective y, have h1p : (0 : ℝ) < 1 / p := one_div_pos.2 (nat.cast_pos.2 hp.1.pos), rw ← ring_hom.map_mul, rw ← ring_hom.map_pow at hx hy, rw ← v_p_lt_val hv at hx hy ⊢, rw [ring_hom.map_pow, v.map_pow, ← rpow_lt_rpow_iff h1p, ← rpow_nat_cast, ← rpow_mul, mul_one_div_cancel (nat.cast_ne_zero.2 hp.1.ne_zero : (p : ℝ) ≠ 0), rpow_one] at hx hy, rw [ring_hom.map_mul, v.map_mul], refine lt_of_le_of_lt _ (mul_lt_mul₀ hx hy), by_cases hvp : v p = 0, { rw hvp, exact zero_le _ }, replace hvp := zero_lt_iff.2 hvp, conv_lhs { rw ← rpow_one (v p) }, rw ← rpow_add (ne_of_gt hvp), refine rpow_le_rpow_of_exponent_ge hvp (map_nat_cast (algebra_map O K) p ▸ hv.2 _) _, rw [← add_div, div_le_one (nat.cast_pos.2 hp.1.pos : 0 < (p : ℝ))], exact_mod_cast hp.1.two_le end end classical end mod_p /-- Perfection of `O/(p)` where `O` is the ring of integers of `K`. -/ @[nolint has_nonempty_instance] def pre_tilt := ring.perfection (mod_p K v O hv p) p include hp hvp namespace pre_tilt instance : comm_ring (pre_tilt K v O hv p) := perfection.comm_ring p _ instance : char_p (pre_tilt K v O hv p) p := perfection.char_p (mod_p K v O hv p) p section classical open_locale classical open perfection /-- The valuation `Perfection(O/(p)) → ℝ≥0` as a function. Given `f ∈ Perfection(O/(p))`, if `f = 0` then output `0`; otherwise output `pre_val(f(n))^(p^n)` for any `n` such that `f(n) ≠ 0`. -/ noncomputable def val_aux (f : pre_tilt K v O hv p) : ℝ≥0 := if h : ∃ n, coeff _ _ n f ≠ 0 then mod_p.pre_val K v O hv p (coeff _ _ (nat.find h) f) ^ (p ^ nat.find h) else 0 variables {K v O hv p} lemma coeff_nat_find_add_ne_zero {f : pre_tilt K v O hv p} {h : ∃ n, coeff _ _ n f ≠ 0} (k : ℕ) : coeff _ _ (nat.find h + k) f ≠ 0 := coeff_add_ne_zero (nat.find_spec h) k lemma val_aux_eq {f : pre_tilt K v O hv p} {n : ℕ} (hfn : coeff _ _ n f ≠ 0) : val_aux K v O hv p f = mod_p.pre_val K v O hv p (coeff _ _ n f) ^ (p ^ n) := begin have h : ∃ n, coeff _ _ n f ≠ 0 := ⟨n, hfn⟩, rw [val_aux, dif_pos h], obtain ⟨k, rfl⟩ := nat.exists_eq_add_of_le (nat.find_min' h hfn), induction k with k ih, { refl }, obtain ⟨x, hx⟩ := ideal.quotient.mk_surjective (coeff _ _ (nat.find h + k + 1) f), have h1 : (ideal.quotient.mk _ x : mod_p K v O hv p) ≠ 0 := hx.symm ▸ hfn, have h2 : (ideal.quotient.mk _ (x ^ p) : mod_p K v O hv p) ≠ 0, by { erw [ring_hom.map_pow, hx, ← ring_hom.map_pow, coeff_pow_p], exact coeff_nat_find_add_ne_zero k }, erw [ih (coeff_nat_find_add_ne_zero k), ← hx, ← coeff_pow_p, ring_hom.map_pow, ← hx, ← ring_hom.map_pow, mod_p.pre_val_mk h1, mod_p.pre_val_mk h2, ring_hom.map_pow, v.map_pow, ← pow_mul, pow_succ], refl end lemma val_aux_zero : val_aux K v O hv p 0 = 0 := dif_neg $ λ ⟨n, hn⟩, hn rfl lemma val_aux_one : val_aux K v O hv p 1 = 1 := (val_aux_eq $ show coeff (mod_p K v O hv p) p 0 1 ≠ 0, from one_ne_zero).trans $ by { rw [pow_zero, pow_one, ring_hom.map_one, ← (ideal.quotient.mk _).map_one, mod_p.pre_val_mk, ring_hom.map_one, v.map_one], change (1 : mod_p K v O hv p) ≠ 0, exact one_ne_zero } lemma val_aux_mul (f g : pre_tilt K v O hv p) : val_aux K v O hv p (f * g) = val_aux K v O hv p f * val_aux K v O hv p g := begin by_cases hf : f = 0, { rw [hf, zero_mul, val_aux_zero, zero_mul] }, by_cases hg : g = 0, { rw [hg, mul_zero, val_aux_zero, mul_zero] }, obtain ⟨m, hm⟩ : ∃ n, coeff _ _ n f ≠ 0 := not_forall.1 (λ h, hf $ perfection.ext h), obtain ⟨n, hn⟩ : ∃ n, coeff _ _ n g ≠ 0 := not_forall.1 (λ h, hg $ perfection.ext h), replace hm := coeff_ne_zero_of_le hm (le_max_left m n), replace hn := coeff_ne_zero_of_le hn (le_max_right m n), have hfg : coeff _ _ (max m n + 1) (f * g) ≠ 0, { rw ring_hom.map_mul, refine mod_p.mul_ne_zero_of_pow_p_ne_zero _ _, { rw [← ring_hom.map_pow, coeff_pow_p f], assumption }, { rw [← ring_hom.map_pow, coeff_pow_p g], assumption } }, rw [val_aux_eq (coeff_add_ne_zero hm 1), val_aux_eq (coeff_add_ne_zero hn 1), val_aux_eq hfg], rw ring_hom.map_mul at hfg ⊢, rw [mod_p.pre_val_mul hfg, mul_pow] end lemma val_aux_add (f g : pre_tilt K v O hv p) : val_aux K v O hv p (f + g) ≤ max (val_aux K v O hv p f) (val_aux K v O hv p g) := begin by_cases hf : f = 0, { rw [hf, zero_add, val_aux_zero, max_eq_right], exact zero_le _ }, by_cases hg : g = 0, { rw [hg, add_zero, val_aux_zero, max_eq_left], exact zero_le _ }, by_cases hfg : f + g = 0, { rw [hfg, val_aux_zero], exact zero_le _ }, replace hf : ∃ n, coeff _ _ n f ≠ 0 := not_forall.1 (λ h, hf $ perfection.ext h), replace hg : ∃ n, coeff _ _ n g ≠ 0 := not_forall.1 (λ h, hg $ perfection.ext h), replace hfg : ∃ n, coeff _ _ n (f + g) ≠ 0 := not_forall.1 (λ h, hfg $ perfection.ext h), obtain ⟨m, hm⟩ := hf, obtain ⟨n, hn⟩ := hg, obtain ⟨k, hk⟩ := hfg, replace hm := coeff_ne_zero_of_le hm (le_trans (le_max_left m n) (le_max_left _ k)), replace hn := coeff_ne_zero_of_le hn (le_trans (le_max_right m n) (le_max_left _ k)), replace hk := coeff_ne_zero_of_le hk (le_max_right (max m n) k), rw [val_aux_eq hm, val_aux_eq hn, val_aux_eq hk, ring_hom.map_add], cases le_max_iff.1 (mod_p.pre_val_add (coeff _ _ (max (max m n) k) f) (coeff _ _ (max (max m n) k) g)) with h h, { exact le_max_of_le_left (pow_le_pow_of_le_left' h _) }, { exact le_max_of_le_right (pow_le_pow_of_le_left' h _) } end variables (K v O hv p) /-- The valuation `Perfection(O/(p)) → ℝ≥0`. Given `f ∈ Perfection(O/(p))`, if `f = 0` then output `0`; otherwise output `pre_val(f(n))^(p^n)` for any `n` such that `f(n) ≠ 0`. -/ noncomputable def val : valuation (pre_tilt K v O hv p) ℝ≥0 := { to_fun := val_aux K v O hv p, map_one' := val_aux_one, map_mul' := val_aux_mul, map_zero' := val_aux_zero, map_add_le_max' := val_aux_add } variables {K v O hv p} lemma map_eq_zero {f : pre_tilt K v O hv p} : val K v O hv p f = 0 ↔ f = 0 := begin by_cases hf0 : f = 0, { rw hf0, exact iff_of_true (valuation.map_zero _) rfl }, obtain ⟨n, hn⟩ : ∃ n, coeff _ _ n f ≠ 0 := not_forall.1 (λ h, hf0 $ perfection.ext h), show val_aux K v O hv p f = 0 ↔ f = 0, refine iff_of_false (λ hvf, hn _) hf0, rw val_aux_eq hn at hvf, replace hvf := pow_eq_zero hvf, rwa mod_p.pre_val_eq_zero at hvf end end classical instance : is_domain (pre_tilt K v O hv p) := begin haveI : nontrivial (pre_tilt K v O hv p) := ⟨(char_p.nontrivial_of_char_ne_one hp.1.ne_one).1⟩, haveI : no_zero_divisors (pre_tilt K v O hv p) := ⟨λ f g hfg, by { simp_rw ← map_eq_zero at hfg ⊢, contrapose! hfg, rw valuation.map_mul, exact mul_ne_zero hfg.1 hfg.2 }⟩, exact no_zero_divisors.to_is_domain _ end end pre_tilt /-- The tilt of a field, as defined in Perfectoid Spaces by Peter Scholze, as in [scholze2011perfectoid]. Given a field `K` with valuation `K → ℝ≥0` and ring of integers `O`, this is implemented as the fraction field of the perfection of `O/(p)`. -/ @[nolint has_nonempty_instance] def tilt := fraction_ring (pre_tilt K v O hv p) namespace tilt noncomputable instance : field (tilt K v O hv p) := fraction_ring.field end tilt end perfectoid
705529d75bdc47b606f0728ae3a84715bf73d67e
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/shadow1.lean
c38fba1b77a25d309cdef6ef2afef4cb8fa544d1
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
480
lean
variable a : nat definition f : nat → nat | (nat.succ a) := a | nat.zero := nat.zero example : f 3 = 2 := rfl definition g : nat → nat | a := a example (a : nat) : g a = a := rfl definition h (a : nat) : nat → nat | a := a example (a b : nat) : h a b = b := rfl definition o : nat := zero definition f2 : nat → nat | o := 0 example (a : nat) : f2 a = 0 := rfl definition f3 : nat → nat | (add a 1) := a | nat.zero := nat.zero example : f3 10 = 9 := rfl
d045ab3d0c4d03355a6ddd85e59ee3cf749e7535
07c6143268cfb72beccd1cc35735d424ebcb187b
/src/data/set/finite.lean
fa615080222604dc2cc8bede54cab27e438f6449
[ "Apache-2.0" ]
permissive
khoek/mathlib
bc49a842910af13a3c372748310e86467d1dc766
aa55f8b50354b3e11ba64792dcb06cccb2d8ee28
refs/heads/master
1,588,232,063,837
1,587,304,803,000
1,587,304,803,000
176,688,517
0
0
Apache-2.0
1,553,070,585,000
1,553,070,585,000
null
UTF-8
Lean
false
false
23,636
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 Finite sets. -/ import logic.function import data.nat.basic data.fintype.basic data.set.lattice data.set.function import algebra.big_operators open set function universes u v w x variables {α : Type u} {β : Type v} {ι : Sort w} {γ : Type x} namespace set /-- A set is finite if the subtype is a fintype, i.e. there is a list that enumerates its members. -/ def finite (s : set α) : Prop := nonempty (fintype s) /-- A set is infinite if it is not finite. -/ def infinite (s : set α) : Prop := ¬ finite s /-- The subtype corresponding to a finite set is a finite type. Note that because `finite` isn't a typeclass, this will not fire if it is made into an instance -/ noncomputable def finite.fintype {s : set α} (h : finite s) : fintype s := classical.choice h /-- Get a finset from a finite set -/ noncomputable def finite.to_finset {s : set α} (h : finite s) : finset α := @set.to_finset _ _ (finite.fintype h) @[simp] theorem finite.mem_to_finset {s : set α} {h : finite s} {a : α} : a ∈ h.to_finset ↔ a ∈ s := @mem_to_finset _ _ (finite.fintype h) _ lemma finite.coe_to_finset {α} {s : set α} (h : finite s) : ↑h.to_finset = s := by { ext, apply mem_to_finset } theorem finite.exists_finset {s : set α} : finite s → ∃ s' : finset α, ∀ a : α, a ∈ s' ↔ a ∈ s | ⟨h⟩ := by exactI ⟨to_finset s, λ _, mem_to_finset⟩ theorem finite.exists_finset_coe {s : set α} (hs : finite s) : ∃ s' : finset α, ↑s' = s := ⟨hs.to_finset, hs.coe_to_finset⟩ /-- Finite sets can be lifted to finsets. -/ instance : can_lift (set α) (finset α) := { coe := coe, cond := finite, prf := λ s hs, hs.exists_finset_coe } theorem finite_mem_finset (s : finset α) : finite {a | a ∈ s} := ⟨fintype.of_finset s (λ _, iff.rfl)⟩ theorem finite.of_fintype [fintype α] (s : set α) : finite s := by classical; exact ⟨set_fintype s⟩ /-- Membership of a subset of a finite type is decidable. Using this as an instance leads to potential loops with `subtype.fintype` under certain decidability assumptions, so it should only be declared a local instance. -/ def decidable_mem_of_fintype [decidable_eq α] (s : set α) [fintype s] (a) : decidable (a ∈ s) := decidable_of_iff _ mem_to_finset instance fintype_empty : fintype (∅ : set α) := fintype.of_finset ∅ $ by simp theorem empty_card : fintype.card (∅ : set α) = 0 := rfl @[simp] theorem empty_card' {h : fintype.{u} (∅ : set α)} : @fintype.card (∅ : set α) h = 0 := eq.trans (by congr) empty_card @[simp] theorem finite_empty : @finite α ∅ := ⟨set.fintype_empty⟩ def fintype_insert' {a : α} (s : set α) [fintype s] (h : a ∉ s) : fintype (insert a s : set α) := fintype.of_finset ⟨a :: s.to_finset.1, multiset.nodup_cons_of_nodup (by simp [h]) s.to_finset.2⟩ $ by simp theorem card_fintype_insert' {a : α} (s : set α) [fintype s] (h : a ∉ s) : @fintype.card _ (fintype_insert' s h) = fintype.card s + 1 := by rw [fintype_insert', fintype.card_of_finset]; simp [finset.card, to_finset]; refl @[simp] theorem card_insert {a : α} (s : set α) [fintype s] (h : a ∉ s) {d : fintype.{u} (insert a s : set α)} : @fintype.card _ d = fintype.card s + 1 := by rw ← card_fintype_insert' s h; congr lemma card_image_of_inj_on {s : set α} [fintype s] {f : α → β} [fintype (f '' s)] (H : ∀x∈s, ∀y∈s, f x = f y → x = y) : fintype.card (f '' s) = fintype.card s := by haveI := classical.prop_decidable; exact calc fintype.card (f '' s) = (s.to_finset.image f).card : fintype.card_of_finset' _ (by simp) ... = s.to_finset.card : finset.card_image_of_inj_on (λ x hx y hy hxy, H x (mem_to_finset.1 hx) y (mem_to_finset.1 hy) hxy) ... = fintype.card s : (fintype.card_of_finset' _ (λ a, mem_to_finset)).symm lemma card_image_of_injective (s : set α) [fintype s] {f : α → β} [fintype (f '' s)] (H : function.injective f) : fintype.card (f '' s) = fintype.card s := card_image_of_inj_on $ λ _ _ _ _ h, H h section local attribute [instance] decidable_mem_of_fintype instance fintype_insert [decidable_eq α] (a : α) (s : set α) [fintype s] : fintype (insert a s : set α) := if h : a ∈ s then by rwa [insert_eq, union_eq_self_of_subset_left (singleton_subset_iff.2 h)] else fintype_insert' _ h end @[simp] theorem finite_insert (a : α) {s : set α} : finite s → finite (insert a s) | ⟨h⟩ := ⟨@set.fintype_insert _ (classical.dec_eq α) _ _ h⟩ lemma to_finset_insert [decidable_eq α] {a : α} {s : set α} (hs : finite s) : (finite_insert a hs).to_finset = insert a hs.to_finset := finset.ext.mpr $ by simp @[elab_as_eliminator] theorem finite.induction_on {C : set α → Prop} {s : set α} (h : finite s) (H0 : C ∅) (H1 : ∀ {a s}, a ∉ s → finite s → C s → C (insert a s)) : C s := let ⟨t⟩ := h in by exactI match s.to_finset, @mem_to_finset _ s _ with | ⟨l, nd⟩, al := begin change ∀ a, a ∈ l ↔ a ∈ s at al, clear _let_match _match t h, revert s nd al, refine multiset.induction_on l _ (λ a l IH, _); intros s nd al, { rw show s = ∅, from eq_empty_iff_forall_not_mem.2 (by simpa using al), exact H0 }, { rw ← show insert a {x | x ∈ l} = s, from set.ext (by simpa using al), cases multiset.nodup_cons.1 nd with m nd', refine H1 _ ⟨finset.subtype.fintype ⟨l, nd'⟩⟩ (IH nd' (λ _, iff.rfl)), exact m } end end @[elab_as_eliminator] theorem finite.dinduction_on {C : ∀s:set α, finite s → Prop} {s : set α} (h : finite s) (H0 : C ∅ finite_empty) (H1 : ∀ {a s}, a ∉ s → ∀h:finite s, C s h → C (insert a s) (finite_insert a h)) : C s h := have ∀h:finite s, C s h, from finite.induction_on h (assume h, H0) (assume a s has hs ih h, H1 has hs (ih _)), this h instance fintype_singleton (a : α) : fintype ({a} : set α) := fintype_insert' _ (not_mem_empty _) @[simp] theorem card_singleton (a : α) : fintype.card ({a} : set α) = 1 := by rw [show fintype.card ({a} : set α) = _, from card_fintype_insert' ∅ (not_mem_empty a)]; refl @[simp] theorem finite_singleton (a : α) : finite ({a} : set α) := ⟨set.fintype_singleton _⟩ instance fintype_pure : ∀ a : α, fintype (pure a : set α) := set.fintype_singleton theorem finite_pure (a : α) : finite (pure a : set α) := ⟨set.fintype_pure a⟩ instance fintype_univ [fintype α] : fintype (@univ α) := fintype.of_equiv α $ (equiv.set.univ α).symm theorem finite_univ [fintype α] : finite (@univ α) := ⟨set.fintype_univ⟩ theorem infinite_univ_iff : (@univ α).infinite ↔ _root_.infinite α := ⟨λ h₁, ⟨λ h₂, h₁ $ @finite_univ α h₂⟩, λ ⟨h₁⟩ ⟨h₂⟩, h₁ $ @fintype.of_equiv _ _ h₂ $ equiv.set.univ _⟩ theorem infinite_univ [h : _root_.infinite α] : infinite (@univ α) := infinite_univ_iff.2 h instance fintype_union [decidable_eq α] (s t : set α) [fintype s] [fintype t] : fintype (s ∪ t : set α) := fintype.of_finset (s.to_finset ∪ t.to_finset) $ by simp theorem finite_union {s t : set α} : finite s → finite t → finite (s ∪ t) | ⟨hs⟩ ⟨ht⟩ := ⟨@set.fintype_union _ (classical.dec_eq α) _ _ hs ht⟩ instance fintype_sep (s : set α) (p : α → Prop) [fintype s] [decidable_pred p] : fintype ({a ∈ s | p a} : set α) := fintype.of_finset (s.to_finset.filter p) $ by simp instance fintype_inter (s t : set α) [fintype s] [decidable_pred t] : fintype (s ∩ t : set α) := set.fintype_sep s t def fintype_subset (s : set α) {t : set α} [fintype s] [decidable_pred t] (h : t ⊆ s) : fintype t := by rw ← inter_eq_self_of_subset_right h; apply_instance theorem finite_subset {s : set α} : finite s → ∀ {t : set α}, t ⊆ s → finite t | ⟨hs⟩ t h := ⟨@set.fintype_subset _ _ _ hs (classical.dec_pred t) h⟩ instance fintype_image [decidable_eq β] (s : set α) (f : α → β) [fintype s] : fintype (f '' s) := fintype.of_finset (s.to_finset.image f) $ by simp instance fintype_range [decidable_eq β] (f : α → β) [fintype α] : fintype (range f) := fintype.of_finset (finset.univ.image f) $ by simp [range] theorem finite_range (f : α → β) [fintype α] : finite (range f) := by haveI := classical.dec_eq β; exact ⟨by apply_instance⟩ theorem finite_image {s : set α} (f : α → β) : finite s → finite (f '' s) | ⟨h⟩ := ⟨@set.fintype_image _ _ (classical.dec_eq β) _ _ h⟩ lemma finite_dependent_image {s : set α} (hs : finite s) {F : Π i ∈ s, β} {t : set β} (H : ∀ y ∈ t, ∃ x (hx : x ∈ s), y = F x hx) : set.finite t := begin let G : s → β := λ x, F x.1 x.2, have A : t ⊆ set.range G, { assume y hy, rcases H y hy with ⟨x, hx, xy⟩, refine ⟨⟨x, hx⟩, xy.symm⟩ }, letI : fintype s := finite.fintype hs, exact finite_subset (finite_range G) A end instance fintype_map {α β} [decidable_eq β] : ∀ (s : set α) (f : α → β) [fintype s], fintype (f <$> s) := set.fintype_image theorem finite_map {α β} {s : set α} : ∀ (f : α → β), finite s → finite (f <$> s) := finite_image def fintype_of_fintype_image (s : set α) {f : α → β} {g} (I : is_partial_inv f g) [fintype (f '' s)] : fintype s := fintype.of_finset ⟨_, @multiset.nodup_filter_map β α g _ (@injective_of_partial_inv_right _ _ f g I) (f '' s).to_finset.2⟩ $ λ a, begin suffices : (∃ b x, f x = b ∧ g b = some a ∧ x ∈ s) ↔ a ∈ s, by simpa [exists_and_distrib_left.symm, and.comm, and.left_comm, and.assoc], rw exists_swap, suffices : (∃ x, x ∈ s ∧ g (f x) = some a) ↔ a ∈ s, {simpa [and.comm, and.left_comm, and.assoc]}, simp [I _, (injective_of_partial_inv I).eq_iff] end theorem finite_of_finite_image_on {s : set α} {f : α → β} (hi : set.inj_on f s) : finite (f '' s) → finite s | ⟨h⟩ := ⟨@fintype.of_injective _ _ h (λa:s, ⟨f a.1, mem_image_of_mem f a.2⟩) $ assume a b eq, subtype.eq $ hi a.2 b.2 $ subtype.ext.1 eq⟩ theorem finite_image_iff_on {s : set α} {f : α → β} (hi : inj_on f s) : finite (f '' s) ↔ finite s := ⟨finite_of_finite_image_on hi, finite_image _⟩ theorem finite_of_finite_image {s : set α} {f : α → β} (I : set.inj_on f s) : finite (f '' s) → finite s := finite_of_finite_image_on I theorem finite_preimage {s : set β} {f : α → β} (I : set.inj_on f (f⁻¹' s)) (h : finite s) : finite (f ⁻¹' s) := finite_of_finite_image I (finite_subset h (image_preimage_subset f s)) instance fintype_Union [decidable_eq α] {ι : Type*} [fintype ι] (f : ι → set α) [∀ i, fintype (f i)] : fintype (⋃ i, f i) := fintype.of_finset (finset.univ.bind (λ i, (f i).to_finset)) $ by simp theorem finite_Union {ι : Type*} [fintype ι] {f : ι → set α} (H : ∀i, finite (f i)) : finite (⋃ i, f i) := ⟨@set.fintype_Union _ (classical.dec_eq α) _ _ _ (λ i, finite.fintype (H i))⟩ def fintype_bUnion [decidable_eq α] {ι : Type*} {s : set ι} [fintype s] (f : ι → set α) (H : ∀ i ∈ s, fintype (f i)) : fintype (⋃ i ∈ s, f i) := by rw bUnion_eq_Union; exact @set.fintype_Union _ _ _ _ _ (by rintro ⟨i, hi⟩; exact H i hi) instance fintype_bUnion' [decidable_eq α] {ι : Type*} {s : set ι} [fintype s] (f : ι → set α) [H : ∀ i, fintype (f i)] : fintype (⋃ i ∈ s, f i) := fintype_bUnion _ (λ i _, H i) theorem finite_sUnion {s : set (set α)} (h : finite s) (H : ∀t∈s, finite t) : finite (⋃₀ s) := by rw sUnion_eq_Union; haveI := finite.fintype h; apply finite_Union; simpa using H theorem finite_bUnion {α} {ι : Type*} {s : set ι} {f : ι → set α} : finite s → (∀i, finite (f i)) → finite (⋃ i∈s, f i) | ⟨hs⟩ h := by rw [bUnion_eq_Union]; exactI finite_Union (λ i, h _) theorem finite_bUnion' {α} {ι : Type*} {s : set ι} (f : ι → set α) : finite s → (∀i ∈ s, finite (f i)) → finite (⋃ i∈s, f i) | ⟨hs⟩ h := by { rw [bUnion_eq_Union], exactI finite_Union (λ i, h i.1 i.2) } instance fintype_lt_nat (n : ℕ) : fintype {i | i < n} := fintype.of_finset (finset.range n) $ by simp instance fintype_le_nat (n : ℕ) : fintype {i | i ≤ n} := by simpa [nat.lt_succ_iff] using set.fintype_lt_nat (n+1) lemma finite_le_nat (n : ℕ) : finite {i | i ≤ n} := ⟨set.fintype_le_nat _⟩ lemma finite_lt_nat (n : ℕ) : finite {i | i < n} := ⟨set.fintype_lt_nat _⟩ instance fintype_prod (s : set α) (t : set β) [fintype s] [fintype t] : fintype (set.prod s t) := fintype.of_finset (s.to_finset.product t.to_finset) $ by simp lemma finite_prod {s : set α} {t : set β} : finite s → finite t → finite (set.prod s t) | ⟨hs⟩ ⟨ht⟩ := by exactI ⟨set.fintype_prod s t⟩ def fintype_bind {α β} [decidable_eq β] (s : set α) [fintype s] (f : α → set β) (H : ∀ a ∈ s, fintype (f a)) : fintype (s >>= f) := set.fintype_bUnion _ H instance fintype_bind' {α β} [decidable_eq β] (s : set α) [fintype s] (f : α → set β) [H : ∀ a, fintype (f a)] : fintype (s >>= f) := fintype_bind _ _ (λ i _, H i) theorem finite_bind {α β} {s : set α} {f : α → set β} : finite s → (∀ a ∈ s, finite (f a)) → finite (s >>= f) | ⟨hs⟩ H := ⟨@fintype_bind _ _ (classical.dec_eq β) _ hs _ (λ a ha, (H a ha).fintype)⟩ instance fintype_seq {α β : Type u} [decidable_eq β] (f : set (α → β)) (s : set α) [fintype f] [fintype s] : fintype (f <*> s) := by rw seq_eq_bind_map; apply set.fintype_bind' theorem finite_seq {α β : Type u} {f : set (α → β)} {s : set α} : finite f → finite s → finite (f <*> s) | ⟨hf⟩ ⟨hs⟩ := by { haveI := classical.dec_eq β, exactI ⟨set.fintype_seq _ _⟩ } /-- There are finitely many subsets of a given finite set -/ lemma finite_subsets_of_finite {α : Type u} {a : set α} (h : finite a) : finite {b | b ⊆ a} := begin -- we just need to translate the result, already known for finsets, -- to the language of finite sets let s := coe '' ((finset.powerset (finite.to_finset h)).to_set), have : finite s := finite_image _ (finite_mem_finset _), have : {b | b ⊆ a} ⊆ s := begin assume b hb, rw [set.mem_image], rw [set.mem_set_of_eq] at hb, let b' : finset α := finite.to_finset (finite_subset h hb), have : b' ∈ (finset.powerset (finite.to_finset h)).to_set := show b' ∈ (finset.powerset (finite.to_finset h)), by simp [b', finset.subset_iff]; exact hb, have : coe b' = b := by ext; simp, exact ⟨b', by assumption, by assumption⟩ end, exact finite_subset ‹finite s› this end lemma exists_min_image [linear_order β] (s : set α) (f : α → β) (h1 : finite s) : s.nonempty → ∃ a ∈ s, ∀ b ∈ s, f a ≤ f b | ⟨x, hx⟩ := by simpa only [exists_prop, finite.mem_to_finset] using (finite.to_finset h1).exists_min_image f ⟨x, finite.mem_to_finset.2 hx⟩ lemma exists_max_image [linear_order β] (s : set α) (f : α → β) (h1 : finite s) : s.nonempty → ∃ a ∈ s, ∀ b ∈ s, f b ≤ f a | ⟨x, hx⟩ := by simpa only [exists_prop, finite.mem_to_finset] using (finite.to_finset h1).exists_max_image f ⟨x, finite.mem_to_finset.2 hx⟩ end set namespace finset variables [decidable_eq β] variables {s t u : finset α} {f : α → β} {a : α} lemma finite_to_set (s : finset α) : set.finite (↑s : set α) := set.finite_mem_finset s @[simp] lemma coe_bind {f : α → finset β} : ↑(s.bind f) = (⋃x ∈ (↑s : set α), ↑(f x) : set β) := by simp [set.ext_iff] @[simp] lemma coe_to_finset {s : set α} {hs : set.finite s} : ↑(hs.to_finset) = s := by simp [set.ext_iff] @[simp] lemma coe_to_finset' (s : set α) [fintype s] : (↑s.to_finset : set α) = s := by ext; simp end finset namespace set lemma finite_subset_Union {s : set α} (hs : finite s) {ι} {t : ι → set α} (h : s ⊆ ⋃ i, t i) : ∃ I : set ι, finite I ∧ s ⊆ ⋃ i ∈ I, t i := begin unfreezeI, cases hs, choose f hf using show ∀ x : s, ∃ i, x.1 ∈ t i, {simpa [subset_def] using h}, refine ⟨range f, finite_range f, _⟩, rintro x hx, simp, exact ⟨x, ⟨hx, hf _⟩⟩, end lemma eq_finite_Union_of_finite_subset_Union {ι} {s : ι → set α} {t : set α} (tfin : finite t) (h : t ⊆ ⋃ i, s i) : ∃ I : set ι, (finite I) ∧ ∃ σ : {i | i ∈ I} → set α, (∀ i, finite (σ i)) ∧ (∀ i, σ i ⊆ s i) ∧ t = ⋃ i, σ i := let ⟨I, Ifin, hI⟩ := finite_subset_Union tfin h in ⟨I, Ifin, λ x, s x ∩ t, λ i, finite_subset tfin (inter_subset_right _ _), λ i, inter_subset_left _ _, begin ext x, rw mem_Union, split, { intro x_in, rcases mem_Union.mp (hI x_in) with ⟨i, _, ⟨hi, rfl⟩, H⟩, use [i, hi, H, x_in] }, { rintros ⟨i, hi, H⟩, exact H } end⟩ lemma finite_range_ite {p : α → Prop} [decidable_pred p] {f g : α → β} (hf : finite (range f)) (hg : finite (range g)) : finite (range (λ x, if p x then f x else g x)) := finite_subset (finite_union hf hg) range_ite_subset lemma finite_range_const {c : β} : finite (range (λ x : α, c)) := finite_subset (finite_singleton c) range_const_subset lemma range_find_greatest_subset {P : α → ℕ → Prop} [∀ x, decidable_pred (P x)] {b : ℕ}: range (λ x, nat.find_greatest (P x) b) ⊆ ↑(finset.range (b + 1)) := by { rw range_subset_iff, assume x, simp [nat.lt_succ_iff, nat.find_greatest_le] } lemma finite_range_find_greatest {P : α → ℕ → Prop} [∀ x, decidable_pred (P x)] {b : ℕ} : finite (range (λ x, nat.find_greatest (P x) b)) := finite_subset (finset.finite_to_set $ finset.range (b + 1)) range_find_greatest_subset lemma card_lt_card {s t : set α} [fintype s] [fintype t] (h : s ⊂ t) : fintype.card s < fintype.card t := begin haveI := classical.prop_decidable, rw [← finset.coe_to_finset' s, ← finset.coe_to_finset' t, finset.coe_ssubset] at h, rw [fintype.card_of_finset' _ (λ x, mem_to_finset), fintype.card_of_finset' _ (λ x, mem_to_finset)], exact finset.card_lt_card h, end lemma card_le_of_subset {s t : set α} [fintype s] [fintype t] (hsub : s ⊆ t) : fintype.card s ≤ fintype.card t := calc fintype.card s = s.to_finset.card : fintype.card_of_finset' _ (by simp) ... ≤ t.to_finset.card : finset.card_le_of_subset (λ x hx, by simp [set.subset_def, *] at *) ... = fintype.card t : eq.symm (fintype.card_of_finset' _ (by simp)) lemma eq_of_subset_of_card_le {s t : set α} [fintype s] [fintype t] (hsub : s ⊆ t) (hcard : fintype.card t ≤ fintype.card s) : s = t := (eq_or_ssubset_of_subset hsub).elim id (λ h, absurd hcard $ not_le_of_lt $ card_lt_card h) lemma card_range_of_injective [fintype α] {f : α → β} (hf : injective f) [fintype (range f)] : fintype.card (range f) = fintype.card α := eq.symm $ fintype.card_congr (@equiv.of_bijective _ _ (λ a : α, show range f, from ⟨f a, a, rfl⟩) ⟨λ x y h, hf $ subtype.mk.inj h, λ b, let ⟨a, ha⟩ := b.2 in ⟨a, by simp *⟩⟩) lemma finite.exists_maximal_wrt [partial_order β] (f : α → β) (s : set α) (h : set.finite s) : s.nonempty → ∃a∈s, ∀a'∈s, f a ≤ f a' → f a = f a' := begin classical, refine h.induction_on _ _, { assume h, exact absurd h empty_not_nonempty }, assume a s his _ ih _, cases s.eq_empty_or_nonempty with h h, { use a, simp [h] }, rcases ih h with ⟨b, hb, ih⟩, by_cases f b ≤ f a, { refine ⟨a, set.mem_insert _ _, assume c hc hac, le_antisymm hac _⟩, rcases set.mem_insert_iff.1 hc with rfl | hcs, { refl }, { rwa [← ih c hcs (le_trans h hac)] } }, { refine ⟨b, set.mem_insert_of_mem _ hb, assume c hc hbc, _⟩, rcases set.mem_insert_iff.1 hc with rfl | hcs, { exact (h hbc).elim }, { exact ih c hcs hbc } } end section local attribute [instance, priority 1] classical.prop_decidable lemma to_finset_card {α : Type*} [fintype α] (H : set α) : H.to_finset.card = fintype.card H := multiset.card_map subtype.val finset.univ.val lemma to_finset_inter {α : Type*} [fintype α] (s t : set α) [decidable_eq α] : (s ∩ t).to_finset = s.to_finset ∩ t.to_finset := by ext; simp end section variables [semilattice_sup α] [nonempty α] {s : set α} /--A finite set is bounded above.-/ lemma bdd_above_finite (hs : finite s) : bdd_above s := finite.induction_on hs bdd_above_empty $ λ a s _ _ h, h.insert a /--A finite union of sets which are all bounded above is still bounded above.-/ lemma bdd_above_finite_union {I : set β} {S : β → set α} (H : finite I) : (bdd_above (⋃i∈I, S i)) ↔ (∀i ∈ I, bdd_above (S i)) := finite.induction_on H (by simp only [bUnion_empty, bdd_above_empty, ball_empty_iff]) (λ a s ha _ hs, by simp only [bUnion_insert, ball_insert_iff, bdd_above_union, hs]) end section variables [semilattice_inf α] [nonempty α] {s : set α} /--A finite set is bounded below.-/ lemma bdd_below_finite (hs : finite s) : bdd_below s := finite.induction_on hs bdd_below_empty $ λ a s _ _ h, h.insert a /--A finite union of sets which are all bounded below is still bounded below.-/ lemma bdd_below_finite_union {I : set β} {S : β → set α} (H : finite I) : (bdd_below (⋃i∈I, S i)) ↔ (∀i ∈ I, bdd_below (S i)) := @bdd_above_finite_union (order_dual α) _ _ _ _ _ H end end set namespace finset section preimage noncomputable def preimage {f : α → β} (s : finset β) (hf : set.inj_on f (f ⁻¹' ↑s)) : finset α := set.finite.to_finset (set.finite_preimage hf (set.finite_mem_finset s)) @[simp] lemma mem_preimage {f : α → β} {s : finset β} {hf : set.inj_on f (f ⁻¹' ↑s)} {x : α} : x ∈ preimage s hf ↔ f x ∈ s := by simp [preimage] @[simp] lemma coe_preimage {f : α → β} (s : finset β) (hf : set.inj_on f (f ⁻¹' ↑s)) : (↑(preimage s hf) : set α) = f ⁻¹' ↑s := by simp [set.ext_iff] lemma image_preimage [decidable_eq β] (f : α → β) (s : finset β) (hf : set.bij_on f (f ⁻¹' s.to_set) s.to_set) : image f (preimage s hf.inj_on) = s := finset.coe_inj.1 $ suffices f '' (f ⁻¹' ↑s) = ↑s, by simpa, (set.subset.antisymm (image_preimage_subset _ _) hf.2.2) end preimage @[to_additive] lemma prod_preimage [comm_monoid β] (f : α → γ) (s : finset γ) (hf : set.bij_on f (f ⁻¹' ↑s) ↑s) (g : γ → β) : (preimage s hf.inj_on).prod (g ∘ f) = s.prod g := by classical; calc (preimage s hf.inj_on).prod (g ∘ f) = (image f (preimage s hf.inj_on)).prod g : begin rw prod_image, intros x hx y hy hxy, apply hf.inj_on, repeat { try { rw mem_preimage at hx hy, rw [set.mem_preimage, mem_coe] }, assumption }, end ... = s.prod g : by rw [image_preimage] /-- A finset is bounded above. -/ lemma bdd_above [semilattice_sup α] [nonempty α] (s : finset α) : bdd_above (↑s : set α) := set.bdd_above_finite (finset.finite_to_set s) /-- A finset is bounded below. -/ lemma bdd_below [semilattice_inf α] [nonempty α] (s : finset α) : bdd_below (↑s : set α) := set.bdd_below_finite (finset.finite_to_set s) end finset lemma fintype.exists_max [fintype α] [nonempty α] {β : Type*} [linear_order β] (f : α → β) : ∃ x₀ : α, ∀ x, f x ≤ f x₀ := begin rcases set.finite_univ.exists_maximal_wrt f _ univ_nonempty with ⟨x, _, hx⟩, exact ⟨x, λ y, (le_total (f x) (f y)).elim (λ h, ge_of_eq $ hx _ trivial h) id⟩ end
9e67e3a005504b53934ab0a824b3fef982059a15
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/data/padics/ring_homs.lean
506b6d1be930a21af4529d4c8e5603ea9ee26996
[ "Apache-2.0" ]
permissive
anthony2698/mathlib
03cd69fe5c280b0916f6df2d07c614c8e1efe890
407615e05814e98b24b2ff322b14e8e3eb5e5d67
refs/heads/master
1,678,792,774,873
1,614,371,563,000
1,614,371,563,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
24,645
lean
/- Copyright (c) 2020 Johan Commelin and Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin and Robert Y. Lewis -/ import data.padics.padic_integers /-! # Relating `ℤ_[p]` to `zmod (p ^ n)` In this file we establish connections between the `p`-adic integers $\mathbb{Z}_p$ and the integers modulo powers of `p`, $\mathbb{Z}/p^n\mathbb{Z}$. ## Main declarations We show that $\mathbb{Z}_p$ has a ring hom to $\mathbb{Z}/p^n\mathbb{Z}$ for each `n`. The case for `n = 1` is handled separately, since it is used in the general construction and we may want to use it without the `^1` getting in the way. * `padic_int.to_zmod`: ring hom to `zmod p` * `padic_int.to_zmod_pow`: ring hom to `zmod (p^n)` * `padic_int.ker_to_zmod` / `padic_int.ker_to_zmod_pow`: the kernels of these maps are the ideals generated by `p^n` We also establish the universal property of $\mathbb{Z}_p$ as a projective limit. Given a family of compatible ring homs $f_k : R \to \mathbb{Z}/p^n\mathbb{Z}$, there is a unique limit $R \to \mathbb{Z}_p$. * `padic_int.lift`: the limit function * `padic_int.lift_spec` / `padic_int.lift_unique`: the universal property ## Implementation notes The ring hom constructions go through an auxiliary constructor `padic_int.to_zmod_hom`, which removes some boilerplate code. -/ noncomputable theory open_locale classical namespace padic_int open nat local_ring padic variables {p : ℕ} [hp_prime : fact (p.prime)] include hp_prime section ring_homs /-! ### Ring homomorphisms to `zmod p` and `zmod (p ^ n)` -/ variables (p) (r : ℚ) omit hp_prime /-- `mod_part p r` is an integer that satisfies `∥(r - mod_part p r : ℚ_[p])∥ < 1` when `∥(r : ℚ_[p])∥ ≤ 1`, see `padic_int.norm_sub_mod_part`. It is the unique non-negative integer that is `< p` with this property. (Note that this definition assumes `r : ℚ`. See `padic_int.zmod_repr` for a version that takes values in `ℕ` and works for arbitrary `x : ℤ_[p]`.) -/ def mod_part : ℤ := (r.num * gcd_a r.denom p) % p include hp_prime variable {p} lemma mod_part_lt_p : mod_part p r < p := begin convert int.mod_lt _ _, { simp }, { exact_mod_cast hp_prime.ne_zero } end lemma mod_part_nonneg : 0 ≤ mod_part p r := int.mod_nonneg _ $ by exact_mod_cast hp_prime.ne_zero lemma is_unit_denom (r : ℚ) (h : ∥(r : ℚ_[p])∥ ≤ 1) : is_unit (r.denom : ℤ_[p]) := begin rw is_unit_iff, apply le_antisymm (r.denom : ℤ_[p]).2, rw [← not_lt, val_eq_coe, coe_coe], intro norm_denom_lt, have hr : ∥(r * r.denom : ℚ_[p])∥ = ∥(r.num : ℚ_[p])∥, { rw_mod_cast @rat.mul_denom_eq_num r, refl, }, rw padic_norm_e.mul at hr, have key : ∥(r.num : ℚ_[p])∥ < 1, { calc _ = _ : hr.symm ... < 1 * 1 : mul_lt_mul' h norm_denom_lt (norm_nonneg _) zero_lt_one ... = 1 : mul_one 1 }, have : ↑p ∣ r.num ∧ (p : ℤ) ∣ r.denom, { simp only [← norm_int_lt_one_iff_dvd, ← padic_norm_e_of_padic_int], norm_cast, exact ⟨key, norm_denom_lt⟩ }, apply hp_prime.not_dvd_one, rwa [← r.cop.gcd_eq_one, nat.dvd_gcd_iff, ← int.coe_nat_dvd_left, ← int.coe_nat_dvd], end lemma norm_sub_mod_part_aux (r : ℚ) (h : ∥(r : ℚ_[p])∥ ≤ 1) : ↑p ∣ r.num - r.num * r.denom.gcd_a p % p * ↑(r.denom) := begin rw ← zmod.int_coe_zmod_eq_zero_iff_dvd, simp only [int.cast_coe_nat, zmod.nat_cast_mod p, int.cast_mul, int.cast_sub], have := congr_arg (coe : ℤ → zmod p) (gcd_eq_gcd_ab r.denom p), simp only [int.cast_coe_nat, add_zero, int.cast_add, zmod.nat_cast_self, int.cast_mul, zero_mul] at this, push_cast, rw [mul_right_comm, mul_assoc, ←this], suffices rdcp : r.denom.coprime p, { rw rdcp.gcd_eq_one, simp only [mul_one, cast_one, sub_self], }, apply coprime.symm, apply (coprime_or_dvd_of_prime ‹_› _).resolve_right, rw [← int.coe_nat_dvd, ← norm_int_lt_one_iff_dvd, not_lt], apply ge_of_eq, rw ← is_unit_iff, exact is_unit_denom r h, end lemma norm_sub_mod_part (h : ∥(r : ℚ_[p])∥ ≤ 1) : ∥(⟨r,h⟩ - mod_part p r : ℤ_[p])∥ < 1 := begin let n := mod_part p r, by_cases aux : (⟨r,h⟩ - n : ℤ_[p]) = 0, { rw [aux, norm_zero], exact zero_lt_one, }, rw [norm_lt_one_iff_dvd, ← (is_unit_denom r h).dvd_mul_right], suffices : ↑p ∣ r.num - n * r.denom, { convert (int.cast_ring_hom ℤ_[p]).map_dvd this, simp only [sub_mul, int.cast_coe_nat, ring_hom.eq_int_cast, int.cast_mul, sub_left_inj, int.cast_sub], apply subtype.coe_injective, simp only [coe_mul, subtype.coe_mk, coe_coe], rw_mod_cast @rat.mul_denom_eq_num r, refl }, exact norm_sub_mod_part_aux r h end lemma exists_mem_range_of_norm_rat_le_one (h : ∥(r : ℚ_[p])∥ ≤ 1) : ∃ n : ℤ, 0 ≤ n ∧ n < p ∧ ∥(⟨r,h⟩ - n : ℤ_[p])∥ < 1 := ⟨mod_part p r, mod_part_nonneg _, mod_part_lt_p _, norm_sub_mod_part _ h⟩ lemma zmod_congr_of_sub_mem_span_aux (n : ℕ) (x : ℤ_[p]) (a b : ℤ) (ha : x - a ∈ (ideal.span {p ^ n} : ideal ℤ_[p])) (hb : x - b ∈ (ideal.span {p ^ n} : ideal ℤ_[p])) : (a : zmod (p ^ n)) = b := begin rw [ideal.mem_span_singleton] at ha hb, rw [← sub_eq_zero, ← int.cast_sub, zmod.int_coe_zmod_eq_zero_iff_dvd, int.coe_nat_pow], rw [← dvd_neg, neg_sub] at ha, have := dvd_add ha hb, rwa [sub_eq_add_neg, sub_eq_add_neg, add_assoc, neg_add_cancel_left, ← sub_eq_add_neg, ← int.cast_sub, pow_p_dvd_int_iff] at this, end lemma zmod_congr_of_sub_mem_span (n : ℕ) (x : ℤ_[p]) (a b : ℕ) (ha : x - a ∈ (ideal.span {p ^ n} : ideal ℤ_[p])) (hb : x - b ∈ (ideal.span {p ^ n} : ideal ℤ_[p])) : (a : zmod (p ^ n)) = b := zmod_congr_of_sub_mem_span_aux n x a b ha hb lemma zmod_congr_of_sub_mem_max_ideal (x : ℤ_[p]) (m n : ℕ) (hm : x - m ∈ maximal_ideal ℤ_[p]) (hn : x - n ∈ maximal_ideal ℤ_[p]) : (m : zmod p) = n := begin rw maximal_ideal_eq_span_p at hm hn, have := zmod_congr_of_sub_mem_span_aux 1 x m n, simp only [pow_one] at this, specialize this hm hn, apply_fun zmod.cast_hom (show p ∣ p ^ 1, by rw pow_one) (zmod p) at this, simpa only [ring_hom.map_int_cast], end variable (x : ℤ_[p]) lemma exists_mem_range : ∃ n : ℕ, n < p ∧ (x - n ∈ maximal_ideal ℤ_[p]) := begin simp only [maximal_ideal_eq_span_p, ideal.mem_span_singleton, ← norm_lt_one_iff_dvd], obtain ⟨r, hr⟩ := rat_dense (x : ℚ_[p]) zero_lt_one, have H : ∥(r : ℚ_[p])∥ ≤ 1, { rw norm_sub_rev at hr, calc _ = ∥(r : ℚ_[p]) - x + x∥ : by ring ... ≤ _ : padic_norm_e.nonarchimedean _ _ ... ≤ _ : max_le (le_of_lt hr) x.2 }, obtain ⟨n, hzn, hnp, hn⟩ := exists_mem_range_of_norm_rat_le_one r H, lift n to ℕ using hzn, use n, split, {exact_mod_cast hnp}, simp only [norm_def, coe_sub, subtype.coe_mk, coe_coe] at hn ⊢, rw show (x - n : ℚ_[p]) = (x - r) + (r - n), by ring, apply lt_of_le_of_lt (padic_norm_e.nonarchimedean _ _), apply max_lt hr, simpa using hn end /-- `zmod_repr x` is the unique natural number smaller than `p` satisfying `∥(x - zmod_repr x : ℤ_[p])∥ < 1`. -/ def zmod_repr : ℕ := classical.some (exists_mem_range x) lemma zmod_repr_spec : zmod_repr x < p ∧ (x - zmod_repr x ∈ maximal_ideal ℤ_[p]) := classical.some_spec (exists_mem_range x) lemma zmod_repr_lt_p : zmod_repr x < p := (zmod_repr_spec _).1 lemma sub_zmod_repr_mem : (x - zmod_repr x ∈ maximal_ideal ℤ_[p]) := (zmod_repr_spec _).2 /-- `to_zmod_hom` is an auxiliary constructor for creating ring homs from `ℤ_[p]` to `zmod v`. -/ def to_zmod_hom (v : ℕ) (f : ℤ_[p] → ℕ) (f_spec : ∀ x, x - f x ∈ (ideal.span {v} : ideal ℤ_[p])) (f_congr : ∀ (x : ℤ_[p]) (a b : ℕ), x - a ∈ (ideal.span {v} : ideal ℤ_[p]) → x - b ∈ (ideal.span {v} : ideal ℤ_[p]) → (a : zmod v) = b) : ℤ_[p] →+* zmod v := { to_fun := λ x, f x, map_zero' := begin rw [f_congr (0 : ℤ_[p]) _ 0, cast_zero], { exact f_spec _ }, { simp only [sub_zero, cast_zero, submodule.zero_mem], } end, map_one' := begin rw [f_congr (1 : ℤ_[p]) _ 1, cast_one], { exact f_spec _ }, { simp only [sub_self, cast_one, submodule.zero_mem], } end, map_add' := begin intros x y, rw [f_congr (x + y) _ (f x + f y), cast_add], { exact f_spec _ }, { convert ideal.add_mem _ (f_spec x) (f_spec y), rw cast_add, ring, } end, map_mul' := begin intros x y, rw [f_congr (x * y) _ (f x * f y), cast_mul], { exact f_spec _ }, { let I : ideal ℤ_[p] := ideal.span {v}, convert I.add_mem (I.mul_mem_left x (f_spec y)) (I.mul_mem_right (f y) (f_spec x)), rw cast_mul, ring, } end, } /-- `to_zmod` is a ring hom from `ℤ_[p]` to `zmod p`, with the equality `to_zmod x = (zmod_repr x : zmod p)`. -/ def to_zmod : ℤ_[p] →+* zmod p := to_zmod_hom p zmod_repr (by { rw ←maximal_ideal_eq_span_p, exact sub_zmod_repr_mem }) (by { rw ←maximal_ideal_eq_span_p, exact zmod_congr_of_sub_mem_max_ideal } ) /-- `z - (to_zmod z : ℤ_[p])` is contained in the maximal ideal of `ℤ_[p]`, for every `z : ℤ_[p]`. The coercion from `zmod p` to `ℤ_[p]` is `zmod.has_coe_t`, which coerces `zmod p` into artibrary rings. This is unfortunate, but a consequence of the fact that we allow `zmod p` to coerce to rings of arbitrary characteristic, instead of only rings of characteristic `p`. This coercion is only a ring homomorphism if it coerces into a ring whose characteristic divides `p`. While this is not the case here we can still make use of the coercion. -/ lemma to_zmod_spec (z : ℤ_[p]) : z - (to_zmod z : ℤ_[p]) ∈ maximal_ideal ℤ_[p] := begin convert sub_zmod_repr_mem z using 2, dsimp [to_zmod, to_zmod_hom], unfreezingI { rcases (exists_eq_add_of_lt (hp_prime.pos)) with ⟨p', rfl⟩ }, change ↑(zmod.val _) = _, simp only [zmod.val_nat_cast, add_zero, add_def, cast_inj, zero_add], apply mod_eq_of_lt, simpa only [zero_add] using zmod_repr_lt_p z, end lemma ker_to_zmod : (to_zmod : ℤ_[p] →+* zmod p).ker = maximal_ideal ℤ_[p] := begin ext x, rw ring_hom.mem_ker, split, { intro h, simpa only [h, zmod.cast_zero, sub_zero] using to_zmod_spec x, }, { intro h, rw ← sub_zero x at h, dsimp [to_zmod, to_zmod_hom], convert zmod_congr_of_sub_mem_max_ideal x _ 0 _ h, apply sub_zmod_repr_mem, } end /-- `appr n x` gives a value `v : ℕ` such that `x` and `↑v : ℤ_p` are congruent mod `p^n`. See `appr_spec`. -/ noncomputable def appr : ℤ_[p] → ℕ → ℕ | x 0 := 0 | x (n+1) := let y := x - appr x n in if hy : y = 0 then appr x n else let u := unit_coeff hy in appr x n + p ^ n * (to_zmod ((u : ℤ_[p]) * (p ^ (y.valuation - n).nat_abs))).val lemma appr_lt (x : ℤ_[p]) (n : ℕ) : x.appr n < p ^ n := begin induction n with n ih generalizing x, { simp only [appr, succ_pos', pow_zero], }, simp only [appr, ring_hom.map_nat_cast, zmod.nat_cast_self, ring_hom.map_pow, int.nat_abs, ring_hom.map_mul], have hp : p ^ n < p ^ (n + 1), { apply pow_lt_pow hp_prime.one_lt (lt_add_one n) }, split_ifs with h, { apply lt_trans (ih _) hp, }, { calc _ < p ^ n + p ^ n * (p - 1) : _ ... = p ^ (n + 1) : _, { apply add_lt_add_of_lt_of_le (ih _), apply nat.mul_le_mul_left, apply le_pred_of_lt, apply zmod.val_lt }, { rw [nat.mul_sub_left_distrib, mul_one, ← pow_succ'], apply nat.add_sub_cancel' (le_of_lt hp) } } end lemma appr_mono (x : ℤ_[p]) : monotone x.appr := begin apply monotone_of_monotone_nat, intro n, dsimp [appr], split_ifs, { refl, }, apply nat.le_add_right, end lemma dvd_appr_sub_appr (x : ℤ_[p]) (m n : ℕ) (h : m ≤ n) : p ^ m ∣ x.appr n - x.appr m := begin obtain ⟨k, rfl⟩ := nat.exists_eq_add_of_le h, clear h, induction k with k ih, { simp only [add_zero, nat.sub_self, dvd_zero], }, rw [nat.succ_eq_add_one, ← add_assoc], dsimp [appr], split_ifs with h, { exact ih }, rw [add_comm, nat.add_sub_assoc (appr_mono _ (nat.le_add_right m k))], apply dvd_add _ ih, apply dvd_mul_of_dvd_left, apply pow_dvd_pow _ (nat.le_add_right m k), end lemma appr_spec (n : ℕ) : ∀ (x : ℤ_[p]), x - appr x n ∈ (ideal.span {p^n} : ideal ℤ_[p]) := begin simp only [ideal.mem_span_singleton], induction n with n ih, { simp only [is_unit_one, is_unit.dvd, pow_zero, forall_true_iff], }, { intro x, dsimp only [appr], split_ifs with h, { rw h, apply dvd_zero }, { push_cast, rw sub_add_eq_sub_sub, obtain ⟨c, hc⟩ := ih x, simp only [ring_hom.map_nat_cast, zmod.nat_cast_self, ring_hom.map_pow, ring_hom.map_mul, zmod.nat_cast_val], have hc' : c ≠ 0, { rintro rfl, simp only [mul_zero] at hc, contradiction }, conv_rhs { congr, simp only [hc], }, rw show (x - ↑(appr x n)).valuation = (↑p ^ n * c).valuation, { rw hc }, rw [valuation_p_pow_mul _ _ hc', add_sub_cancel', pow_succ', ← mul_sub], apply mul_dvd_mul_left, by_cases hc0 : c.valuation.nat_abs = 0, { simp only [hc0, mul_one, pow_zero], rw [mul_comm, unit_coeff_spec h] at hc, suffices : c = unit_coeff h, { rw [← this, ← ideal.mem_span_singleton, ← maximal_ideal_eq_span_p], apply to_zmod_spec }, obtain ⟨c, rfl⟩ : is_unit c, -- TODO: write a can_lift instance for units { rw int.nat_abs_eq_zero at hc0, rw [is_unit_iff, norm_eq_pow_val hc', hc0, neg_zero, fpow_zero], }, rw discrete_valuation_ring.unit_mul_pow_congr_unit _ _ _ _ _ hc, exact irreducible_p }, { rw [zero_pow (nat.pos_of_ne_zero hc0)], simp only [sub_zero, zmod.cast_zero, mul_zero], rw unit_coeff_spec hc', apply dvd_mul_of_dvd_right, apply dvd_pow (dvd_refl _), exact hc0 } } } end attribute [irreducible] appr /-- A ring hom from `ℤ_[p]` to `zmod (p^n)`, with underlying function `padic_int.appr n`. -/ def to_zmod_pow (n : ℕ) : ℤ_[p] →+* zmod (p ^ n) := to_zmod_hom (p^n) (λ x, appr x n) (by { intros, convert appr_spec n _ using 1, simp }) (by { intros x a b ha hb, apply zmod_congr_of_sub_mem_span n x a b, { simpa using ha }, { simpa using hb } }) lemma ker_to_zmod_pow (n : ℕ) : (to_zmod_pow n : ℤ_[p] →+* zmod (p ^ n)).ker = ideal.span {p ^ n} := begin ext x, rw ring_hom.mem_ker, split, { intro h, suffices : x.appr n = 0, { convert appr_spec n x, simp only [this, sub_zero, cast_zero], }, dsimp [to_zmod_pow, to_zmod_hom] at h, rw zmod.nat_coe_zmod_eq_zero_iff_dvd at h, apply eq_zero_of_dvd_of_lt h (appr_lt _ _), }, { intro h, rw ← sub_zero x at h, dsimp [to_zmod_pow, to_zmod_hom], rw [zmod_congr_of_sub_mem_span n x _ 0 _ h, cast_zero], apply appr_spec, } end @[simp] lemma zmod_cast_comp_to_zmod_pow (m n : ℕ) (h : m ≤ n) : (zmod.cast_hom (pow_dvd_pow p h) (zmod (p ^ m))).comp (to_zmod_pow n) = to_zmod_pow m := begin apply zmod.ring_hom_eq_of_ker_eq, ext x, rw [ring_hom.mem_ker, ring_hom.mem_ker], simp only [function.comp_app, zmod.cast_hom_apply, ring_hom.coe_comp], simp only [to_zmod_pow, to_zmod_hom, ring_hom.coe_mk], rw [zmod.cast_nat_cast (pow_dvd_pow p h), zmod_congr_of_sub_mem_span m (x.appr n) (x.appr n) (x.appr m)], { rw [sub_self], apply ideal.zero_mem _, }, { rw ideal.mem_span_singleton, rcases dvd_appr_sub_appr x m n h with ⟨c, hc⟩, use c, rw [← nat.cast_sub (appr_mono _ h), hc, nat.cast_mul, nat.cast_pow], }, { apply_instance } end @[simp] lemma cast_to_zmod_pow (m n : ℕ) (h : m ≤ n) (x : ℤ_[p]) : ↑(to_zmod_pow n x) = to_zmod_pow m x := by { rw ← zmod_cast_comp_to_zmod_pow _ _ h, refl } lemma dense_range_nat_cast : dense_range (nat.cast : ℕ → ℤ_[p]) := begin intro x, rw metric.mem_closure_range_iff, intros ε hε, obtain ⟨n, hn⟩ := exists_pow_neg_lt p hε, use (x.appr n), rw dist_eq_norm, apply lt_of_le_of_lt _ hn, rw norm_le_pow_iff_mem_span_pow, apply appr_spec, end lemma dense_range_int_cast : dense_range (int.cast : ℤ → ℤ_[p]) := begin intro x, apply dense_range_nat_cast.induction_on x, { exact is_closed_closure, }, { intro a, change (a.cast : ℤ_[p]) with (a : ℤ).cast, apply subset_closure, exact set.mem_range_self _ } end end ring_homs section lift /-! ### Universal property as projective limit -/ open cau_seq padic_seq variables {R : Type*} [comm_ring R] (f : Π k : ℕ, R →+* zmod (p^k)) (f_compat : ∀ k1 k2 (hk : k1 ≤ k2), (zmod.cast_hom (pow_dvd_pow p hk) _).comp (f k2) = f k1) omit hp_prime /-- Given a family of ring homs `f : Π n : ℕ, R →+* zmod (p ^ n)`, `nth_hom f r` is an integer-valued sequence whose `n`th value is the unique integer `k` such that `0 ≤ k < p ^ n` and `f n r = (k : zmod (p ^ n))`. -/ def nth_hom (r : R) : ℕ → ℤ := λ n, (f n r : zmod (p^n)).val @[simp] lemma nth_hom_zero : nth_hom f 0 = 0 := by simp [nth_hom]; refl variable {f} include hp_prime include f_compat lemma pow_dvd_nth_hom_sub (r : R) (i j : ℕ) (h : i ≤ j) : ↑p ^ i ∣ nth_hom f r j - nth_hom f r i := begin specialize f_compat (i) (j) h, rw [← int.coe_nat_pow, ← zmod.int_coe_zmod_eq_zero_iff_dvd, int.cast_sub], dsimp [nth_hom], rw [← f_compat, ring_hom.comp_apply], have : fact (p ^ (i) > 0) := pow_pos (nat.prime.pos ‹_›) _, have : fact (p ^ (j) > 0) := pow_pos (nat.prime.pos ‹_›) _, unfreezingI { simp only [zmod.cast_id, zmod.cast_hom_apply, sub_self, zmod.nat_cast_val], }, end lemma is_cau_seq_nth_hom (r : R): is_cau_seq (padic_norm p) (λ n, nth_hom f r n) := begin intros ε hε, obtain ⟨k, hk⟩ : ∃ k : ℕ, (p ^ - (↑(k : ℕ) : ℤ) : ℚ) < ε := exists_pow_neg_lt_rat p hε, use k, intros j hj, refine lt_of_le_of_lt _ hk, norm_cast, rw ← padic_norm.dvd_iff_norm_le, exact_mod_cast pow_dvd_nth_hom_sub f_compat r k j hj end /-- `nth_hom_seq f_compat r` bundles `padic_int.nth_hom f r` as a Cauchy sequence of rationals with respect to the `p`-adic norm. The `n`th value of the sequence is `((f n r).val : ℚ)`. -/ def nth_hom_seq (r : R) : padic_seq p := ⟨λ n, nth_hom f r n, is_cau_seq_nth_hom f_compat r⟩ lemma nth_hom_seq_one : nth_hom_seq f_compat 1 ≈ 1 := begin intros ε hε, change _ < _ at hε, use 1, intros j hj, haveI : fact (1 < p^j) := nat.one_lt_pow _ _ (by linarith) (nat.prime.one_lt ‹_›), simp [nth_hom_seq, nth_hom, zmod.val_one, hε], end lemma nth_hom_seq_add (r s : R) : nth_hom_seq f_compat (r + s) ≈ nth_hom_seq f_compat r + nth_hom_seq f_compat s := begin intros ε hε, obtain ⟨n, hn⟩ := exists_pow_neg_lt_rat p hε, use n, intros j hj, dsimp [nth_hom_seq], apply lt_of_le_of_lt _ hn, rw [← int.cast_add, ← int.cast_sub, ← padic_norm.dvd_iff_norm_le, ← zmod.int_coe_zmod_eq_zero_iff_dvd], dsimp [nth_hom], have : fact (p ^ n > 0) := pow_pos (nat.prime.pos ‹_›) _, have : fact (p ^ j > 0) := pow_pos (nat.prime.pos ‹_›) _, unfreezingI { simp only [int.cast_coe_nat, int.cast_add, ring_hom.map_add, int.cast_sub, zmod.nat_cast_val] }, rw [zmod.cast_add (show p ^ n ∣ p ^ j, from _), sub_self], { apply_instance }, { apply pow_dvd_pow, linarith only [hj] }, end lemma nth_hom_seq_mul (r s : R) : nth_hom_seq f_compat (r * s) ≈ nth_hom_seq f_compat r * nth_hom_seq f_compat s := begin intros ε hε, obtain ⟨n, hn⟩ := exists_pow_neg_lt_rat p hε, use n, intros j hj, dsimp [nth_hom_seq], apply lt_of_le_of_lt _ hn, rw [← int.cast_mul, ← int.cast_sub, ← padic_norm.dvd_iff_norm_le, ← zmod.int_coe_zmod_eq_zero_iff_dvd], dsimp [nth_hom], have : fact (p ^ n > 0) := pow_pos (nat.prime.pos ‹_›) _, have : fact (p ^ j > 0) := pow_pos (nat.prime.pos ‹_›) _, unfreezingI { simp only [int.cast_coe_nat, int.cast_mul, int.cast_sub, ring_hom.map_mul, zmod.nat_cast_val] }, rw [zmod.cast_mul (show p ^ n ∣ p ^ j, from _), sub_self], { apply_instance }, { apply pow_dvd_pow, linarith only [hj] }, end /-- `lim_nth_hom f_compat r` is the limit of a sequence `f` of compatible ring homs `R →+* zmod (p^k)`. This is itself a ring hom: see `padic_int.lift`. -/ def lim_nth_hom (r : R) : ℤ_[p] := of_int_seq (nth_hom f r) (is_cau_seq_nth_hom f_compat r) lemma lim_nth_hom_spec (r : R) : ∀ ε : ℝ, 0 < ε → ∃ N : ℕ, ∀ n ≥ N, ∥lim_nth_hom f_compat r - nth_hom f r n∥ < ε := begin intros ε hε, obtain ⟨ε', hε'0, hε'⟩ : ∃ v : ℚ, (0 : ℝ) < v ∧ ↑v < ε := exists_rat_btwn hε, norm_cast at hε'0, obtain ⟨N, hN⟩ := padic_norm_e.defn (nth_hom_seq f_compat r) hε'0, use N, intros n hn, apply lt_trans _ hε', change ↑(padic_norm_e _) < _, norm_cast, convert hN _ hn, simp [nth_hom, lim_nth_hom, nth_hom_seq, of_int_seq], end lemma lim_nth_hom_zero : lim_nth_hom f_compat 0 = 0 := by simp [lim_nth_hom]; refl lemma lim_nth_hom_one : lim_nth_hom f_compat 1 = 1 := subtype.ext $ quot.sound $ nth_hom_seq_one _ lemma lim_nth_hom_add (r s : R) : lim_nth_hom f_compat (r + s) = lim_nth_hom f_compat r + lim_nth_hom f_compat s := subtype.ext $ quot.sound $ nth_hom_seq_add _ _ _ lemma lim_nth_hom_mul (r s : R) : lim_nth_hom f_compat (r * s) = lim_nth_hom f_compat r * lim_nth_hom f_compat s := subtype.ext $ quot.sound $ nth_hom_seq_mul _ _ _ -- TODO: generalize this to arbitrary complete discrete valuation rings /-- `lift f_compat` is the limit of a sequence `f` of compatible ring homs `R →+* zmod (p^k)`, with the equality `lift f_compat r = padic_int.lim_nth_hom f_compat r`. -/ def lift : R →+* ℤ_[p] := { to_fun := lim_nth_hom f_compat, map_one' := lim_nth_hom_one f_compat, map_mul' := lim_nth_hom_mul f_compat, map_zero' := lim_nth_hom_zero f_compat, map_add' := lim_nth_hom_add f_compat } omit f_compat lemma lift_sub_val_mem_span (r : R) (n : ℕ) : (lift f_compat r - (f n r).val) ∈ (ideal.span {↑p ^ n} : ideal ℤ_[p]) := begin obtain ⟨k, hk⟩ := lim_nth_hom_spec f_compat r _ (show (0 : ℝ) < p ^ (-n : ℤ), from nat.fpow_pos_of_pos hp_prime.pos _), have := le_of_lt (hk (max n k) (le_max_right _ _)), rw norm_le_pow_iff_mem_span_pow at this, dsimp [lift], rw sub_eq_sub_add_sub (lim_nth_hom f_compat r) _ ↑(nth_hom f r (max n k)), apply ideal.add_mem _ _ this, rw [ideal.mem_span_singleton], simpa only [ring_hom.eq_int_cast, ring_hom.map_pow, int.cast_sub] using (int.cast_ring_hom ℤ_[p]).map_dvd (pow_dvd_nth_hom_sub f_compat r n (max n k) (le_max_left _ _)), end /-- One part of the universal property of `ℤ_[p]` as a projective limit. See also `padic_int.lift_unique`. -/ lemma lift_spec (n : ℕ) : (to_zmod_pow n).comp (lift f_compat) = f n := begin ext r, haveI : fact (0 < p ^ n) := pow_pos (nat.prime.pos ‹_›) n, rw [ring_hom.comp_apply, ← zmod.nat_cast_zmod_val (f n r), ← (to_zmod_pow n).map_nat_cast, ← sub_eq_zero, ← ring_hom.map_sub, ← ring_hom.mem_ker, ker_to_zmod_pow], apply lift_sub_val_mem_span, end /-- One part of the universal property of `ℤ_[p]` as a projective limit. See also `padic_int.lift_spec`. -/ lemma lift_unique (g : R →+* ℤ_[p]) (hg : ∀ n, (to_zmod_pow n).comp g = f n) : lift f_compat = g := begin ext1 r, apply eq_of_forall_dist_le, intros ε hε, obtain ⟨n, hn⟩ := exists_pow_neg_lt p hε, apply le_trans _ (le_of_lt hn), rw [dist_eq_norm, norm_le_pow_iff_mem_span_pow, ← ker_to_zmod_pow, ring_hom.mem_ker, ring_hom.map_sub, ← ring_hom.comp_apply, ← ring_hom.comp_apply, lift_spec, hg, sub_self], end @[simp] lemma lift_self (z : ℤ_[p]) : @lift p _ ℤ_[p] _ to_zmod_pow zmod_cast_comp_to_zmod_pow z = z := begin show _ = ring_hom.id _ z, rw @lift_unique p _ ℤ_[p] _ _ zmod_cast_comp_to_zmod_pow (ring_hom.id ℤ_[p]), intro, rw ring_hom.comp_id, end end lift lemma ext_of_to_zmod_pow {x y : ℤ_[p]} : (∀ n, to_zmod_pow n x = to_zmod_pow n y) ↔ x = y := begin split, { intro h, rw [← lift_self x, ← lift_self y], simp [lift, lim_nth_hom, nth_hom, h] }, { rintro rfl _, refl } end lemma to_zmod_pow_eq_iff_ext {R : Type*} [comm_ring R] {g g' : R →+* ℤ_[p]} : (∀ n, (to_zmod_pow n).comp g = (to_zmod_pow n).comp g') ↔ g = g' := begin split, { intro hg, ext x : 1, apply ext_of_to_zmod_pow.mp, intro n, show (to_zmod_pow n).comp g x = (to_zmod_pow n).comp g' x, rw hg n }, { rintro rfl _, refl } end end padic_int