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
9a11ad98f97e214b983b5217348a2798ca1c8c93
491068d2ad28831e7dade8d6dff871c3e49d9431
/tests/lean/run/priority_test2.lean
05f9121c4fc34d768170506ebbeb5c5a15ba192a
[ "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
692
lean
open nat structure foo [class] := (a : nat) (b : nat) definition i1 [instance] [priority std.priority.default-2] : foo := foo.mk 1 1 example : foo.a = 1 := rfl definition i2 [instance] [priority std.priority.default-1] : foo := foo.mk 2 2 example : foo.a = 2 := rfl definition i3 [instance] : foo := foo.mk 3 3 example : foo.a = 3 := rfl definition i4 [instance] [priority std.priority.default-1] : foo := foo.mk 4 4 example : foo.a = 3 := rfl attribute i4 [priority std.priority.default+2] example : foo.a = 4 := rfl attribute i1 [priority std.priority.default+3] example : foo.a = 1 := rfl attribute i2 [instance] [priority std.priority.default+4] example : foo.a = 2 := rfl
7312bac090f973eb7918ea99be801d51d272b64c
07c76fbd96ea1786cc6392fa834be62643cea420
/hott/homotopy/EM.hlean
9a724d04c66882bb0880fd72826e6c79fc8dbac9
[ "Apache-2.0" ]
permissive
fpvandoorn/lean2
5a430a153b570bf70dc8526d06f18fc000a60ad9
0889cf65b7b3cebfb8831b8731d89c2453dd1e9f
refs/heads/master
1,592,036,508,364
1,545,093,958,000
1,545,093,958,000
75,436,854
0
0
null
1,480,718,780,000
1,480,718,780,000
null
UTF-8
Lean
false
false
18,141
hlean
/- Copyright (c) 2016 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn Eilenberg MacLane spaces -/ import hit.groupoid_quotient homotopy.hopf homotopy.freudenthal homotopy.homotopy_group open algebra pointed nat eq category group is_trunc iso unit trunc equiv is_conn function is_equiv trunc_index namespace EM open groupoid_quotient variables {G : Group} definition EM1' (G : Group) : Type := groupoid_quotient (Groupoid_of_Group G) definition EM1 [constructor] (G : Group) : Type* := pointed.MK (EM1' G) (elt star) definition base : EM1' G := elt star definition pth : G → base = base := pth definition resp_mul (g h : G) : pth (g * h) = pth g ⬝ pth h := resp_comp h g definition resp_one : pth (1 : G) = idp := resp_id star definition resp_inv (g : G) : pth (g⁻¹) = (pth g)⁻¹ := resp_inv g local attribute pointed.MK pointed.carrier EM1 EM1' [reducible] protected definition rec {P : EM1' G → Type} [H : Π(x : EM1' G), is_trunc 1 (P x)] (Pb : P base) (Pp : Π(g : G), Pb =[pth g] Pb) (Pmul : Π(g h : G), change_path (resp_mul g h) (Pp (g * h)) = Pp g ⬝o Pp h) (x : EM1' G) : P x := begin induction x, { induction g, exact Pb}, { induction a, induction b, exact Pp f}, { induction a, induction b, induction c, exact Pmul f g} end protected definition rec_on {P : EM1' G → Type} [H : Π(x : EM1' G), is_trunc 1 (P x)] (x : EM1' G) (Pb : P base) (Pp : Π(g : G), Pb =[pth g] Pb) (Pmul : Π(g h : G), change_path (resp_mul g h) (Pp (g * h)) = Pp g ⬝o Pp h) : P x := EM.rec Pb Pp Pmul x protected definition set_rec {P : EM1' G → Type} [H : Π(x : EM1' G), is_set (P x)] (Pb : P base) (Pp : Π(g : G), Pb =[pth g] Pb) (x : EM1' G) : P x := EM.rec Pb Pp !center x protected definition prop_rec {P : EM1' G → Type} [H : Π(x : EM1' G), is_prop (P x)] (Pb : P base) (x : EM1' G) : P x := EM.rec Pb !center !center x definition rec_pth {P : EM1' G → Type} [H : Π(x : EM1' G), is_trunc 1 (P x)] {Pb : P base} {Pp : Π(g : G), Pb =[pth g] Pb} (Pmul : Π(g h : G), change_path (resp_mul g h) (Pp (g * h)) = Pp g ⬝o Pp h) (g : G) : apd (EM.rec Pb Pp Pmul) (pth g) = Pp g := proof !rec_pth qed protected definition elim {P : Type} [is_trunc 1 P] (Pb : P) (Pp : Π(g : G), Pb = Pb) (Pmul : Π(g h : G), Pp (g * h) = Pp g ⬝ Pp h) (x : EM1' G) : P := begin induction x, { exact Pb}, { exact Pp f}, { exact Pmul f g} end protected definition elim_on [reducible] {P : Type} [is_trunc 1 P] (x : EM1' G) (Pb : P) (Pp : G → Pb = Pb) (Pmul : Π(g h : G), Pp (g * h) = Pp g ⬝ Pp h) : P := EM.elim Pb Pp Pmul x protected definition set_elim [reducible] {P : Type} [is_set P] (Pb : P) (Pp : G → Pb = Pb) (x : EM1' G) : P := EM.elim Pb Pp !center x protected definition prop_elim [reducible] {P : Type} [is_prop P] (Pb : P) (x : EM1' G) : P := EM.elim Pb !center !center x definition elim_pth {P : Type} [is_trunc 1 P] {Pb : P} {Pp : G → Pb = Pb} (Pmul : Π(g h : G), Pp (g * h) = Pp g ⬝ Pp h) (g : G) : ap (EM.elim Pb Pp Pmul) (pth g) = Pp g := proof !elim_pth qed protected definition elim_set.{u} (Pb : Set.{u}) (Pp : Π(g : G), Pb ≃ Pb) (Pmul : Π(g h : G) (x : Pb), Pp (g * h) x = Pp h (Pp g x)) (x : EM1' G) : Set.{u} := groupoid_quotient.elim_set (λu, Pb) (λu v, Pp) (λu v w g h, proof Pmul h g qed) x theorem elim_set_pth {Pb : Set} {Pp : Π(g : G), Pb ≃ Pb} (Pmul : Π(g h : G) (x : Pb), Pp (g * h) x = Pp h (Pp g x)) (g : G) : transport (EM.elim_set Pb Pp Pmul) (pth g) = Pp g := !elim_set_pth end EM attribute EM.base [constructor] attribute EM.rec EM.elim [unfold 7] [recursor 7] attribute EM.rec_on EM.elim_on [unfold 4] attribute EM.set_rec EM.set_elim [unfold 6] attribute EM.prop_rec EM.prop_elim EM.elim_set [unfold 5] namespace EM open groupoid_quotient variables (G : Group) definition base_eq_base_equiv : (base = base :> EM1 G) ≃ G := !elt_eq_elt_equiv definition fundamental_group_EM1 : π₁ (EM1 G) ≃g G := begin fapply isomorphism_of_equiv, { exact trunc_equiv_trunc 0 !base_eq_base_equiv ⬝e trunc_equiv 0 G}, { intros g h, induction g with p, induction h with q, exact encode_con p q} end proposition is_trunc_EM1 [instance] : is_trunc 1 (EM1 G) := !is_trunc_groupoid_quotient proposition is_trunc_EM1' [instance] : is_trunc 1 (EM1' G) := !is_trunc_groupoid_quotient proposition is_conn_EM1' [instance] : is_conn 0 (EM1' G) := by apply @is_conn_groupoid_quotient; esimp; exact _ proposition is_conn_EM1 [instance] : is_conn 0 (EM1 G) := is_conn_EM1' G variable {G} open infgroup definition EM1_map [unfold 6] {G : Group} {X : Type*} (e : G →∞g Ωg X) [is_trunc 1 X] : EM1 G → X := begin intro x, induction x using EM.elim, { exact Point X }, { exact e g }, { exact to_respect_mul_inf e g h } end /- Uniqueness of K(G, 1) -/ definition EM1_pmap [constructor] {G : Group} {X : Type*} (e : G →∞g Ωg X) [is_trunc 1 X] : EM1 G →* X := pmap.mk (EM1_map e) idp variable (G) definition loop_EM1 [constructor] : G ≃* Ω (EM1 G) := (pequiv_of_equiv (base_eq_base_equiv G) idp)⁻¹ᵉ* variable {G} definition loop_EM1_pmap {G : Group} {X : Type*} (e : G →∞g Ωg X) [is_trunc 1 X] : Ω→(EM1_pmap e) ∘* loop_EM1 G ~* pmap_of_inf_homomorphism e := begin fapply phomotopy.mk, { intro g, refine !idp_con ⬝ elim_pth (to_respect_mul_inf e) g }, { apply is_set.elim } end definition EM1_pequiv'.{u} {G : Group.{u}} {X : pType.{u}} (e : G ≃∞g Ωg X) [is_conn 0 X] [is_trunc 1 X] : EM1 G ≃* X := begin apply pequiv_of_pmap (EM1_pmap e), apply whitehead_principle_pointed 1, intro k, cases k with k, { apply @is_equiv_of_is_contr, all_goals (esimp; exact _)}, { cases k with k, { apply is_equiv_trunc_functor, esimp, apply is_equiv.homotopy_closed, { symmetry, exact phomotopy_pinv_right_of_phomotopy (loop_EM1_pmap e) }, refine is_equiv_compose e _ _ _, apply inf_isomorphism.is_equiv_to_hom }, { apply @is_equiv_of_is_contr, do 2 exact trivial_homotopy_group_of_is_trunc _ (succ_lt_succ !zero_lt_succ)}} end definition EM1_pequiv.{u} {G : Group.{u}} {X : pType.{u}} (e : G ≃g π₁ X) [is_conn 0 X] [is_trunc 1 X] : EM1 G ≃* X := have is_set (Ωg X), from !is_trunc_loop, EM1_pequiv' (inf_isomorphism_of_isomorphism e ⬝∞g gtrunc_isomorphism (Ωg X)) definition EM1_pequiv_type (X : Type*) [is_conn 0 X] [is_trunc 1 X] : EM1 (π₁ X) ≃* X := EM1_pequiv !isomorphism.refl end EM open hopf susp namespace EM /- EM1 G is an h-space if G is an abelian group. This allows us to construct K(G,n) for n ≥ 2 -/ variables {G : AbGroup} (n : ℕ) definition EM1_mul [unfold 2 3] (x x' : EM1' G) : EM1' G := begin induction x, { exact x'}, { induction x' using EM.set_rec, { exact pth g}, { exact abstract begin apply loop_pathover, apply square_of_eq, refine !resp_mul⁻¹ ⬝ _ ⬝ !resp_mul, exact ap pth !mul.comm end end}}, { refine EM.prop_rec _ x', apply resp_mul } end variable (G) definition EM1_mul_one (x : EM1' G) : EM1_mul x base = x := begin induction x using EM.set_rec, { reflexivity}, { apply eq_pathover_id_right, apply hdeg_square, refine EM.elim_pth _ g} end definition h_space_EM1 [constructor] [instance] : h_space (EM1' G) := begin fapply h_space.mk, { exact EM1_mul}, { exact base}, { intro x', reflexivity}, { apply EM1_mul_one} end /- K(G, n+1) -/ definition EMadd1 : ℕ → Type* | 0 := EM1 G | (n+1) := ptrunc (n+2) (susp (EMadd1 n)) definition EMadd1_succ [unfold_full] (n : ℕ) : EMadd1 G (succ n) = ptrunc (n.+2) (susp (EMadd1 G n)) := idp definition loop_EM2 : Ω[1] (EMadd1 G 1) ≃* EM1 G := hopf.delooping (EM1' G) idp definition is_conn_EMadd1 [instance] (n : ℕ) : is_conn n (EMadd1 G n) := begin induction n with n IH, { apply is_conn_EM1 }, { rewrite EMadd1_succ, exact _ } end definition is_trunc_EMadd1 [instance] (n : ℕ) : is_trunc (n+1) (EMadd1 G n) := begin cases n with n, { apply is_trunc_EM1 }, { apply is_trunc_trunc } end /- loops of an EM-space -/ definition loop_EMadd1 (n : ℕ) : EMadd1 G n ≃* Ω (EMadd1 G (succ n)) := begin cases n with n, { exact !loop_EM2⁻¹ᵉ* }, { rewrite [EMadd1_succ G (succ n)], refine (ptrunc_pequiv (succ n + 1) _)⁻¹ᵉ* ⬝e* _ ⬝e* (loop_ptrunc_pequiv _ _)⁻¹ᵉ*, have succ n + 1 ≤ 2 * succ n, from add_mul_le_mul_add n 1 1, refine freudenthal_pequiv this _ } end definition loopn_EMadd1_pequiv_EM1 (G : AbGroup) (n : ℕ) : EM1 G ≃* Ω[n] (EMadd1 G n) := begin induction n with n e, { reflexivity }, { refine _ ⬝e* !loopn_succ_in⁻¹ᵉ*, refine _ ⬝e* loopn_pequiv_loopn n !loop_EMadd1, exact e } end -- use loopn_EMadd1_pequiv_EM1 in this definition? definition loopn_EMadd1 (G : AbGroup) (n : ℕ) : G ≃* Ω[succ n] (EMadd1 G n) := begin induction n with n e, { apply loop_EM1 }, { refine _ ⬝e* !loopn_succ_in⁻¹ᵉ*, refine _ ⬝e* loopn_pequiv_loopn (succ n) !loop_EMadd1, exact e } end definition loopn_EMadd1_succ [unfold_full] (G : AbGroup) (n : ℕ) : loopn_EMadd1 G (succ n) ~* !loopn_succ_in⁻¹ᵉ* ∘* apn (succ n) !loop_EMadd1 ∘* loopn_EMadd1 G n := by reflexivity definition EM_up {G : AbGroup} {X : Type*} {n : ℕ} (e : AbInfGroup_of_AbGroup G →∞g Ωg[succ (succ n)] X) : AbInfGroup_of_AbGroup G →∞g Ωg[succ n] (Ω X) := gloopn_succ_in (succ n) X ∘∞g e definition EMadd1_pmap [unfold 8] {G : AbGroup} {X : Type*} (n : ℕ) (e : AbInfGroup_of_AbGroup G →∞g Ωg[succ n] X) [H : is_trunc (n.+1) X] : EMadd1 G n →* X := begin revert X e H, induction n with n f: intro X e H, { exact EM1_pmap e }, rewrite [EMadd1_succ], apply ptrunc.elim ((succ n).+1), apply susp_elim, exact f _ (EM_up e) _ end definition EMadd1_pmap_succ {G : AbGroup} {X : Type*} (n : ℕ) (e : AbInfGroup_of_AbGroup G →∞g Ωg[succ (succ n)] X) [H2 : is_trunc ((succ n).+1) X] : EMadd1_pmap (succ n) e = ptrunc.elim ((succ n).+1) (susp_elim (EMadd1_pmap n (EM_up e))) := by reflexivity definition loop_EMadd1_pmap {G : AbGroup} {X : Type*} {n : ℕ} (e : AbInfGroup_of_AbGroup G →∞g Ωg[succ (succ n)] X) [H : is_trunc ((succ n).+1) X] : Ω→(EMadd1_pmap (succ n) e) ∘* loop_EMadd1 G n ~* EMadd1_pmap n (EM_up e) := begin cases n with n, { apply hopf_delooping_elim }, { refine !passoc⁻¹* ⬝* _, rewrite [EMadd1_pmap_succ (succ n)], refine pwhisker_right _ !ap1_ptrunc_elim ⬝* _, refine !passoc⁻¹* ⬝* _, refine pwhisker_right _ (ptrunc_elim_freudenthal_pequiv (succ n) (succ (succ n)) (add_mul_le_mul_add n 1 1) _) ⬝* _, reflexivity } end definition loopn_EMadd1_pmap' {G : AbGroup} {X : Type*} {n : ℕ} (e : AbInfGroup_of_AbGroup G →∞g Ωg[succ n] X) [H : is_trunc (n.+1) X] : Ω→[succ n](EMadd1_pmap n e) ∘* loopn_EMadd1 G n ~* pmap_of_inf_homomorphism e := begin revert X e H, induction n with n IH: intro X e H, { apply loop_EM1_pmap }, refine pwhisker_left _ !loopn_EMadd1_succ ⬝* _, refine !passoc⁻¹* ⬝* _, refine pwhisker_right _ !loopn_succ_in_inv_natural ⬝* _, refine !passoc ⬝* _, refine pwhisker_left _ (!passoc⁻¹* ⬝* pwhisker_right _ (!apn_pcompose⁻¹* ⬝* apn_phomotopy _ !loop_EMadd1_pmap) ⬝* !IH) ⬝* _, refine _ ⬝* pinv_pcompose_cancel_left !loopn_succ_in (pmap_of_inf_homomorphism e), apply pwhisker_left, apply phomotopy_of_homotopy, reflexivity, intro g, apply is_set_loopn, end definition EMadd1_pequiv' {G : AbGroup} {X : Type*} (n : ℕ) (e : AbInfGroup_of_AbGroup G ≃∞g Ωg[succ n] X) [H1 : is_conn n X] [H2 : is_trunc (n.+1) X] : EMadd1 G n ≃* X := begin apply pequiv_of_pmap (EMadd1_pmap n e), have is_conn 0 (EMadd1 G n), from is_conn_of_le _ (zero_le_of_nat n), have is_trunc (n.+1) (EMadd1 G n), from !is_trunc_EMadd1, refine whitehead_principle_pointed (n.+1) _ _, intro k, apply @nat.lt_by_cases k (succ n): intro H, { apply @is_equiv_of_is_contr, do 2 exact trivial_homotopy_group_of_is_conn _ (le_of_lt_succ H)}, { cases H, esimp, apply is_equiv_trunc_functor, esimp, apply is_equiv.homotopy_closed, { symmetry, exact phomotopy_pinv_right_of_phomotopy (loopn_EMadd1_pmap' _) }, refine is_equiv_compose e _ _ _, apply inf_isomorphism.is_equiv_to_hom }, { apply @is_equiv_of_is_contr, do 2 exact trivial_homotopy_group_of_is_trunc _ H} end definition EMadd1_pequiv {G : AbGroup} {X : Type*} (n : ℕ) (e : G ≃g πg[n+1] X) [H1 : is_conn n X] [H2 : is_trunc (n.+1) X] : EMadd1 G n ≃* X := begin have is_set (Ωg[succ n] X), from is_set_loopn (succ n) X, apply EMadd1_pequiv' n, refine inf_isomorphism_of_isomorphism e ⬝∞g gtrunc_isomorphism (Ωg[succ n] X), end definition EMadd1_pequiv_succ {G : AbGroup} {X : Type*} (n : ℕ) (e : G ≃g πag[n+2] X) [H1 : is_conn (n.+1) X] [H2 : is_trunc (n.+2) X] : EMadd1 G (succ n) ≃* X := EMadd1_pequiv (succ n) e definition ghomotopy_group_EMadd1 (n : ℕ) : πg[n+1] (EMadd1 G n) ≃g G := begin change π₁ (Ω[n] (EMadd1 G n)) ≃g G, refine homotopy_group_isomorphism_of_pequiv 0 (loopn_EMadd1_pequiv_EM1 G n)⁻¹ᵉ* ⬝g _, apply fundamental_group_EM1, end definition EMadd1_pequiv_type (X : Type*) (n : ℕ) [is_conn (n+1) X] [is_trunc (n+1+1) X] : EMadd1 (πag[n+2] X) (succ n) ≃* X := EMadd1_pequiv_succ n !isomorphism.refl /- K(G, n) -/ definition EM (G : AbGroup) : ℕ → Type* | 0 := G | (k+1) := EMadd1 G k namespace ops abbreviation K := @EM end ops open ops definition homotopy_group_EM (n : ℕ) : π[n] (EM G n) ≃* G := begin cases n with n, { rexact ptrunc_pequiv 0 G }, { exact pequiv_of_isomorphism (ghomotopy_group_EMadd1 G n)} end definition ghomotopy_group_EM (n : ℕ) : πg[n+1] (EM G (n+1)) ≃g G := ghomotopy_group_EMadd1 G n definition is_conn_EM [instance] (n : ℕ) : is_conn (n.-1) (EM G n) := begin cases n with n, { apply is_conn_minus_one, apply tr, unfold [EM], exact 1}, { apply is_conn_EMadd1} end definition is_conn_EM_succ [instance] (n : ℕ) : is_conn n (EM G (succ n)) := is_conn_EM G (succ n) definition is_trunc_EM [instance] (n : ℕ) : is_trunc n (EM G n) := begin cases n with n, { unfold [EM], apply semigroup.is_set_carrier}, { apply is_trunc_EMadd1} end definition loop_EM (n : ℕ) : Ω (K G (succ n)) ≃* K G n := begin cases n with n, { refine _ ⬝e* pequiv_of_isomorphism (fundamental_group_EM1 G), symmetry, apply ptrunc_pequiv }, { exact !loop_EMadd1⁻¹ᵉ* } end open circle int definition EM_pequiv_circle : K agℤ 1 ≃* S¹* := EM1_pequiv fundamental_group_of_circle⁻¹ᵍ /- Functorial action of Eilenberg-Maclane spaces -/ definition EM1_functor [constructor] {G H : Group} (φ : G →g H) : EM1 G →* EM1 H := begin fapply pmap.mk, { intro g, induction g, { exact base }, { exact pth (φ g) }, { exact ap pth (to_respect_mul φ g h) ⬝ resp_mul (φ g) (φ h) }}, { reflexivity } end definition EMadd1_functor [constructor] {G H : AbGroup} (φ : G →g H) (n : ℕ) : EMadd1 G n →* EMadd1 H n := begin induction n with n ψ, { exact EM1_functor φ }, { apply ptrunc_functor, apply susp_functor, exact ψ } end definition EMadd1_functor_succ [constructor] {G H : AbGroup} (φ : G →g H) (n : ℕ) : EMadd1_functor φ (succ n) ~* ptrunc_functor (n+2) (susp_functor (EMadd1_functor φ n)) := by reflexivity definition EM_functor [unfold 4] {G H : AbGroup} (φ : G →g H) (n : ℕ) : K G n →* K H n := begin cases n with n, { exact pmap_of_homomorphism φ }, { exact EMadd1_functor φ n } end /- Equivalence of Groups and pointed connected 1-truncated types -/ definition ptruncconntype10_pequiv (X Y : 1-Type*[0]) (e : π₁ X ≃g π₁ Y) : X ≃* Y := (EM1_pequiv !isomorphism.refl)⁻¹ᵉ* ⬝e* EM1_pequiv e definition EM1_pequiv_ptruncconntype10 (X : 1-Type*[0]) : EM1 (π₁ X) ≃* X := EM1_pequiv_type X definition Group_equiv_ptruncconntype10 [constructor] : Group ≃ 1-Type*[0] := equiv.MK (λG, ptruncconntype.mk (EM1 G) _ pt !is_conn_EM1) (λX, π₁ X) begin intro X, apply ptruncconntype_eq, esimp, exact EM1_pequiv_type X end begin intro G, apply eq_of_isomorphism, apply fundamental_group_EM1 end /- Equivalence of AbGroups and pointed n-connected (n+1)-truncated types (n ≥ 1) -/ open trunc_index definition ptruncconntype_pequiv : Π(n : ℕ) (X Y : (n.+1)-Type*[n]) (e : πg[n+1] X ≃g πg[n+1] Y), X ≃* Y | 0 X Y e := ptruncconntype10_pequiv X Y e | (succ n) X Y e := begin refine (EMadd1_pequiv_succ n _)⁻¹ᵉ* ⬝e* EMadd1_pequiv_succ n !isomorphism.refl, exact e⁻¹ᵍ end definition EM1_pequiv_ptruncconntype (n : ℕ) (X : (n+1+1)-Type*[n+1]) : EMadd1 (πag[n+2] X) (succ n) ≃* X := EMadd1_pequiv_type X n definition AbGroup_equiv_ptruncconntype' [constructor] (n : ℕ) : AbGroup ≃ (n + 1 + 1)-Type*[n+1] := equiv.MK (λG, ptruncconntype.mk (EMadd1 G (n+1)) _ pt _) (λX, πag[n+2] X) begin intro X, apply ptruncconntype_eq, apply EMadd1_pequiv_type end begin intro G, apply AbGroup_eq_of_isomorphism, exact ghomotopy_group_EMadd1 G (n+1) end definition AbGroup_equiv_ptruncconntype [constructor] (n : ℕ) : AbGroup ≃ (n.+2)-Type*[n.+1] := AbGroup_equiv_ptruncconntype' n end EM
91baef365c676cf90ebc46ee7007e54ccee98150
367134ba5a65885e863bdc4507601606690974c1
/src/category_theory/limits/shapes/equalizers.lean
4994b98870ccf1b5976f24af0f71fb983520efec
[ "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
33,009
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Markus Himmel -/ import category_theory.epi_mono import category_theory.limits.limits /-! # Equalizers and coequalizers This file defines (co)equalizers as special cases of (co)limits. An equalizer is the categorical generalization of the subobject {a ∈ A | f(a) = g(a)} known from abelian groups or modules. It is a limit cone over the diagram formed by `f` and `g`. A coequalizer is the dual concept. ## Main definitions * `walking_parallel_pair` is the indexing category used for (co)equalizer_diagrams * `parallel_pair` is a functor from `walking_parallel_pair` to our category `C`. * a `fork` is a cone over a parallel pair. * there is really only one interesting morphism in a fork: the arrow from the vertex of the fork to the domain of f and g. It is called `fork.ι`. * an `equalizer` is now just a `limit (parallel_pair f g)` Each of these has a dual. ## Main statements * `equalizer.ι_mono` states that every equalizer map is a monomorphism * `is_iso_limit_cone_parallel_pair_of_self` states that the identity on the domain of `f` is an equalizer of `f` and `f`. ## Implementation notes As with the other special shapes in the limits library, all the definitions here are given as `abbreviation`s of the general statements for limits, so all the `simp` lemmas and theorems about general limits can be used. ## References * [F. Borceux, *Handbook of Categorical Algebra 1*][borceux-vol1] -/ noncomputable theory open category_theory namespace category_theory.limits local attribute [tidy] tactic.case_bash universes v u u₂ /-- The type of objects for the diagram indexing a (co)equalizer. -/ @[derive decidable_eq, derive inhabited] inductive walking_parallel_pair : Type v | zero | one open walking_parallel_pair /-- The type family of morphisms for the diagram indexing a (co)equalizer. -/ @[derive decidable_eq] inductive walking_parallel_pair_hom : walking_parallel_pair → walking_parallel_pair → Type v | left : walking_parallel_pair_hom zero one | right : walking_parallel_pair_hom zero one | id : Π X : walking_parallel_pair.{v}, walking_parallel_pair_hom X X /-- Satisfying the inhabited linter -/ instance : inhabited (walking_parallel_pair_hom zero one) := { default := walking_parallel_pair_hom.left } open walking_parallel_pair_hom /-- Composition of morphisms in the indexing diagram for (co)equalizers. -/ def walking_parallel_pair_hom.comp : Π (X Y Z : walking_parallel_pair) (f : walking_parallel_pair_hom X Y) (g : walking_parallel_pair_hom Y Z), walking_parallel_pair_hom X Z | _ _ _ (id _) h := h | _ _ _ left (id one) := left | _ _ _ right (id one) := right . instance walking_parallel_pair_hom_category : small_category walking_parallel_pair := { hom := walking_parallel_pair_hom, id := walking_parallel_pair_hom.id, comp := walking_parallel_pair_hom.comp } @[simp] lemma walking_parallel_pair_hom_id (X : walking_parallel_pair) : walking_parallel_pair_hom.id X = 𝟙 X := rfl variables {C : Type u} [category.{v} C] variables {X Y : C} /-- `parallel_pair f g` is the diagram in `C` consisting of the two morphisms `f` and `g` with common domain and codomain. -/ def parallel_pair (f g : X ⟶ Y) : walking_parallel_pair.{v} ⥤ C := { obj := λ x, match x with | zero := X | one := Y end, map := λ x y h, match x, y, h with | _, _, (id _) := 𝟙 _ | _, _, left := f | _, _, right := g end, -- `tidy` can cope with this, but it's too slow: map_comp' := begin rintros (⟨⟩|⟨⟩) (⟨⟩|⟨⟩) (⟨⟩|⟨⟩) ⟨⟩⟨⟩; { unfold_aux, simp; refl }, end, }. @[simp] lemma parallel_pair_obj_zero (f g : X ⟶ Y) : (parallel_pair f g).obj zero = X := rfl @[simp] lemma parallel_pair_obj_one (f g : X ⟶ Y) : (parallel_pair f g).obj one = Y := rfl @[simp] lemma parallel_pair_map_left (f g : X ⟶ Y) : (parallel_pair f g).map left = f := rfl @[simp] lemma parallel_pair_map_right (f g : X ⟶ Y) : (parallel_pair f g).map right = g := rfl @[simp] lemma parallel_pair_functor_obj {F : walking_parallel_pair ⥤ C} (j : walking_parallel_pair) : (parallel_pair (F.map left) (F.map right)).obj j = F.obj j := begin cases j; refl end /-- Every functor indexing a (co)equalizer is naturally isomorphic (actually, equal) to a `parallel_pair` -/ @[simps] def diagram_iso_parallel_pair (F : walking_parallel_pair ⥤ C) : F ≅ parallel_pair (F.map left) (F.map right) := nat_iso.of_components (λ j, eq_to_iso $ by cases j; tidy) $ by tidy /-- A fork on `f` and `g` is just a `cone (parallel_pair f g)`. -/ abbreviation fork (f g : X ⟶ Y) := cone (parallel_pair f g) /-- A cofork on `f` and `g` is just a `cocone (parallel_pair f g)`. -/ abbreviation cofork (f g : X ⟶ Y) := cocone (parallel_pair f g) variables {f g : X ⟶ Y} /-- A fork `t` on the parallel pair `f g : X ⟶ Y` consists of two morphisms `t.π.app zero : t.X ⟶ X` and `t.π.app one : t.X ⟶ Y`. Of these, only the first one is interesting, and we give it the shorter name `fork.ι t`. -/ abbreviation fork.ι (t : fork f g) := t.π.app zero /-- A cofork `t` on the parallel_pair `f g : X ⟶ Y` consists of two morphisms `t.ι.app zero : X ⟶ t.X` and `t.ι.app one : Y ⟶ t.X`. Of these, only the second one is interesting, and we give it the shorter name `cofork.π t`. -/ abbreviation cofork.π (t : cofork f g) := t.ι.app one @[simp] lemma fork.ι_eq_app_zero (t : fork f g) : t.ι = t.π.app zero := rfl @[simp] lemma cofork.π_eq_app_one (t : cofork f g) : t.π = t.ι.app one := rfl @[simp, reassoc] lemma fork.app_zero_left (s : fork f g) : s.π.app zero ≫ f = s.π.app one := by rw [←s.w left, parallel_pair_map_left] @[simp, reassoc] lemma fork.app_zero_right (s : fork f g) : s.π.app zero ≫ g = s.π.app one := by rw [←s.w right, parallel_pair_map_right] @[simp, reassoc] lemma cofork.left_app_one (s : cofork f g) : f ≫ s.ι.app one = s.ι.app zero := by rw [←s.w left, parallel_pair_map_left] @[simp, reassoc] lemma cofork.right_app_one (s : cofork f g) : g ≫ s.ι.app one = s.ι.app zero := by rw [←s.w right, parallel_pair_map_right] /-- A fork on `f g : X ⟶ Y` is determined by the morphism `ι : P ⟶ X` satisfying `ι ≫ f = ι ≫ g`. -/ @[simps] def fork.of_ι {P : C} (ι : P ⟶ X) (w : ι ≫ f = ι ≫ g) : fork f g := { X := P, π := { app := λ X, begin cases X, exact ι, exact ι ≫ f, end, naturality' := λ X Y f, begin cases X; cases Y; cases f; dsimp; simp, { dsimp, simp, }, -- See note [dsimp, simp]. { exact w }, { dsimp, simp, }, end } } /-- A cofork on `f g : X ⟶ Y` is determined by the morphism `π : Y ⟶ P` satisfying `f ≫ π = g ≫ π`. -/ @[simps] def cofork.of_π {P : C} (π : Y ⟶ P) (w : f ≫ π = g ≫ π) : cofork f g := { X := P, ι := { app := λ X, walking_parallel_pair.cases_on X (f ≫ π) π, naturality' := λ i j f, by { cases f; dsimp; simp [w] } } } -- See note [dsimp, simp] lemma fork.ι_of_ι {P : C} (ι : P ⟶ X) (w : ι ≫ f = ι ≫ g) : (fork.of_ι ι w).ι = ι := rfl lemma cofork.π_of_π {P : C} (π : Y ⟶ P) (w : f ≫ π = g ≫ π) : (cofork.of_π π w).π = π := rfl @[reassoc] lemma fork.condition (t : fork f g) : t.ι ≫ f = t.ι ≫ g := by rw [t.app_zero_left, t.app_zero_right] @[reassoc] lemma cofork.condition (t : cofork f g) : f ≫ t.π = g ≫ t.π := by rw [t.left_app_one, t.right_app_one] /-- To check whether two maps are equalized by both maps of a fork, it suffices to check it for the first map -/ lemma fork.equalizer_ext (s : fork f g) {W : C} {k l : W ⟶ s.X} (h : k ≫ fork.ι s = l ≫ fork.ι s) : ∀ (j : walking_parallel_pair), k ≫ s.π.app j = l ≫ s.π.app j | zero := h | one := by rw [←fork.app_zero_left, reassoc_of h] /-- To check whether two maps are coequalized by both maps of a cofork, it suffices to check it for the second map -/ lemma cofork.coequalizer_ext (s : cofork f g) {W : C} {k l : s.X ⟶ W} (h : cofork.π s ≫ k = cofork.π s ≫ l) : ∀ (j : walking_parallel_pair), s.ι.app j ≫ k = s.ι.app j ≫ l | zero := by simp only [←cofork.left_app_one, category.assoc, h] | one := h lemma fork.is_limit.hom_ext {s : fork f g} (hs : is_limit s) {W : C} {k l : W ⟶ s.X} (h : k ≫ fork.ι s = l ≫ fork.ι s) : k = l := hs.hom_ext $ fork.equalizer_ext _ h lemma cofork.is_colimit.hom_ext {s : cofork f g} (hs : is_colimit s) {W : C} {k l : s.X ⟶ W} (h : cofork.π s ≫ k = cofork.π s ≫ l) : k = l := hs.hom_ext $ cofork.coequalizer_ext _ h /-- If `s` is a limit fork over `f` and `g`, then a morphism `k : W ⟶ X` satisfying `k ≫ f = k ≫ g` induces a morphism `l : W ⟶ s.X` such that `l ≫ fork.ι s = k`. -/ def fork.is_limit.lift' {s : fork f g} (hs : is_limit s) {W : C} (k : W ⟶ X) (h : k ≫ f = k ≫ g) : {l : W ⟶ s.X // l ≫ fork.ι s = k} := ⟨hs.lift $ fork.of_ι _ h, hs.fac _ _⟩ /-- If `s` is a colimit cofork over `f` and `g`, then a morphism `k : Y ⟶ W` satisfying `f ≫ k = g ≫ k` induces a morphism `l : s.X ⟶ W` such that `cofork.π s ≫ l = k`. -/ def cofork.is_colimit.desc' {s : cofork f g} (hs : is_colimit s) {W : C} (k : Y ⟶ W) (h : f ≫ k = g ≫ k) : {l : s.X ⟶ W // cofork.π s ≫ l = k} := ⟨hs.desc $ cofork.of_π _ h, hs.fac _ _⟩ /-- This is a slightly more convenient method to verify that a fork is a limit cone. It only asks for a proof of facts that carry any mathematical content -/ def fork.is_limit.mk (t : fork f g) (lift : Π (s : fork f g), s.X ⟶ t.X) (fac : ∀ (s : fork f g), lift s ≫ fork.ι t = fork.ι s) (uniq : ∀ (s : fork f g) (m : s.X ⟶ t.X) (w : ∀ j : walking_parallel_pair, m ≫ t.π.app j = s.π.app j), m = lift s) : is_limit t := { lift := lift, fac' := λ s j, walking_parallel_pair.cases_on j (fac s) $ by erw [←s.w left, ←t.w left, ←category.assoc, fac]; refl, uniq' := uniq } /-- This is another convenient method to verify that a fork is a limit cone. It only asks for a proof of facts that carry any mathematical content, and allows access to the same `s` for all parts. -/ def fork.is_limit.mk' {X Y : C} {f g : X ⟶ Y} (t : fork f g) (create : Π (s : fork f g), {l // l ≫ t.ι = s.ι ∧ ∀ {m}, m ≫ t.ι = s.ι → m = l}) : is_limit t := fork.is_limit.mk t (λ s, (create s).1) (λ s, (create s).2.1) (λ s m w, (create s).2.2 (w zero)) /-- This is a slightly more convenient method to verify that a cofork is a colimit cocone. It only asks for a proof of facts that carry any mathematical content -/ def cofork.is_colimit.mk (t : cofork f g) (desc : Π (s : cofork f g), t.X ⟶ s.X) (fac : ∀ (s : cofork f g), cofork.π t ≫ desc s = cofork.π s) (uniq : ∀ (s : cofork f g) (m : t.X ⟶ s.X) (w : ∀ j : walking_parallel_pair, t.ι.app j ≫ m = s.ι.app j), m = desc s) : is_colimit t := { desc := desc, fac' := λ s j, walking_parallel_pair.cases_on j (by erw [←s.w left, ←t.w left, category.assoc, fac]; refl) (fac s), uniq' := uniq } /-- This is another convenient method to verify that a fork is a limit cone. It only asks for a proof of facts that carry any mathematical content, and allows access to the same `s` for all parts. -/ def cofork.is_colimit.mk' {X Y : C} {f g : X ⟶ Y} (t : cofork f g) (create : Π (s : cofork f g), {l : t.X ⟶ s.X // t.π ≫ l = s.π ∧ ∀ {m}, t.π ≫ m = s.π → m = l}) : is_colimit t := cofork.is_colimit.mk t (λ s, (create s).1) (λ s, (create s).2.1) (λ s m w, (create s).2.2 (w one)) /-- Given a limit cone for the pair `f g : X ⟶ Y`, for any `Z`, morphisms from `Z` to its point are in bijection with morphisms `h : Z ⟶ X` such that `h ≫ f = h ≫ g`. Further, this bijection is natural in `Z`: see `fork.is_limit.hom_iso_natural`. This is a special case of `is_limit.hom_iso'`, often useful to construct adjunctions. -/ @[simps] def fork.is_limit.hom_iso {X Y : C} {f g : X ⟶ Y} {t : fork f g} (ht : is_limit t) (Z : C) : (Z ⟶ t.X) ≃ {h : Z ⟶ X // h ≫ f = h ≫ g} := { to_fun := λ k, ⟨k ≫ t.ι, by simp⟩, inv_fun := λ h, (fork.is_limit.lift' ht _ h.prop).1, left_inv := λ k, fork.is_limit.hom_ext ht (fork.is_limit.lift' _ _ _).prop, right_inv := λ h, subtype.ext (fork.is_limit.lift' ht _ _).prop } /-- The bijection of `fork.is_limit.hom_iso` is natural in `Z`. -/ lemma fork.is_limit.hom_iso_natural {X Y : C} {f g : X ⟶ Y} {t : fork f g} (ht : is_limit t) {Z Z' : C} (q : Z' ⟶ Z) (k : Z ⟶ t.X) : (fork.is_limit.hom_iso ht _ (q ≫ k) : Z' ⟶ X) = q ≫ (fork.is_limit.hom_iso ht _ k : Z ⟶ X) := category.assoc _ _ _ /-- Given a colimit cocone for the pair `f g : X ⟶ Y`, for any `Z`, morphisms from the cocone point to `Z` are in bijection with morphisms `h : Y ⟶ Z` such that `f ≫ h = g ≫ h`. Further, this bijection is natural in `Z`: see `cofork.is_colimit.hom_iso_natural`. This is a special case of `is_colimit.hom_iso'`, often useful to construct adjunctions. -/ @[simps] def cofork.is_colimit.hom_iso {X Y : C} {f g : X ⟶ Y} {t : cofork f g} (ht : is_colimit t) (Z : C) : (t.X ⟶ Z) ≃ {h : Y ⟶ Z // f ≫ h = g ≫ h} := { to_fun := λ k, ⟨t.π ≫ k, by simp⟩, inv_fun := λ h, (cofork.is_colimit.desc' ht _ h.prop).1, left_inv := λ k, cofork.is_colimit.hom_ext ht (cofork.is_colimit.desc' _ _ _).prop, right_inv := λ h, subtype.ext (cofork.is_colimit.desc' ht _ _).prop } /-- The bijection of `cofork.is_colimit.hom_iso` is natural in `Z`. -/ lemma cofork.is_colimit.hom_iso_natural {X Y : C} {f g : X ⟶ Y} {t : cofork f g} {Z Z' : C} (q : Z ⟶ Z') (ht : is_colimit t) (k : t.X ⟶ Z) : (cofork.is_colimit.hom_iso ht _ (k ≫ q) : Y ⟶ Z') = (cofork.is_colimit.hom_iso ht _ k : Y ⟶ Z) ≫ q := (category.assoc _ _ _).symm /-- This is a helper construction that can be useful when verifying that a category has all equalizers. Given `F : walking_parallel_pair ⥤ C`, which is really the same as `parallel_pair (F.map left) (F.map right)`, and a fork on `F.map left` and `F.map right`, we get a cone on `F`. If you're thinking about using this, have a look at `has_equalizers_of_has_limit_parallel_pair`, which you may find to be an easier way of achieving your goal. -/ def cone.of_fork {F : walking_parallel_pair ⥤ C} (t : fork (F.map left) (F.map right)) : cone F := { X := t.X, π := { app := λ X, t.π.app X ≫ eq_to_hom (by tidy), naturality' := λ j j' g, by { cases j; cases j'; cases g; dsimp; simp } } } /-- This is a helper construction that can be useful when verifying that a category has all coequalizers. Given `F : walking_parallel_pair ⥤ C`, which is really the same as `parallel_pair (F.map left) (F.map right)`, and a cofork on `F.map left` and `F.map right`, we get a cocone on `F`. If you're thinking about using this, have a look at `has_coequalizers_of_has_colimit_parallel_pair`, which you may find to be an easier way of achieving your goal. -/ def cocone.of_cofork {F : walking_parallel_pair ⥤ C} (t : cofork (F.map left) (F.map right)) : cocone F := { X := t.X, ι := { app := λ X, eq_to_hom (by tidy) ≫ t.ι.app X, naturality' := λ j j' g, by { cases j; cases j'; cases g; dsimp; simp } } } @[simp] lemma cone.of_fork_π {F : walking_parallel_pair ⥤ C} (t : fork (F.map left) (F.map right)) (j) : (cone.of_fork t).π.app j = t.π.app j ≫ eq_to_hom (by tidy) := rfl @[simp] lemma cocone.of_cofork_ι {F : walking_parallel_pair ⥤ C} (t : cofork (F.map left) (F.map right)) (j) : (cocone.of_cofork t).ι.app j = eq_to_hom (by tidy) ≫ t.ι.app j := rfl /-- Given `F : walking_parallel_pair ⥤ C`, which is really the same as `parallel_pair (F.map left) (F.map right)` and a cone on `F`, we get a fork on `F.map left` and `F.map right`. -/ def fork.of_cone {F : walking_parallel_pair ⥤ C} (t : cone F) : fork (F.map left) (F.map right) := { X := t.X, π := { app := λ X, t.π.app X ≫ eq_to_hom (by tidy) } } /-- Given `F : walking_parallel_pair ⥤ C`, which is really the same as `parallel_pair (F.map left) (F.map right)` and a cocone on `F`, we get a cofork on `F.map left` and `F.map right`. -/ def cofork.of_cocone {F : walking_parallel_pair ⥤ C} (t : cocone F) : cofork (F.map left) (F.map right) := { X := t.X, ι := { app := λ X, eq_to_hom (by tidy) ≫ t.ι.app X } } @[simp] lemma fork.of_cone_π {F : walking_parallel_pair ⥤ C} (t : cone F) (j) : (fork.of_cone t).π.app j = t.π.app j ≫ eq_to_hom (by tidy) := rfl @[simp] lemma cofork.of_cocone_ι {F : walking_parallel_pair ⥤ C} (t : cocone F) (j) : (cofork.of_cocone t).ι.app j = eq_to_hom (by tidy) ≫ t.ι.app j := rfl /-- Helper function for constructing morphisms between equalizer forks. -/ @[simps] def fork.mk_hom {s t : fork f g} (k : s.X ⟶ t.X) (w : k ≫ t.ι = s.ι) : s ⟶ t := { hom := k, w' := begin rintro ⟨_|_⟩, { exact w }, { simpa using w =≫ f }, end } /-- To construct an isomorphism between forks, it suffices to give an isomorphism between the cone points and check that it commutes with the `ι` morphisms. -/ @[simps] def fork.ext {s t : fork f g} (i : s.X ≅ t.X) (w : i.hom ≫ t.ι = s.ι) : s ≅ t := { hom := fork.mk_hom i.hom w, inv := fork.mk_hom i.inv (by rw [← w, iso.inv_hom_id_assoc]) } /-- Helper function for constructing morphisms between coequalizer coforks. -/ @[simps] def cofork.mk_hom {s t : cofork f g} (k : s.X ⟶ t.X) (w : s.π ≫ k = t.π) : s ⟶ t := { hom := k, w' := begin rintro ⟨_|_⟩, simpa using f ≫= w, exact w, end } /-- To construct an isomorphism between coforks, it suffices to give an isomorphism between the cocone points and check that it commutes with the `π` morphisms. -/ def cofork.ext {s t : cofork f g} (i : s.X ≅ t.X) (w : s.π ≫ i.hom = t.π) : s ≅ t := { hom := cofork.mk_hom i.hom w, inv := cofork.mk_hom i.inv (by rw [iso.comp_inv_eq, w]) } variables (f g) section /-- `has_equalizer f g` represents a particular choice of limiting cone for the parallel pair of morphisms `f` and `g`. -/ abbreviation has_equalizer := has_limit (parallel_pair f g) variables [has_equalizer f g] /-- If an equalizer of `f` and `g` exists, we can access an arbitrary choice of such by saying `equalizer f g`. -/ abbreviation equalizer : C := limit (parallel_pair f g) /-- If an equalizer of `f` and `g` exists, we can access the inclusion `equalizer f g ⟶ X` by saying `equalizer.ι f g`. -/ abbreviation equalizer.ι : equalizer f g ⟶ X := limit.π (parallel_pair f g) zero /-- An equalizer cone for a parallel pair `f` and `g`. -/ abbreviation equalizer.fork : fork f g := limit.cone (parallel_pair f g) @[simp] lemma equalizer.fork_ι : (equalizer.fork f g).ι = equalizer.ι f g := rfl @[simp] lemma equalizer.fork_π_app_zero : (equalizer.fork f g).π.app zero = equalizer.ι f g := rfl @[reassoc] lemma equalizer.condition : equalizer.ι f g ≫ f = equalizer.ι f g ≫ g := fork.condition $ limit.cone $ parallel_pair f g /-- The equalizer built from `equalizer.ι f g` is limiting. -/ def equalizer_is_equalizer : is_limit (fork.of_ι (equalizer.ι f g) (equalizer.condition f g)) := is_limit.of_iso_limit (limit.is_limit _) (fork.ext (iso.refl _) (by tidy)) variables {f g} /-- A morphism `k : W ⟶ X` satisfying `k ≫ f = k ≫ g` factors through the equalizer of `f` and `g` via `equalizer.lift : W ⟶ equalizer f g`. -/ abbreviation equalizer.lift {W : C} (k : W ⟶ X) (h : k ≫ f = k ≫ g) : W ⟶ equalizer f g := limit.lift (parallel_pair f g) (fork.of_ι k h) @[simp, reassoc] lemma equalizer.lift_ι {W : C} (k : W ⟶ X) (h : k ≫ f = k ≫ g) : equalizer.lift k h ≫ equalizer.ι f g = k := limit.lift_π _ _ /-- A morphism `k : W ⟶ X` satisfying `k ≫ f = k ≫ g` induces a morphism `l : W ⟶ equalizer f g` satisfying `l ≫ equalizer.ι f g = k`. -/ def equalizer.lift' {W : C} (k : W ⟶ X) (h : k ≫ f = k ≫ g) : {l : W ⟶ equalizer f g // l ≫ equalizer.ι f g = k} := ⟨equalizer.lift k h, equalizer.lift_ι _ _⟩ /-- Two maps into an equalizer are equal if they are are equal when composed with the equalizer map. -/ @[ext] lemma equalizer.hom_ext {W : C} {k l : W ⟶ equalizer f g} (h : k ≫ equalizer.ι f g = l ≫ equalizer.ι f g) : k = l := fork.is_limit.hom_ext (limit.is_limit _) h /-- An equalizer morphism is a monomorphism -/ instance equalizer.ι_mono : mono (equalizer.ι f g) := { right_cancellation := λ Z h k w, equalizer.hom_ext w } end section variables {f g} /-- The equalizer morphism in any limit cone is a monomorphism. -/ lemma mono_of_is_limit_parallel_pair {c : cone (parallel_pair f g)} (i : is_limit c) : mono (fork.ι c) := { right_cancellation := λ Z h k w, fork.is_limit.hom_ext i w } end section variables {f g} /-- The identity determines a cone on the equalizer diagram of `f` and `g` if `f = g`. -/ def id_fork (h : f = g) : fork f g := fork.of_ι (𝟙 X) $ h ▸ rfl /-- The identity on `X` is an equalizer of `(f, g)`, if `f = g`. -/ def is_limit_id_fork (h : f = g) : is_limit (id_fork h) := fork.is_limit.mk _ (λ s, fork.ι s) (λ s, category.comp_id _) (λ s m h, by { convert h zero, exact (category.comp_id _).symm }) /-- Every equalizer of `(f, g)`, where `f = g`, is an isomorphism. -/ def is_iso_limit_cone_parallel_pair_of_eq (h₀ : f = g) {c : cone (parallel_pair f g)} (h : is_limit c) : is_iso (c.π.app zero) := is_iso.of_iso $ is_limit.cone_point_unique_up_to_iso h $ is_limit_id_fork h₀ /-- The equalizer of `(f, g)`, where `f = g`, is an isomorphism. -/ def equalizer.ι_of_eq [has_equalizer f g] (h : f = g) : is_iso (equalizer.ι f g) := is_iso_limit_cone_parallel_pair_of_eq h $ limit.is_limit _ /-- Every equalizer of `(f, f)` is an isomorphism. -/ def is_iso_limit_cone_parallel_pair_of_self {c : cone (parallel_pair f f)} (h : is_limit c) : is_iso (c.π.app zero) := is_iso_limit_cone_parallel_pair_of_eq rfl h /-- An equalizer that is an epimorphism is an isomorphism. -/ def is_iso_limit_cone_parallel_pair_of_epi {c : cone (parallel_pair f g)} (h : is_limit c) [epi (c.π.app zero)] : is_iso (c.π.app zero) := is_iso_limit_cone_parallel_pair_of_eq ((cancel_epi _).1 (fork.condition c)) h end instance has_equalizer_of_self : has_equalizer f f := has_limit.mk { cone := id_fork rfl, is_limit := is_limit_id_fork rfl } /-- The equalizer inclusion for `(f, f)` is an isomorphism. -/ instance equalizer.ι_of_self : is_iso (equalizer.ι f f) := equalizer.ι_of_eq rfl /-- The equalizer of a morphism with itself is isomorphic to the source. -/ def equalizer.iso_source_of_self : equalizer f f ≅ X := as_iso (equalizer.ι f f) @[simp] lemma equalizer.iso_source_of_self_hom : (equalizer.iso_source_of_self f).hom = equalizer.ι f f := rfl @[simp] lemma equalizer.iso_source_of_self_inv : (equalizer.iso_source_of_self f).inv = equalizer.lift (𝟙 X) (by simp) := rfl section /-- `has_coequalizer f g` represents a particular choice of colimiting cocone for the parallel pair of morphisms `f` and `g`. -/ abbreviation has_coequalizer := has_colimit (parallel_pair f g) variables [has_coequalizer f g] /-- If a coequalizer of `f` and `g` exists, we can access an arbitrary choice of such by saying `coequalizer f g`. -/ abbreviation coequalizer : C := colimit (parallel_pair f g) /-- If a coequalizer of `f` and `g` exists, we can access the corresponding projection by saying `coequalizer.π f g`. -/ abbreviation coequalizer.π : Y ⟶ coequalizer f g := colimit.ι (parallel_pair f g) one /-- An arbitrary choice of coequalizer cocone for a parallel pair `f` and `g`. -/ abbreviation coequalizer.cofork : cofork f g := colimit.cocone (parallel_pair f g) @[simp] lemma coequalizer.cofork_π : (coequalizer.cofork f g).π = coequalizer.π f g := rfl @[simp] lemma coequalizer.cofork_ι_app_one : (coequalizer.cofork f g).ι.app one = coequalizer.π f g := rfl @[reassoc] lemma coequalizer.condition : f ≫ coequalizer.π f g = g ≫ coequalizer.π f g := cofork.condition $ colimit.cocone $ parallel_pair f g /-- The cofork built from `coequalizer.π f g` is colimiting. -/ def coequalizer_is_coequalizer : is_colimit (cofork.of_π (coequalizer.π f g) (coequalizer.condition f g)) := is_colimit.of_iso_colimit (colimit.is_colimit _) (cofork.ext (iso.refl _) (by tidy)) variables {f g} /-- Any morphism `k : Y ⟶ W` satisfying `f ≫ k = g ≫ k` factors through the coequalizer of `f` and `g` via `coequalizer.desc : coequalizer f g ⟶ W`. -/ abbreviation coequalizer.desc {W : C} (k : Y ⟶ W) (h : f ≫ k = g ≫ k) : coequalizer f g ⟶ W := colimit.desc (parallel_pair f g) (cofork.of_π k h) @[simp, reassoc] lemma coequalizer.π_desc {W : C} (k : Y ⟶ W) (h : f ≫ k = g ≫ k) : coequalizer.π f g ≫ coequalizer.desc k h = k := colimit.ι_desc _ _ /-- Any morphism `k : Y ⟶ W` satisfying `f ≫ k = g ≫ k` induces a morphism `l : coequalizer f g ⟶ W` satisfying `coequalizer.π ≫ g = l`. -/ def coequalizer.desc' {W : C} (k : Y ⟶ W) (h : f ≫ k = g ≫ k) : {l : coequalizer f g ⟶ W // coequalizer.π f g ≫ l = k} := ⟨coequalizer.desc k h, coequalizer.π_desc _ _⟩ /-- Two maps from a coequalizer are equal if they are equal when composed with the coequalizer map -/ @[ext] lemma coequalizer.hom_ext {W : C} {k l : coequalizer f g ⟶ W} (h : coequalizer.π f g ≫ k = coequalizer.π f g ≫ l) : k = l := cofork.is_colimit.hom_ext (colimit.is_colimit _) h /-- A coequalizer morphism is an epimorphism -/ instance coequalizer.π_epi : epi (coequalizer.π f g) := { left_cancellation := λ Z h k w, coequalizer.hom_ext w } end section variables {f g} /-- The coequalizer morphism in any colimit cocone is an epimorphism. -/ lemma epi_of_is_colimit_parallel_pair {c : cocone (parallel_pair f g)} (i : is_colimit c) : epi (c.ι.app one) := { left_cancellation := λ Z h k w, cofork.is_colimit.hom_ext i w } end section variables {f g} /-- The identity determines a cocone on the coequalizer diagram of `f` and `g`, if `f = g`. -/ def id_cofork (h : f = g) : cofork f g := cofork.of_π (𝟙 Y) $ h ▸ rfl /-- The identity on `Y` is a coequalizer of `(f, g)`, where `f = g`. -/ def is_colimit_id_cofork (h : f = g) : is_colimit (id_cofork h) := cofork.is_colimit.mk _ (λ s, cofork.π s) (λ s, category.id_comp _) (λ s m h, by { convert h one, exact (category.id_comp _).symm }) /-- Every coequalizer of `(f, g)`, where `f = g`, is an isomorphism. -/ def is_iso_colimit_cocone_parallel_pair_of_eq (h₀ : f = g) {c : cocone (parallel_pair f g)} (h : is_colimit c) : is_iso (c.ι.app one) := is_iso.of_iso $ is_colimit.cocone_point_unique_up_to_iso (is_colimit_id_cofork h₀) h /-- The coequalizer of `(f, g)`, where `f = g`, is an isomorphism. -/ def coequalizer.π_of_eq [has_coequalizer f g] (h : f = g) : is_iso (coequalizer.π f g) := is_iso_colimit_cocone_parallel_pair_of_eq h $ colimit.is_colimit _ /-- Every coequalizer of `(f, f)` is an isomorphism. -/ def is_iso_colimit_cocone_parallel_pair_of_self {c : cocone (parallel_pair f f)} (h : is_colimit c) : is_iso (c.ι.app one) := is_iso_colimit_cocone_parallel_pair_of_eq rfl h /-- A coequalizer that is a monomorphism is an isomorphism. -/ def is_iso_limit_cocone_parallel_pair_of_epi {c : cocone (parallel_pair f g)} (h : is_colimit c) [mono (c.ι.app one)] : is_iso (c.ι.app one) := is_iso_colimit_cocone_parallel_pair_of_eq ((cancel_mono _).1 (cofork.condition c)) h end instance has_coequalizer_of_self : has_coequalizer f f := has_colimit.mk { cocone := id_cofork rfl, is_colimit := is_colimit_id_cofork rfl } /-- The coequalizer projection for `(f, f)` is an isomorphism. -/ instance coequalizer.π_of_self : is_iso (coequalizer.π f f) := coequalizer.π_of_eq rfl /-- The coequalizer of a morphism with itself is isomorphic to the target. -/ def coequalizer.iso_target_of_self : coequalizer f f ≅ Y := (as_iso (coequalizer.π f f)).symm @[simp] lemma coequalizer.iso_target_of_self_hom : (coequalizer.iso_target_of_self f).hom = coequalizer.desc (𝟙 Y) (by simp) := rfl @[simp] lemma coequalizer.iso_target_of_self_inv : (coequalizer.iso_target_of_self f).inv = coequalizer.π f f := rfl section comparison variables {D : Type u₂} [category.{v} D] (G : C ⥤ D) /-- The comparison morphism for the equalizer of `f,g`. This is an isomorphism iff `G` preserves the equalizer of `f,g`; see `category_theory/limits/preserves/shapes/equalizers.lean` -/ def equalizer_comparison [has_equalizer f g] [has_equalizer (G.map f) (G.map g)] : G.obj (equalizer f g) ⟶ equalizer (G.map f) (G.map g) := equalizer.lift (G.map (equalizer.ι _ _)) (by simp only [←G.map_comp, equalizer.condition]) @[simp, reassoc] lemma equalizer_comparison_comp_π [has_equalizer f g] [has_equalizer (G.map f) (G.map g)] : equalizer_comparison f g G ≫ equalizer.ι (G.map f) (G.map g) = G.map (equalizer.ι f g) := equalizer.lift_ι _ _ @[simp, reassoc] lemma map_lift_equalizer_comparison [has_equalizer f g] [has_equalizer (G.map f) (G.map g)] {Z : C} {h : Z ⟶ X} (w : h ≫ f = h ≫ g) : G.map (equalizer.lift h w) ≫ equalizer_comparison f g G = equalizer.lift (G.map h) (by simp only [←G.map_comp, w]) := by { ext, simp [← G.map_comp] } /-- The comparison morphism for the coequalizer of `f,g`. -/ def coequalizer_comparison [has_coequalizer f g] [has_coequalizer (G.map f) (G.map g)] : coequalizer (G.map f) (G.map g) ⟶ G.obj (coequalizer f g) := coequalizer.desc (G.map (coequalizer.π _ _)) (by simp only [←G.map_comp, coequalizer.condition]) @[simp, reassoc] lemma ι_comp_coequalizer_comparison [has_coequalizer f g] [has_coequalizer (G.map f) (G.map g)] : coequalizer.π _ _ ≫ coequalizer_comparison f g G = G.map (coequalizer.π _ _) := coequalizer.π_desc _ _ @[simp, reassoc] lemma coequalizer_comparison_map_desc [has_coequalizer f g] [has_coequalizer (G.map f) (G.map g)] {Z : C} {h : Y ⟶ Z} (w : f ≫ h = g ≫ h) : coequalizer_comparison f g G ≫ G.map (coequalizer.desc h w) = coequalizer.desc (G.map h) (by simp only [←G.map_comp, w]) := by { ext, simp [← G.map_comp] } end comparison variables (C) /-- `has_equalizers` represents a choice of equalizer for every pair of morphisms -/ abbreviation has_equalizers := has_limits_of_shape walking_parallel_pair C /-- `has_coequalizers` represents a choice of coequalizer for every pair of morphisms -/ abbreviation has_coequalizers := has_colimits_of_shape walking_parallel_pair C /-- If `C` has all limits of diagrams `parallel_pair f g`, then it has all equalizers -/ lemma has_equalizers_of_has_limit_parallel_pair [Π {X Y : C} {f g : X ⟶ Y}, has_limit (parallel_pair f g)] : has_equalizers C := { has_limit := λ F, has_limit_of_iso (diagram_iso_parallel_pair F).symm } /-- If `C` has all colimits of diagrams `parallel_pair f g`, then it has all coequalizers -/ lemma has_coequalizers_of_has_colimit_parallel_pair [Π {X Y : C} {f g : X ⟶ Y}, has_colimit (parallel_pair f g)] : has_coequalizers C := { has_colimit := λ F, has_colimit_of_iso (diagram_iso_parallel_pair F) } section -- In this section we show that a split mono `f` equalizes `(retraction f ≫ f)` and `(𝟙 Y)`. variables {C} [split_mono f] /-- A split mono `f` equalizes `(retraction f ≫ f)` and `(𝟙 Y)`. Here we build the cone, and show in `split_mono_equalizes` that it is a limit cone. -/ @[simps {rhs_md := semireducible}] def cone_of_split_mono : cone (parallel_pair (𝟙 Y) (retraction f ≫ f)) := fork.of_ι f (by simp) /-- A split mono `f` equalizes `(retraction f ≫ f)` and `(𝟙 Y)`. -/ def split_mono_equalizes {X Y : C} (f : X ⟶ Y) [split_mono f] : is_limit (cone_of_split_mono f) := fork.is_limit.mk' _ $ λ s, ⟨s.ι ≫ retraction f, by { dsimp, rw [category.assoc, ←s.condition], apply category.comp_id }, λ m hm, by simp [←hm]⟩ end section -- In this section we show that a split epi `f` coequalizes `(f ≫ section_ f)` and `(𝟙 X)`. variables {C} [split_epi f] /-- A split epi `f` coequalizes `(f ≫ section_ f)` and `(𝟙 X)`. Here we build the cocone, and show in `split_epi_coequalizes` that it is a colimit cocone. -/ @[simps {rhs_md := semireducible}] def cocone_of_split_epi : cocone (parallel_pair (𝟙 X) (f ≫ section_ f)) := cofork.of_π f (by simp) /-- A split epi `f` coequalizes `(f ≫ section_ f)` and `(𝟙 X)`. -/ def split_epi_coequalizes {X Y : C} (f : X ⟶ Y) [split_epi f] : is_colimit (cocone_of_split_epi f) := cofork.is_colimit.mk' _ $ λ s, ⟨section_ f ≫ s.π, by { dsimp, rw [← category.assoc, ← s.condition, category.id_comp] }, λ m hm, by simp [← hm]⟩ end end category_theory.limits
73de7dc441ca47821df2a3447cbc6f42f98bd2ac
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/algebra/category/Module/change_of_rings.lean
fc8d97972b2a55538a9ecb857b28c7414ceef941
[ "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
2,442
lean
/- Copyright (c) 2022 Jujian Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jujian Zhang -/ import algebra.category.Module.basic /-! # Change Of Rings ## Main definitions * `category_theory.Module.restrict_scalars`: given rings `R, S` and a ring homomorphism `R ⟶ S`, then `restrict_scalars : Module S ⥤ Module R` is defined by `M ↦ M` where `M : S-module` is seen as `R-module` by `r • m := f r • m` and `S`-linear map `l : M ⟶ M'` is `R`-linear as well. -/ namespace category_theory.Module universes v u₁ u₂ namespace restrict_scalars variables {R : Type u₁} {S : Type u₂} [ring R] [ring S] (f : R →+* S) variable (M : Module.{v} S) /-- Any `S`-module M is also an `R`-module via a ring homomorphism `f : R ⟶ S` by defining `r • m := f r • m` (`module.comp_hom`). This is called restriction of scalars. -/ def obj' : Module R := { carrier := M, is_module := module.comp_hom M f } /-- Given an `S`-linear map `g : M → M'` between `S`-modules, `g` is also `R`-linear between `M` and `M'` by means of restriction of scalars. -/ def map' {M M' : Module.{v} S} (g : M ⟶ M') : obj' f M ⟶ obj' f M' := { map_smul' := λ r, g.map_smul (f r), ..g } end restrict_scalars /-- The restriction of scalars operation is functorial. For any `f : R →+* S` a ring homomorphism, * an `S`-module `M` can be considered as `R`-module by `r • m = f r • m` * an `S`-linear map is also `R`-linear -/ def restrict_scalars {R : Type u₁} {S : Type u₂} [ring R] [ring S] (f : R →+* S) : Module.{v} S ⥤ Module.{v} R := { obj := restrict_scalars.obj' f, map := λ _ _, restrict_scalars.map' f, map_id' := λ _, linear_map.ext $ λ m, rfl, map_comp' := λ _ _ _ g h, linear_map.ext $ λ m, rfl } @[simp] lemma restrict_scalars.map_apply {R : Type u₁} {S : Type u₂} [ring R] [ring S] (f : R →+* S) {M M' : Module.{v} S} (g : M ⟶ M') (x) : (restrict_scalars f).map g x = g x := rfl @[simp] lemma restrict_scalars.smul_def {R : Type u₁} {S : Type u₂} [ring R] [ring S] (f : R →+* S) {M : Module.{v} S} (r : R) (m : (restrict_scalars f).obj M) : r • m = (f r • m : M) := rfl @[simp] lemma restrict_scalars.smul_def' {R : Type u₁} {S : Type u₂} [ring R] [ring S] (f : R →+* S) {M : Module.{v} S} (r : R) (m : M) : (r • m : (restrict_scalars f).obj M) = (f r • m : M) := rfl end category_theory.Module
a3836a158d9af8b80bd3817a771417b922a29fb9
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/04_Quantifiers_and_Equality.org.4.lean
c4e4eb1fbe5f8ee688d7635f2f0deb13dd5c97df
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
251
lean
/- page 49 -/ import standard variables (A : Type) (r : A → A → Prop) variable (trans_r : ∀ {x y z}, r x y → r y z → r x z) variables (a b c : A) variables (Hab : r a b) (Hbc : r b c) check trans_r check trans_r Hab check trans_r Hab Hbc
39d13b5d8f6c751174fbddd18ba16c33f06db1ed
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/tactic/aesop/rule_builder.lean
101df0d4a7e97317b7aa78bf9be4215546de0d73
[ "Apache-2.0" ]
permissive
JLimperg/aesop3
306cc6570c556568897ed2e508c8869667252e8a
a4a116f650cc7403428e72bd2e2c4cda300fe03f
refs/heads/master
1,682,884,916,368
1,620,320,033,000
1,620,320,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,043
lean
/- Copyright (c) 2021 Jannis Limperg. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jannis Limperg -/ import tactic.aesop.rule namespace tactic namespace aesop meta inductive rule_builder_output | rule (r : rule) (imode : indexing_mode) | simp_lemmas (s : simp_lemmas) meta def rule_builder := declaration → tactic rule_builder_output namespace rule_builder meta def tac : rule_builder := λ d, match d.type with | `(tactic unit) := do t ← eval_expr (tactic unit) d.value, pure $ rule_builder_output.rule { tac := t, description := to_fmt d.to_name } indexing_mode.unindexed | _ := fail! "Expected {d.to_name} to have type `tactic unit`." end meta def apply_indexing_mode (type : expr) : tactic indexing_mode := do head_constant ← type.conclusion_head_constant, pure $ match head_constant with | some c := index_target_head c | none := unindexed end meta def apply : rule_builder := λ d, do imode ← apply_indexing_mode d.type, let n := d.to_name, pure $ rule_builder_output.rule { tac := mk_const n >>= tactic.apply >> skip, description := format! "apply {n}"} imode meta def normalization_simp_lemma : rule_builder := λ d, do let n := d.to_name, s ← simp_lemmas.mk.add_simp n <|> fail! "Expected {n} to be a (conditional) equation that can be used as a simp lemma.", pure $ rule_builder_output.simp_lemmas s meta def no_tactic (d : declaration) : tactic unit := match d.type with | `(tactic _) := fail! "To register a tactic as an Aesop rule, it must have type `tactic unit`, but {d.to_name} has type `{d.type}`." | _ := pure () end meta def normalization_default : rule_builder := λ d, tac d <|> normalization_simp_lemma d <|> fail! "Expected {d.to_name} to have type `tactic unit` or to be suitable as a simp lemma." meta def safe_default : rule_builder := λ d, tac d <|> (no_tactic d >> apply d) meta def unsafe_default : rule_builder := safe_default end rule_builder end aesop end tactic
db8936c06ea1df023a97102f44480b17e2bb8eb4
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/int/nat_prime_auto.lean
0ec4dd83515ef1f85135cf20783c4f07902bf83f
[]
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
611
lean
/- Copyright (c) 2020 Bryan Gin-ge Chen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Lacker, Bryan Gin-ge Chen -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.nat.prime import Mathlib.data.int.basic import Mathlib.PostPort namespace Mathlib /-! # Lemmas about nat.prime using `int`s -/ namespace int theorem not_prime_of_int_mul {a : ℤ} {b : ℤ} {c : ℕ} (ha : 1 < nat_abs a) (hb : 1 < nat_abs b) (hc : a * b = ↑c) : ¬nat.prime c := nat.not_prime_mul' (nat_abs_mul_nat_abs_eq hc) ha hb end Mathlib
b0797f91ea7e7252281873fc233ab96066ec4957
92b50235facfbc08dfe7f334827d47281471333b
/library/data/finset/partition.lean
cf74cc562bf25a24249c07baf8b170e9b8154ea7
[ "Apache-2.0" ]
permissive
htzh/lean
24f6ed7510ab637379ec31af406d12584d31792c
d70c79f4e30aafecdfc4a60b5d3512199200ab6e
refs/heads/master
1,607,677,731,270
1,437,089,952,000
1,437,089,952,000
37,078,816
0
0
null
1,433,780,956,000
1,433,780,955,000
null
UTF-8
Lean
false
false
5,764
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Haitao Zhang Partitions of a type A into finite subsets of A. Such a partition is represented by a function f : A → finset A which maps every element a : A to its equivalence class. -/ import .card open function eq.ops variable {A : Type} variable [deceqA : decidable_eq A] include deceqA namespace finset definition is_partition (f : A → finset A) := ∀ a b, a ∈ f b = (f a = f b) structure partition : Type := (set : finset A) (part : A → finset A) (is_part : is_partition part) (complete : set = Union set part) attribute partition.part [coercion] namespace partition definition equiv_classes (f : partition) : finset (finset A) := image (partition.part f) (partition.set f) lemma equiv_class_disjoint (f : partition) (a1 a2 : finset A) (Pa1 : a1 ∈ equiv_classes f) (Pa2 : a2 ∈ equiv_classes f) : a1 ≠ a2 → a1 ∩ a2 = ∅ := assume Pne, assert Pe1 : _, from exists_of_mem_image Pa1, obtain g1 Pg1, from Pe1, assert Pe2 : _, from exists_of_mem_image Pa2, obtain g2 Pg2, from Pe2, begin apply inter_eq_empty_of_disjoint, apply disjoint.intro, rewrite [eq.symm (and.right Pg1), eq.symm (and.right Pg2)], intro x, rewrite [*partition.is_part f], intro Pxg1, rewrite [Pxg1, and.right Pg1, and.right Pg2], intro Pe, exact absurd Pe Pne end theorem class_equation (f : @partition A _) : card (partition.set f) = nat.Sum (equiv_classes f) card := let s := (partition.set f), p := (partition.part f), img := image p s in calc card s = card (Union s p) : partition.complete f ... = card (Union img id) : image_eq_Union_index_image s p ... = card (Union (equiv_classes f) id) : rfl ... = nat.Sum (equiv_classes f) card : card_Union_of_disjoint _ id (equiv_class_disjoint f) lemma equiv_class_refl {f : A → finset A} (Pequiv : is_partition f) : ∀ a, a ∈ f a := take a, by rewrite [Pequiv a a] -- make it a little easier to prove union from restriction lemma restriction_imp_union {s : finset A} (f : A → finset A) (Pequiv : is_partition f) (Psub : ∀{a}, a ∈ s → f a ⊆ s) : s = Union s f := ext (take a, iff.intro (assume Pains, begin rewrite [(Union_insert_of_mem f Pains)⁻¹, Union_insert], apply mem_union_l, exact equiv_class_refl Pequiv a end) (assume Painu, have Pclass : ∃ x, x ∈ s ∧ a ∈ f x, from iff.elim_left (mem_Union_iff s f _) Painu, obtain x Px, from Pclass, have Pfx : f x ⊆ s, from Psub (and.left Px), mem_of_subset_of_mem Pfx (and.right Px))) lemma binary_union (P : A → Prop) [decP : decidable_pred P] {S : finset A} : S = {a ∈ S | P a} ∪ {a ∈ S | ¬(P a)} := ext take a, iff.intro (assume Pin, decidable.by_cases (λ Pa : P a, mem_union_l (mem_filter_of_mem Pin Pa)) (λ nPa, mem_union_r (mem_filter_of_mem Pin nPa))) (assume Pinu, or.elim (mem_or_mem_of_mem_union Pinu) (assume Pin, mem_of_mem_filter Pin) (assume Pin, mem_of_mem_filter Pin)) lemma binary_inter_empty {P : A → Prop} [decP : decidable_pred P] {S : finset A} : {a ∈ S | P a} ∩ {a ∈ S | ¬(P a)} = ∅ := inter_eq_empty (take a, assume Pa nPa, absurd (of_mem_filter Pa) (of_mem_filter nPa)) definition disjoint_sets (S : finset (finset A)) : Prop := ∀ s₁ s₂ (P₁ : s₁ ∈ S) (P₂ : s₂ ∈ S), s₁ ≠ s₂ → s₁ ∩ s₂ = ∅ lemma disjoint_sets_filter_of_disjoint_sets {P : finset A → Prop} [decP : decidable_pred P] {S : finset (finset A)} : disjoint_sets S → disjoint_sets {s ∈ S | P s} := assume Pds, take s₁ s₂, assume P₁ P₂, Pds s₁ s₂ (mem_of_mem_filter P₁) (mem_of_mem_filter P₂) lemma binary_inter_empty_Union_disjoint_sets {P : finset A → Prop} [decP : decidable_pred P] {S : finset (finset A)} : disjoint_sets S → Union {s ∈ S | P s} id ∩ Union {s ∈ S | ¬P s} id = ∅ := assume Pds, inter_eq_empty (take a, assume Pa nPa, obtain s Psin Pains, from iff.elim_left !mem_Union_iff Pa, obtain t Ptin Paint, from iff.elim_left !mem_Union_iff nPa, assert Pneq : s ≠ t, from assume Peq, absurd (Peq ▸ of_mem_filter Psin) (of_mem_filter Ptin), Pds s t (mem_of_mem_filter Psin) (mem_of_mem_filter Ptin) Pneq ▸ mem_inter Pains Paint) section variables {B: Type} [deceqB : decidable_eq B] include deceqB lemma binary_Union (f : A → finset B) {P : A → Prop} [decP : decidable_pred P] {s : finset A} : Union s f = Union {a ∈ s | P a} f ∪ Union {a ∈ s | ¬P a} f := begin rewrite [binary_union P at {1}], apply Union_union, exact binary_inter_empty end end open nat section open algebra variables {B : Type} [acmB : add_comm_monoid B] include acmB lemma Sum_binary_union (f : A → B) (P : A → Prop) [decP : decidable_pred P] {S : finset A} : Sum S f = Sum {s ∈ S | P s} f + Sum {s ∈ S | ¬P s} f := calc Sum S f = Sum ({s ∈ S | P s} ∪ {s ∈ S | ¬(P s)}) f : binary_union ... = Sum {s ∈ S | P s} f + Sum {s ∈ S | ¬P s} f : Sum_union f binary_inter_empty end lemma card_binary_Union_disjoint_sets (P : finset A → Prop) [decP : decidable_pred P] {S : finset (finset A)} : disjoint_sets S → card (Union S id) = Sum {s ∈ S | P s} card + Sum {s ∈ S | ¬P s} card := assume Pds, calc card (Union S id) = card (Union {s ∈ S | P s} id ∪ Union {s ∈ S | ¬P s} id) : binary_Union ... = card (Union {s ∈ S | P s} id) + card (Union {s ∈ S | ¬P s} id) : card_union_of_disjoint (binary_inter_empty_Union_disjoint_sets Pds) ... = Sum {s ∈ S | P s} card + Sum {s ∈ S | ¬P s} card : by rewrite [*(card_Union_of_disjoint _ id (disjoint_sets_filter_of_disjoint_sets Pds))] end partition end finset
ae5f7931d4a3c278f5c63c021fe54b9094de09e3
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Lean/Meta/Tactic/Replace.lean
9e31d74f90732874b53cafa8734c943dea044f9a
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach" ]
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
5,906
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Util.ForEachExpr import Lean.Meta.AppBuilder import Lean.Meta.MatchUtil import Lean.Meta.Tactic.Util import Lean.Meta.Tactic.Revert import Lean.Meta.Tactic.Intro import Lean.Meta.Tactic.Clear import Lean.Meta.Tactic.Assert namespace Lean.Meta /-- Convert the given goal `Ctx |- target` into `Ctx |- targetNew` using an equality proof `eqProof : target = targetNew`. It assumes `eqProof` has type `target = targetNew` -/ def replaceTargetEq (mvarId : MVarId) (targetNew : Expr) (eqProof : Expr) : MetaM MVarId := withMVarContext mvarId do checkNotAssigned mvarId `replaceTarget let tag ← getMVarTag mvarId let mvarNew ← mkFreshExprSyntheticOpaqueMVar targetNew tag let target ← getMVarType mvarId let u ← getLevel target let eq ← mkEq target targetNew let newProof ← mkExpectedTypeHint eqProof eq let val := mkAppN (Lean.mkConst `Eq.mpr [u]) #[target, targetNew, eqProof, mvarNew] assignExprMVar mvarId val return mvarNew.mvarId! /-- Convert the given goal `Ctx | target` into `Ctx |- targetNew`. It assumes the goals are definitionally equal. We use the proof term ``` @id target mvarNew ``` to create a checkpoint. -/ def replaceTargetDefEq (mvarId : MVarId) (targetNew : Expr) : MetaM MVarId := withMVarContext mvarId do checkNotAssigned mvarId `change let target ← getMVarType mvarId if target == targetNew then return mvarId else let tag ← getMVarTag mvarId let mvarNew ← mkFreshExprSyntheticOpaqueMVar targetNew tag let newVal ← mkExpectedTypeHint mvarNew target assignExprMVar mvarId mvarNew return mvarNew.mvarId! /-- Replace type of the local declaration with id `fvarId` with one with the same user-facing name, but with type `typeNew`. This method assumes `eqProof` is a proof that type of `fvarId` is equal to `typeNew`. This tactic actually adds a new declaration and (try to) clear the old one. If the old one cannot be cleared, then at least its user-facing name becomes inaccessible. Remark: the new declaration is added immediately after `fvarId`. `typeNew` must be well-formed at `fvarId`, but `eqProof` may contain variables declared after `fvarId`. -/ def replaceLocalDecl (mvarId : MVarId) (fvarId : FVarId) (typeNew : Expr) (eqProof : Expr) : MetaM AssertAfterResult := withMVarContext mvarId do let localDecl ← getLocalDecl fvarId let typeNewPr ← mkEqMP eqProof (mkFVar fvarId) -- `typeNew` may contain variables that occur after `fvarId`. -- Thus, we use the auxiliary function `findMaxFVar` to ensure `typeNew` is well-formed at the position we are inserting it. let (_, localDecl') ← findMaxFVar typeNew |>.run localDecl let result ← assertAfter mvarId localDecl'.fvarId localDecl.userName typeNew typeNewPr (do let mvarIdNew ← clear result.mvarId fvarId pure { result with mvarId := mvarIdNew }) <|> pure result where findMaxFVar (e : Expr) : StateRefT LocalDecl MetaM Unit := e.forEach' fun e => do if e.isFVar then let localDecl' ← getLocalDecl e.fvarId! modify fun localDecl => if localDecl'.index > localDecl.index then localDecl' else localDecl return false else return e.hasFVar def replaceLocalDeclDefEq (mvarId : MVarId) (fvarId : FVarId) (typeNew : Expr) : MetaM MVarId := do withMVarContext mvarId do let mvarDecl ← getMVarDecl mvarId if typeNew == mvarDecl.type then return mvarId else let lctxNew := (← getLCtx).modifyLocalDecl fvarId (·.setType typeNew) let mvarNew ← mkFreshExprMVarAt lctxNew (← getLocalInstances) mvarDecl.type mvarDecl.kind mvarDecl.userName assignExprMVar mvarId mvarNew return mvarNew.mvarId! def change (mvarId : MVarId) (targetNew : Expr) (checkDefEq := true) : MetaM MVarId := withMVarContext mvarId do let target ← getMVarType mvarId if checkDefEq then unless (← isDefEq target targetNew) do throwTacticEx `change mvarId m!"given type{indentExpr targetNew}\nis not definitionally equal to{indentExpr target}" replaceTargetDefEq mvarId targetNew def changeLocalDecl (mvarId : MVarId) (fvarId : FVarId) (typeNew : Expr) (checkDefEq := true) : MetaM MVarId := do checkNotAssigned mvarId `changeLocalDecl let (xs, mvarId) ← revert mvarId #[fvarId] true withMVarContext mvarId do let numReverted := xs.size let target ← getMVarType mvarId let check (typeOld : Expr) : MetaM Unit := do if checkDefEq then unless (← isDefEq typeNew typeOld) do throwTacticEx `changeHypothesis mvarId m!"given type{indentExpr typeNew}\nis not definitionally equal to{indentExpr typeOld}" let finalize (targetNew : Expr) : MetaM MVarId := do let mvarId ← replaceTargetDefEq mvarId targetNew let (_, mvarId) ← introNP mvarId numReverted pure mvarId match target with | Expr.forallE n d b c => do check d; finalize (mkForall n c.binderInfo typeNew b) | Expr.letE n t v b _ => do check t; finalize (mkLet n typeNew v b) | _ => throwTacticEx `changeHypothesis mvarId "unexpected auxiliary target" def modifyTarget (mvarId : MVarId) (f : Expr → MetaM Expr) : MetaM MVarId := do withMVarContext mvarId do checkNotAssigned mvarId `modifyTarget change mvarId (← f (← getMVarType mvarId)) (checkDefEq := false) def modifyTargetEqLHS (mvarId : MVarId) (f : Expr → MetaM Expr) : MetaM MVarId := do modifyTarget mvarId fun target => do if let some (_, lhs, rhs) ← matchEq? target then mkEq (← f lhs) rhs else throwTacticEx `modifyTargetEqLHS mvarId m!"equality expected{indentExpr target}" end Lean.Meta
4dba2f3a34d06bf1b7434e40dcfb19a18456abbf
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/inductionErrors.lean
9bc246952fb7a8c47834b84bc24923e10972e8ea
[ "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,481
lean
universe u axiom elimEx (motive : Nat → Nat → Sort u) (x y : Nat) (diag : (a : Nat) → motive a a) (upper : (delta a : Nat) → motive a (a + delta.succ)) (lower : (delta a : Nat) → motive (a + delta.succ) a) : motive y x theorem ex1 (p q : Nat) : p ≤ q ∨ p > q := by cases p, q using elimEx with | lower d => apply Or.inl -- Error | upper d => apply Or.inr -- Error | diag => apply Or.inl; apply Nat.le_refl theorem ex2 (p q : Nat) : p ≤ q ∨ p > q := by cases p, q using elimEx2 with -- Error | lower d => apply Or.inl | upper d => apply Or.inr | diag => apply Or.inl; apply Nat.le_refl theorem ex3 (p q : Nat) : p ≤ q ∨ p > q := by cases p /- Error -/ using elimEx with | lower d => apply Or.inl | upper d => apply Or.inr | diag => apply Or.inl; apply Nat.leRefl theorem ex4 (p q : Nat) : p ≤ q ∨ p > q := by cases p using Nat.add with -- Error | lower d => apply Or.inl | upper d => apply Or.inr | diag => apply Or.inl; apply Nat.le_refl theorem ex5 (x : Nat) : 0 + x = x := by match x with | 0 => done -- Error | y+1 => done -- Error theorem ex5b (x : Nat) : 0 + x = x := by cases x with | zero => done -- Error | succ y => done -- Error inductive Vec : Nat → Type | nil : Vec 0 | cons : Bool → {n : Nat} → Vec n → Vec (n+1) theorem ex6 (x : Vec 0) : x = Vec.nil := by cases x using Vec.casesOn with | nil => rfl | cons => done -- Error theorem ex7 (x : Vec 0) : x = Vec.nil := by cases x with -- Error: TODO: improve error location | nil => rfl | cons => done theorem ex8 (p q : Nat) : p ≤ q ∨ p > q := by cases p, q using elimEx with | lower d => apply Or.inl; admit | upper2 /- Error -/ d => apply Or.inr | diag => apply Or.inl; apply Nat.le_refl theorem ex9 (p q : Nat) : p ≤ q ∨ p > q := by cases p, q using elimEx with | lower d => apply Or.inl; admit | _ => apply Or.inr; admit | diag => apply Or.inl; apply Nat.le_refl theorem ex10 (p q : Nat) : p ≤ q ∨ p > q := by cases p, q using elimEx with | lower d => apply Or.inl; admit | upper d => apply Or.inr; admit | diag => apply Or.inl; apply Nat.le_refl | _ /- error unused -/ => admit theorem ex11 (p q : Nat) : p ≤ q ∨ p > q := by cases p, q using elimEx with | lower d => apply Or.inl; admit | upper d => apply Or.inr; admit | lower d /- error unused -/ => apply Or.inl; admit | diag => apply Or.inl; apply Nat.le_refl
825859661a0ab9fa08d466a92c8215979edd24c6
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/group_theory/sylow.lean
6340dc72ae90c9aaf42f58c2e9271797a1ba937f
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
13,268
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import group_theory.group_action import group_theory.quotient_group import group_theory.order_of_element import data.zmod.basic import data.fintype.card import data.list.rotate /-! # Sylow theorems The Sylow theorems are the following results for every finite group `G` and every prime number `p`. * There exists a Sylow `p`-subgroup of `G`. * All Sylow `p`-subgroups of `G` are conjugate to each other. * Let `nₚ` be the number of Sylow `p`-subgroups of `G`, then `nₚ` divides the index of the Sylow `p`-subgroup, `nₚ ≡ 1 [MOD p]`, and `nₚ` is equal to the index of the normalizer of the Sylow `p`-subgroup in `G`. In this file, currently only the first of these results is proven. ## Main statements * `exists_prime_order_of_dvd_card`: For every prime `p` dividing the order of `G` there exists an element of order `p` in `G`. This is known as Cauchy`s theorem. * `exists_subgroup_card_pow_prime`: A generalisation of the first of the Sylow theorems: For every prime power `pⁿ` dividing `G`, there exists a subgroup of `G` of order `pⁿ`. ## TODO * Prove the second and third of the Sylow theorems. * Sylow theorems for infinite groups -/ open equiv fintype finset mul_action function open equiv.perm subgroup list quotient_group open_locale big_operators universes u v w variables {G : Type u} {α : Type v} {β : Type w} [group G] local attribute [instance, priority 10] subtype.fintype set_fintype classical.prop_decidable namespace mul_action variables [mul_action G α] lemma mem_fixed_points_iff_card_orbit_eq_one {a : α} [fintype (orbit G a)] : a ∈ fixed_points G α ↔ card (orbit G a) = 1 := begin rw [fintype.card_eq_one_iff, mem_fixed_points], split, { exact λ h, ⟨⟨a, mem_orbit_self _⟩, λ ⟨b, ⟨x, hx⟩⟩, subtype.eq $ by simp [h x, hx.symm]⟩ }, { assume h x, rcases h with ⟨⟨z, hz⟩, hz₁⟩, exact calc x • a = z : subtype.mk.inj (hz₁ ⟨x • a, mem_orbit _ _⟩) ... = a : (subtype.mk.inj (hz₁ ⟨a, mem_orbit_self _⟩)).symm } end lemma card_modeq_card_fixed_points [fintype α] [fintype G] [fintype (fixed_points G α)] (p : ℕ) {n : ℕ} [hp : fact p.prime] (h : card G = p ^ n) : card α ≡ card (fixed_points G α) [MOD p] := calc card α = card (Σ y : quotient (orbit_rel G α), {x // quotient.mk' x = y}) : card_congr (sigma_preimage_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] : begin rw [← zmod.eq_iff_modeq_nat p, sum_nat_cast, sum_nat_cast], refine eq.symm (sum_bij_ne_zero (λ a _ _, quotient.mk' a.1) (λ _ _ _, mem_univ _) (λ a₁ a₂ _ _ _ _ h, subtype.eq ((mem_fixed_points' α).1 a₂.2 a₁.1 (quotient.exact' h))) (λ b, _) (λ a ha _, by rw [← mem_fixed_points_iff_card_orbit_eq_one.1 a.2]; simp only [quotient.eq']; congr)), { refine quotient.induction_on' b (λ b _ hb, _), have : card (orbit G b) ∣ p ^ n, { rw [← h, fintype.card_congr (orbit_equiv_quotient_stabilizer G b)], exact card_quotient_dvd_card _ }, rcases (nat.dvd_prime_pow hp.1).1 this with ⟨k, _, hk⟩, have hb' :¬ p ^ 1 ∣ p ^ k, { rw [pow_one, ← hk, ← nat.modeq.modeq_zero_iff, ← zmod.eq_iff_modeq_nat, nat.cast_zero, ← ne.def], exact eq.mpr (by simp only [quotient.eq']; congr) hb }, have : k = 0 := nat.le_zero_iff.1 (nat.le_of_lt_succ (lt_of_not_ge (mt (pow_dvd_pow p) hb'))), refine ⟨⟨b, mem_fixed_points_iff_card_orbit_eq_one.2 $ by rw [hk, this, pow_zero]⟩, mem_univ _, _, rfl⟩, rw [nat.cast_one], exact one_ne_zero } end ... = _ : by simp; refl end mul_action lemma quotient_group.card_preimage_mk [fintype G] (s : subgroup G) (t : set (quotient s)) : fintype.card (quotient_group.mk ⁻¹' t) = fintype.card s * fintype.card t := by rw [← fintype.card_prod, fintype.card_congr (preimage_mk_equiv_subgroup_times_set _ _)] namespace sylow /-- Given a vector `v` of length `n`, make a vector of length `n+1` whose product is `1`, by consing the the inverse of the product of `v`. -/ def mk_vector_prod_eq_one (n : ℕ) (v : vector G n) : vector G (n+1) := v.to_list.prod⁻¹ ::ᵥ v lemma mk_vector_prod_eq_one_injective (n : ℕ) : injective (@mk_vector_prod_eq_one G _ n) := λ ⟨v, _⟩ ⟨w, _⟩ h, subtype.eq (show v = w, by injection h with h; injection h) /-- The type of vectors with terms from `G`, length `n`, and product equal to `1:G`. -/ def vectors_prod_eq_one (G : Type*) [group G] (n : ℕ) : set (vector G n) := {v | v.to_list.prod = 1} lemma mem_vectors_prod_eq_one {n : ℕ} (v : vector G n) : v ∈ vectors_prod_eq_one G n ↔ v.to_list.prod = 1 := iff.rfl lemma mem_vectors_prod_eq_one_iff {n : ℕ} (v : vector G (n + 1)) : v ∈ vectors_prod_eq_one G (n + 1) ↔ v ∈ set.range (@mk_vector_prod_eq_one G _ n) := ⟨λ (h : v.to_list.prod = 1), ⟨v.tail, begin unfold mk_vector_prod_eq_one, conv {to_rhs, rw ← vector.cons_head_tail v}, suffices : (v.tail.to_list.prod)⁻¹ = v.head, { rw this }, rw [← mul_left_inj v.tail.to_list.prod, inv_mul_self, ← list.prod_cons, ← vector.to_list_cons, vector.cons_head_tail, h] end⟩, λ ⟨w, hw⟩, by rw [mem_vectors_prod_eq_one, ← hw, mk_vector_prod_eq_one, vector.to_list_cons, list.prod_cons, inv_mul_self]⟩ /-- The rotation action of `zmod n` (viewed as multiplicative group) on `vectors_prod_eq_one G n`, where `G` is a multiplicative group. -/ def rotate_vectors_prod_eq_one (G : Type*) [group G] (n : ℕ) (m : multiplicative (zmod n)) (v : vectors_prod_eq_one G n) : vectors_prod_eq_one G n := ⟨⟨v.1.to_list.rotate m.val, by simp⟩, prod_rotate_eq_one_of_prod_eq_one v.2 _⟩ instance rotate_vectors_prod_eq_one.mul_action (n : ℕ) [fact (0 < n)] : mul_action (multiplicative (zmod n)) (vectors_prod_eq_one G n) := { smul := (rotate_vectors_prod_eq_one G n), one_smul := begin intro v, apply subtype.eq, apply vector.eq _ _, show rotate _ (0 : zmod n).val = _, rw zmod.val_zero, exact rotate_zero v.1.to_list end, mul_smul := λ a b ⟨⟨v, hv₁⟩, hv₂⟩, subtype.eq $ vector.eq _ _ $ show v.rotate ((a + b : zmod n).val) = list.rotate (list.rotate v (b.val)) (a.val), by rw [zmod.val_add, rotate_rotate, ← rotate_mod _ (b.val + a.val), add_comm, hv₁] } lemma one_mem_vectors_prod_eq_one (n : ℕ) : vector.repeat (1 : G) n ∈ vectors_prod_eq_one G n := by simp [vector.repeat, vectors_prod_eq_one] lemma one_mem_fixed_points_rotate (n : ℕ) [fact (0 < n)] : (⟨vector.repeat (1 : G) n, one_mem_vectors_prod_eq_one n⟩ : vectors_prod_eq_one G n) ∈ fixed_points (multiplicative (zmod n)) (vectors_prod_eq_one G n) := λ m, subtype.eq $ vector.eq _ _ $ rotate_eq_self_iff_eq_repeat.2 ⟨(1 : G), show list.repeat (1 : G) n = list.repeat 1 (list.repeat (1 : G) n).length, by simp⟩ _ /-- Cauchy's theorem -/ lemma exists_prime_order_of_dvd_card [fintype G] (p : ℕ) [hp : fact p.prime] (hdvd : p ∣ card G) : ∃ x : G, order_of x = p := let n : ℕ+ := ⟨p - 1, nat.sub_pos_of_lt hp.1.one_lt⟩ in have hn : p = n + 1 := nat.succ_sub hp.1.pos, have hcard : card (vectors_prod_eq_one G (n + 1)) = card G ^ (n : ℕ), by rw [set.ext mem_vectors_prod_eq_one_iff, set.card_range_of_injective (mk_vector_prod_eq_one_injective _), card_vector], have hzmod : fintype.card (multiplicative (zmod p)) = p ^ 1, by { rw pow_one p, exact zmod.card p }, have hmodeq : _ = _ := @mul_action.card_modeq_card_fixed_points (multiplicative (zmod p)) (vectors_prod_eq_one G p) _ _ _ _ _ _ 1 hp hzmod, have hdvdcard : p ∣ fintype.card (vectors_prod_eq_one G (n + 1)) := calc p ∣ card G ^ 1 : by rwa pow_one ... ∣ card G ^ (n : ℕ) : pow_dvd_pow _ n.2 ... = card (vectors_prod_eq_one G (n + 1)) : hcard.symm, have hdvdcard₂ : p ∣ card (fixed_points (multiplicative (zmod p)) (vectors_prod_eq_one G p)), by { rw nat.dvd_iff_mod_eq_zero at hdvdcard ⊢, rwa [← hn, hmodeq] at hdvdcard }, have hcard_pos : 0 < card (fixed_points (multiplicative (zmod p)) (vectors_prod_eq_one G p)) := fintype.card_pos_iff.2 ⟨⟨⟨vector.repeat 1 p, one_mem_vectors_prod_eq_one _⟩, one_mem_fixed_points_rotate _⟩⟩, have hlt : 1 < card (fixed_points (multiplicative (zmod p)) (vectors_prod_eq_one G p)) := calc (1 : ℕ) < p : hp.1.one_lt ... ≤ _ : nat.le_of_dvd hcard_pos hdvdcard₂, let ⟨⟨⟨⟨x, hx₁⟩, hx₂⟩, hx₃⟩, hx₄⟩ := fintype.exists_ne_of_one_lt_card hlt ⟨_, one_mem_fixed_points_rotate p⟩ in have hx : x ≠ list.repeat (1 : G) p, from λ h, by simpa [h, vector.repeat] using hx₄, have ∃ a, x = list.repeat a x.length := by exactI rotate_eq_self_iff_eq_repeat.1 (λ n, have list.rotate x (n : zmod p).val = x := subtype.mk.inj (subtype.mk.inj (hx₃ (n : zmod p))), by rwa [zmod.val_nat_cast, ← hx₁, rotate_mod] at this), let ⟨a, ha⟩ := this in ⟨a, have hx1 : x.prod = 1 := hx₂, have ha1: a ≠ 1, from λ h, hx (ha.symm ▸ h ▸ hx₁ ▸ rfl), have a ^ p = 1, by rwa [ha, list.prod_repeat, hx₁] at hx1, (hp.1.2 _ (order_of_dvd_of_pow_eq_one this)).resolve_left (λ h, ha1 (order_of_eq_one_iff.1 h))⟩ open subgroup submonoid is_group_hom mul_action lemma mem_fixed_points_mul_left_cosets_iff_mem_normalizer {H : subgroup G} [fintype ((H : set G) : Type u)] {x : G} : (x : quotient H) ∈ fixed_points H (quotient H) ↔ x ∈ normalizer H := ⟨λ hx, have ha : ∀ {y : quotient H}, y ∈ orbit H (x : quotient H) → y = x, from λ _, ((mem_fixed_points' _).1 hx _), (inv_mem_iff _).1 (@mem_normalizer_fintype _ _ _ _inst_2 _ (λ n (hn : n ∈ H), have (n⁻¹ * x)⁻¹ * x ∈ H := quotient_group.eq.1 (ha (mem_orbit _ ⟨n⁻¹, H.inv_mem hn⟩)), show _ ∈ H, by {rw [mul_inv_rev, inv_inv] at this, convert this, rw inv_inv} )), λ (hx : ∀ (n : G), n ∈ H ↔ x * n * x⁻¹ ∈ H), (mem_fixed_points' _).2 $ λ y, quotient.induction_on' y $ λ y hy, quotient_group.eq.2 (let ⟨⟨b, hb₁⟩, hb₂⟩ := hy in have hb₂ : (b * x)⁻¹ * y ∈ H := quotient_group.eq.1 hb₂, (inv_mem_iff H).1 $ (hx _).2 $ (mul_mem_cancel_left H (H.inv_mem hb₁)).1 $ by rw hx at hb₂; simpa [mul_inv_rev, mul_assoc] using hb₂)⟩ def fixed_points_mul_left_cosets_equiv_quotient (H : subgroup G) [fintype (H : set G)] : mul_action.fixed_points H (quotient H) ≃ quotient (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H) := @subtype_quotient_equiv_quotient_subtype G (normalizer H : set G) (id _) (id _) (fixed_points _ _) (λ a, (@mem_fixed_points_mul_left_cosets_iff_mem_normalizer _ _ _ _inst_2 _).symm) (by intros; refl) /-- The first of the Sylow theorems. -/ theorem exists_subgroup_card_pow_prime [fintype G] (p : ℕ) : ∀ {n : ℕ} [hp : fact p.prime] (hdvd : p ^ n ∣ card G), ∃ H : subgroup G, fintype.card H = p ^ n | 0 := λ _ _, ⟨(⊥ : subgroup G), by convert card_bot⟩ | (n+1) := λ hp hdvd, let ⟨H, hH2⟩ := @exists_subgroup_card_pow_prime _ hp (dvd.trans (pow_dvd_pow _ (nat.le_succ _)) hdvd) in let ⟨s, hs⟩ := exists_eq_mul_left_of_dvd hdvd in have hcard : card (quotient H) = s * p := (nat.mul_left_inj (show card H > 0, from fintype.card_pos_iff.2 ⟨⟨1, H.one_mem⟩⟩)).1 (by rwa [← card_eq_card_quotient_mul_card_subgroup H, hH2, hs, pow_succ', mul_assoc, mul_comm p]), have hm : s * p % p = card (quotient (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H)) % p := card_congr (fixed_points_mul_left_cosets_equiv_quotient H) ▸ hcard ▸ @card_modeq_card_fixed_points _ _ _ _ _ _ _ p _ hp hH2, have hm' : p ∣ card (quotient (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H)) := nat.dvd_of_mod_eq_zero (by rwa [nat.mod_eq_zero_of_dvd (dvd_mul_left _ _), eq_comm] at hm), let ⟨x, hx⟩ := @exists_prime_order_of_dvd_card _ (quotient_group.quotient.group _) _ _ hp hm' in have hequiv : H ≃ (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H) := ⟨λ a, ⟨⟨a.1, le_normalizer a.2⟩, a.2⟩, λ a, ⟨a.1.1, a.2⟩, λ ⟨_, _⟩, rfl, λ ⟨⟨_, _⟩, _⟩, rfl⟩, -- begin proof of ∃ H : subgroup G, fintype.card H = p ^ n ⟨subgroup.map ((normalizer H).subtype) (subgroup.comap (quotient_group.mk' (comap H.normalizer.subtype H)) (gpowers x)), begin show card ↥(map H.normalizer.subtype (comap (mk' (comap H.normalizer.subtype H)) (subgroup.gpowers x))) = p ^ (n + 1), suffices : card ↥(subtype.val '' ((subgroup.comap (mk' (comap H.normalizer.subtype H)) (gpowers x)) : set (↥(H.normalizer)))) = p^(n+1), { convert this using 2 }, rw [set.card_image_of_injective (subgroup.comap (mk' (comap H.normalizer.subtype H)) (gpowers x) : set (H.normalizer)) subtype.val_injective, pow_succ', ← hH2, fintype.card_congr hequiv, ← hx, order_eq_card_gpowers, ← fintype.card_prod], exact @fintype.card_congr _ _ (id _) (id _) (preimage_mk_equiv_subgroup_times_set _ _) end⟩ end sylow
1de7a3e1235e28176d3033614138bd60a024c773
d436468d80b739ba7e06843c4d0d2070e43448e5
/src/algebra/category/Mon/basic.lean
5b99dabb5f976e91f66759a66089e07604ea00ab
[ "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
6,350
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.concrete_category import algebra.group import data.equiv.algebra /-! # Category instances for monoid, add_monoid, comm_monoid, and add_comm_monoid. We introduce the bundled categories: * `Mon` * `AddMon` * `CommMon` * `AddCommMon` along with the relevant forgetful functors between them. ## Implementation notes ### Note [locally reducible category instances] We make SemiRing (and the other categories) locally reducible in order to define its instances. This is because writing, for example, instance : concrete_category SemiRing := by { delta SemiRing, apply_instance } results in an instance of the form `id (bundled_hom.concrete_category _)` and this `id`, not being [reducible], prevents a later instance search (once SemiRing is no longer reducible) from seeing that the morphisms of SemiRing are really semiring morphisms (`→+*`), and therefore have a coercion to functions, for example. It's especially important that the `has_coe_to_sort` instance not contain an extra `id` as we want the `semiring ↥R` instance to also apply to `semiring R.α` (it seems to be impractical to guarantee that we always access `R.α` through the coercion rather than directly). TODO: Probably @[derive] should be able to create instances of the required form (without `id`), and then we could use that instead of this obscure `local attribute [reducible]` method. -/ universes u v open category_theory /-- The category of monoids and monoid morphisms. -/ @[to_additive AddMon] def Mon : Type (u+1) := bundled monoid namespace Mon /-- Construct a bundled Mon from the underlying type and typeclass. -/ @[to_additive] def of (M : Type u) [monoid M] : Mon := bundled.of M local attribute [reducible] Mon @[to_additive] instance : has_coe_to_sort Mon := infer_instance @[to_additive add_monoid] instance (M : Mon) : monoid M := M.str @[to_additive] instance bundled_hom : bundled_hom @monoid_hom := ⟨@monoid_hom.to_fun, @monoid_hom.id, @monoid_hom.comp, @monoid_hom.coe_inj⟩ @[to_additive] instance : concrete_category Mon := infer_instance end Mon /-- The category of commutative monoids and monoid morphisms. -/ @[to_additive AddCommMon] def CommMon : Type (u+1) := induced_category Mon (bundled.map @comm_monoid.to_monoid) namespace CommMon /-- Construct a bundled CommMon from the underlying type and typeclass. -/ @[to_additive] def of (M : Type u) [comm_monoid M] : CommMon := bundled.of M local attribute [reducible] CommMon @[to_additive] instance : has_coe_to_sort CommMon := infer_instance @[to_additive add_comm_monoid] instance (M : CommMon) : comm_monoid M := M.str @[to_additive] instance : concrete_category CommMon := infer_instance @[to_additive has_forget_to_AddMon] instance has_forget_to_Mon : has_forget₂ CommMon Mon := infer_instance end CommMon -- We verify that the coercions of morphisms to functions work correctly: example {R S : Mon} (f : R ⟶ S) : (R : Type) → (S : Type) := f example {R S : CommMon} (f : R ⟶ S) : (R : Type) → (S : Type) := f variables {X Y : Type u} section variables [monoid X] [monoid Y] /-- Build an isomorphism in the category `Mon` from a `mul_equiv` between `monoid`s. -/ @[to_additive add_equiv.to_AddMon_iso "Build an isomorphism in the category `AddMon` from a `add_equiv` between `add_monoid`s."] def mul_equiv.to_Mon_iso (e : X ≃* Y) : Mon.of X ≅ Mon.of Y := { hom := e.to_monoid_hom, inv := e.symm.to_monoid_hom } @[simp, to_additive add_equiv.to_AddMon_iso_hom] lemma mul_equiv.to_Mon_iso_hom {e : X ≃* Y} : e.to_Mon_iso.hom = e.to_monoid_hom := rfl @[simp, to_additive add_equiv.to_AddMon_iso_inv] lemma mul_equiv.to_Mon_iso_inv {e : X ≃* Y} : e.to_Mon_iso.inv = e.symm.to_monoid_hom := rfl end section variables [comm_monoid X] [comm_monoid Y] /-- Build an isomorphism in the category `CommMon` from a `mul_equiv` between `comm_monoid`s. -/ @[to_additive add_equiv.to_AddCommMon_iso "Build an isomorphism in the category `AddCommMon` from a `add_equiv` between `add_comm_monoid`s."] def mul_equiv.to_CommMon_iso (e : X ≃* Y) : CommMon.of X ≅ CommMon.of Y := { hom := e.to_monoid_hom, inv := e.symm.to_monoid_hom } @[simp, to_additive add_equiv.to_AddCommMon_iso_hom] lemma mul_equiv.to_CommMon_iso_hom {e : X ≃* Y} : e.to_CommMon_iso.hom = e.to_monoid_hom := rfl @[simp, to_additive add_equiv.to_AddCommMon_iso_inv] lemma mul_equiv.to_CommMon_iso_inv {e : X ≃* Y} : e.to_CommMon_iso.inv = e.symm.to_monoid_hom := rfl end namespace category_theory.iso /-- Build a `mul_equiv` from an isomorphism in the category `Mon`. -/ @[to_additive AddMond_iso_to_add_equiv "Build an `add_equiv` from an isomorphism in the category `AddMon`."] def Mon_iso_to_mul_equiv {X Y : Mon.{u}} (i : X ≅ Y) : X ≃* Y := { to_fun := i.hom, inv_fun := i.inv, left_inv := by tidy, right_inv := by tidy, map_mul' := by tidy }. /-- Build a `mul_equiv` from an isomorphism in the category `CommMon`. -/ @[to_additive AddCommMon_iso_to_add_equiv "Build an `add_equiv` from an isomorphism in the category `AddCommMon`."] def CommMon_iso_to_mul_equiv {X Y : CommMon.{u}} (i : X ≅ Y) : X ≃* Y := { to_fun := i.hom, inv_fun := i.inv, left_inv := by tidy, right_inv := by tidy, map_mul' := by tidy }. end category_theory.iso /-- multiplicative equivalences between `monoid`s are the same as (isomorphic to) isomorphisms in `Mon` -/ @[to_additive add_equiv_iso_AddMon_iso "additive equivalences between `add_monoid`s are the same as (isomorphic to) isomorphisms in `AddMon`"] def mul_equiv_iso_Mon_iso {X Y : Type u} [monoid X] [monoid Y] : (X ≃* Y) ≅ (Mon.of X ≅ Mon.of Y) := { hom := λ e, e.to_Mon_iso, inv := λ i, i.Mon_iso_to_mul_equiv, } /-- multiplicative equivalences between `comm_monoid`s are the same as (isomorphic to) isomorphisms in `CommMon` -/ @[to_additive add_equiv_iso_AddCommMon_iso "additive equivalences between `add_comm_monoid`s are the same as (isomorphic to) isomorphisms in `AddCommMon`"] def mul_equiv_iso_CommMon_iso {X Y : Type u} [comm_monoid X] [comm_monoid Y] : (X ≃* Y) ≅ (CommMon.of X ≅ CommMon.of Y) := { hom := λ e, e.to_CommMon_iso, inv := λ i, i.CommMon_iso_to_mul_equiv, }
aeb36bda500f0980380385de54d4139e325b2a19
8e31b9e0d8cec76b5aa1e60a240bbd557d01047c
/scratch/inverse.lean
2cffd4f03205e23dde43443497944c41f06313f2
[]
no_license
ChrisHughes24/LP
7bdd62cb648461c67246457f3ddcb9518226dd49
e3ed64c2d1f642696104584e74ae7226d8e916de
refs/heads/master
1,685,642,642,858
1,578,070,602,000
1,578,070,602,000
195,268,102
4
3
null
1,569,229,518,000
1,562,255,287,000
Lean
UTF-8
Lean
false
false
1,127
lean
import data.matrix data.rat.basic linear_algebra.determinant variable {n : ℕ} open matrix local infix ` ⬝ `:70 := matrix.mul local postfix `ᵀ` : 1500 := matrix.transpose def comatrix (M : matrix (fin n) (fin n) ℚ) : matrix (fin n) (fin n) ℚ := begin cases n, { exact fin.elim0 }, { exact λ i j, (-1) ^ (i + j : ℕ) * det (minor M (λ i' : fin n, if i'.1 < i.1 then i'.cast_succ else i'.succ) (λ j' : fin n, if j'.1 < j.1 then j'.cast_succ else j'.succ)) } end def list.to_matrix (m :ℕ) (n : ℕ) (l : list (list ℚ)) : matrix (fin m) (fin n) ℚ := λ i j, (l.nth_le i sorry).nth_le j sorry instance has_repr_fin_fun {n : ℕ} {α : Type*} [has_repr α] : has_repr (fin n → α) := ⟨λ f, repr (vector.of_fn f).to_list⟩ instance {m n} : has_repr (matrix (fin m) (fin n) ℚ) := has_repr_fin_fun def inverse (M : matrix (fin n) (fin n) ℚ) : matrix (fin n) (fin n) ℚ := (det M)⁻¹ • (comatrix M)ᵀ lemma mul_inverse : Π n, (M : matrix (fin n) (fin n) ℚ) : M ⬝ inverse M = 1 := begin end def M := list.to_matrix 3 3 [[1,2,3],[1,2,0],[0,1,0]] #eval M ⬝ inverse M
4bb6b8df58d0f8726a450e95abda22c11557a5be
75bd9c50a345718d735a7533c007cf45f9da9a83
/src/data/mv_polynomial/comm_ring.lean
33e77fb5768728e5bf43bacaa3e9893292cc9acd
[ "Apache-2.0" ]
permissive
jtbarker/mathlib
a1a3b1ddc16179826260578410746756ef18032c
392d3e376b44265ef2dedbd92231d3177acc1fd0
refs/heads/master
1,671,246,411,096
1,600,801,712,000
1,600,801,712,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,940
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, Johan Commelin, Mario Carneiro -/ import data.mv_polynomial.variables /-! # Multivariate polynomials over a ring Many results about polynomials hold when the coefficient ring is a commutative semiring. Some stronger results can be derived when we assume this semiring is a ring. This file does not define any new operations, but proves some of these stronger results. ## Notation As in other polynomial files we typically use the notation: + `σ : Type*` (indexing the variables) + `R : Type*` `[comm_ring R]` (the coefficients) + `s : σ →₀ ℕ`, a function from `σ` to `ℕ` which is zero away from a finite set. This will give rise to a monomial in `mv_polynomial σ R` which mathematicians might call `X^s` + `a : R` + `i : σ`, with corresponding monomial `X i`, often denoted `X_i` by mathematicians + `p : mv_polynomial σ R` -/ noncomputable theory open_locale classical big_operators open set function finsupp add_monoid_algebra open_locale big_operators universes u v variables {R : Type u} {S : Type v} namespace mv_polynomial variables {σ : Type*} {a a' a₁ a₂ : R} {e : ℕ} {n m : σ} {s : σ →₀ ℕ} section comm_ring variable [comm_ring R] variables {p q : mv_polynomial σ R} instance : comm_ring (mv_polynomial σ R) := add_monoid_algebra.comm_ring instance C.is_ring_hom : is_ring_hom (C : R → mv_polynomial σ R) := by apply is_ring_hom.of_semiring variables (σ a a') @[simp] lemma C_sub : (C (a - a') : mv_polynomial σ R) = C a - C a' := is_ring_hom.map_sub _ @[simp] lemma C_neg : (C (-a) : mv_polynomial σ R) = -C a := is_ring_hom.map_neg _ @[simp] lemma coeff_neg (m : σ →₀ ℕ) (p : mv_polynomial σ R) : coeff m (-p) = -coeff m p := finsupp.neg_apply @[simp] lemma coeff_sub (m : σ →₀ ℕ) (p q : mv_polynomial σ R) : coeff m (p - q) = coeff m p - coeff m q := finsupp.sub_apply instance coeff.is_add_group_hom (m : σ →₀ ℕ) : is_add_group_hom (coeff m : mv_polynomial σ R → R) := { map_add := coeff_add m } variables {σ} (p) section degrees lemma degrees_neg (p : mv_polynomial σ R) : (- p).degrees = p.degrees := by rw [degrees, finsupp.support_neg]; refl lemma degrees_sub (p q : mv_polynomial σ R) : (p - q).degrees ≤ p.degrees ⊔ q.degrees := le_trans (degrees_add p (-q)) $ by rw [degrees_neg] end degrees section vars variables (p q) @[simp] lemma vars_neg : (-p).vars = p.vars := by simp [vars, degrees_neg] lemma vars_sub_subset : (p - q).vars ⊆ p.vars ∪ q.vars := by convert vars_add_subset p (-q) using 2; simp variables {p q} @[simp] lemma vars_sub_of_disjoint (hpq : disjoint p.vars q.vars) : (p - q).vars = p.vars ∪ q.vars := begin rw ←vars_neg q at hpq, convert vars_add_of_disjoint hpq using 2, simp end end vars section eval₂ variables [comm_ring S] variables (f : R →+* S) (g : σ → S) @[simp] lemma eval₂_sub : (p - q).eval₂ f g = p.eval₂ f g - q.eval₂ f g := (eval₂_hom f g).map_sub _ _ @[simp] lemma eval₂_neg : (-p).eval₂ f g = -(p.eval₂ f g) := (eval₂_hom f g).map_neg _ lemma hom_C (f : mv_polynomial σ ℤ → S) [is_ring_hom f] (n : ℤ) : f (C n) = (n : S) := ((ring_hom.of f).comp (ring_hom.of C)).eq_int_cast n /-- A ring homomorphism f : Z[X_1, X_2, ...] → R is determined by the evaluations f(X_1), f(X_2), ... -/ @[simp] lemma eval₂_hom_X {R : Type u} (c : ℤ →+* S) (f : mv_polynomial R ℤ →+* S) (x : mv_polynomial R ℤ) : eval₂ c (f ∘ X) x = f x := mv_polynomial.induction_on x (λ n, by { rw [hom_C f, eval₂_C], exact (ring_hom.of c).eq_int_cast n }) (λ p q hp hq, by { rw [eval₂_add, hp, hq], exact (is_ring_hom.map_add f).symm }) (λ p n hp, by { rw [eval₂_mul, eval₂_X, hp], exact (is_ring_hom.map_mul f).symm }) /-- Ring homomorphisms out of integer polynomials on a type `σ` are the same as functions out of the type `σ`, -/ def hom_equiv : (mv_polynomial σ ℤ →+* S) ≃ (σ → S) := { to_fun := λ f, ⇑f ∘ X, inv_fun := λ f, eval₂_hom (int.cast_ring_hom S) f, left_inv := λ f, ring_hom.ext $ eval₂_hom_X _ _, right_inv := λ f, funext $ λ x, by simp only [coe_eval₂_hom, function.comp_app, eval₂_X] } end eval₂ section total_degree @[simp] lemma total_degree_neg (a : mv_polynomial σ R) : (-a).total_degree = a.total_degree := by simp only [total_degree, finsupp.support_neg] lemma total_degree_sub (a b : mv_polynomial σ R) : (a - b).total_degree ≤ max a.total_degree b.total_degree := calc (a - b).total_degree = (a + -b).total_degree : by rw sub_eq_add_neg ... ≤ max a.total_degree (-b).total_degree : total_degree_add a (-b) ... = max a.total_degree b.total_degree : by rw total_degree_neg end total_degree end comm_ring end mv_polynomial
6f5cc4cf1ed545c4cd08154d0c2a5c516c6ca288
92b1c7f0343a6a5cd36bc0f623a7490da3f1e0f3
/src/lib/attributed/to_mathlib.lean
f4ea964dbdc2031e1f98bcb048967a2414325dd4
[ "Apache-2.0" ]
permissive
jtristan/stump-learnable
717453eb590af16e60c7d3806cc9e66492fab091
aa3c089f41602efa08d31ef6b41e549456186d57
refs/heads/master
1,625,630,634,360
1,607,552,106,000
1,607,552,106,000
218,629,406
15
2
null
null
null
null
UTF-8
Lean
false
false
30,361
lean
/- Various lemmas intended for mathlib. Some parts of this file are originally from https://github.com/johoelzl/mathlib/blob/c9507242274ac18defbceb917f30d6afb8b839a5/src/measure_theory/measurable_space.lean Authors: Johannes Holzl, John Tristan, Koundinya Vajjha -/ import tactic.tidy import measure_theory.giry_monad measure_theory.integration measure_theory.borel_space .dvector import .probability_theory import analysis.complex.exponential local attribute [instance] classical.prop_decidable noncomputable theory -- set_option pp.implicit true -- set_option pp.coercions true -- set_option trace.class_instances true -- set_option class.instance_max_depth 39 -- local attribute [instance] classical.prop_decidable universes u v open nnreal measure_theory nat list measure_theory.measure set lattice ennreal measurable_space probability_measure infixl ` >>=ₐ `:55 := measure.bind infixl ` <$>ₐ `:55 := measure.map local notation `doₐ` binders ` ←ₐ ` m ` ; ` t:(scoped p, m >>=ₐ p) := t local notation `ret` := measure.dirac namespace to_integration variables {α : Type u} {β : Type u} -- Auxilary results about simple functions and characteristic functions. The results in this section should go into integration.lean in mathlib. @[simp] lemma integral_sum [measurable_space α] (m : measure α) (f g : α → ennreal) [hf : measurable f] [hg : measurable g] : m.integral (f + g) = m.integral f + m.integral g := begin rw [integral, integral, integral,←lintegral_add], refl, repeat{assumption}, end @[simp] lemma integral_const_mul [measurable_space α] (m : measure α) {f : α → ennreal} (hf : measurable f) (k:ennreal): m.integral (λ x, k*f(x)) = k * m.integral f := by rw [integral,lintegral_const_mul,integral] ; assumption /-- The characteristic function (indicator function) of a set A. -/ noncomputable def char_fun [measurable_space α] (A : set α) := simple_func.restrict (simple_func.const α (1 : ennreal)) A notation `χ` `⟦` A `⟧` := char_fun A notation `∫` f `ð`m := integral m f -- variables (A : set α) (a : α) [measurable_space α] @[simp] lemma char_fun_apply [measurable_space α] {A : set α} (hA : is_measurable A)(a : α): (χ ⟦A⟧ : simple_func α ennreal) a = ite (a ∈ A) 1 0 := by unfold_coes ; apply (simple_func.restrict_apply _ hA) @[simp] lemma integral_char_fun [measurable_space α] [ne : nonempty α] (m : measure α) {A : set α} (hA : is_measurable A) : (∫ χ⟦A⟧ ðm) = m A := begin rw [char_fun, integral, simple_func.lintegral_eq_integral, simple_func.restrict_integral], unfold set.preimage, dsimp, erw [simple_func.range_const α], simp, rw [←set.univ_def, set.univ_inter], refl, assumption, end lemma dirac_char_fun [measurable_space α] {A : set α} (hA : is_measurable A) : (λ (x : α), (ret x : measure α) A) = χ⟦A⟧ := begin funext,rw [measure.dirac_apply _ hA, char_fun_apply hA], by_cases x ∈ A, split_ifs, simp [h], split_ifs, simp [h], end lemma prob.dirac_char_fun [measurable_space α] {B: set α} (hB : is_measurable B) : (λ x:α,((retₚ x).to_measure : measure α) B) = χ⟦B⟧ := begin conv {congr, funext, rw ret_to_measure}, exact dirac_char_fun hB, end lemma measurable_dirac_fun [measurable_space α] {A : set α} (hA : is_measurable A) : measurable (λ (x : α), (ret x : measure α) A) := by rw dirac_char_fun hA ; apply simple_func.measurable instance simple_func.add_comm_monoid [measurable_space α] [add_comm_monoid β] : add_comm_monoid (simple_func α β) := { add_comm := assume a b, simple_func.ext (assume a, add_comm _ _), .. simple_func.add_monoid } lemma integral_finset_sum [measurable_space α] (m : measure α) (s : finset (set α)) (hX : ∀ (A : set α) , is_measurable (A)) : m.integral (s.sum (λ A, χ ⟦ A ⟧)) = s.sum (λ A, m A) := begin rw integral, refine finset.induction_on s _ _, { simp, erw lintegral_zero }, { assume a s has ih, simp [has], erw [lintegral_add], rw simple_func.lintegral_eq_integral,unfold char_fun, erw simple_func.restrict_const_integral, dsimp, rw ih, ext1,cases a_1, dsimp at *, simp at *, refl, exact(hX a), { intros i h, dsimp at *, solve_by_elim [hX] }, { intros a b, dsimp at *, solve_by_elim }, }, end lemma integral_le_integral [measurable_space α] (m : measure α) (f g : α → ennreal) (h : f ≤ g) : (∫ f ðm) ≤ (∫ g ðm) := begin rw integral, rw integral, apply lintegral_le_lintegral, assumption, end noncomputable def char_prod [measurable_space α]{f : α → ennreal}{ε : ennreal}(hf : measurable f)(eh : ε > 0): simple_func α ennreal := ⟨ λ x, if (f(x) ≥ ε) then ε else 0, assume x, by letI : measurable_space ennreal := borel ennreal; exact measurable.if (measurable_le measurable_const hf) measurable_const measurable_const _ (is_measurable_of_is_closed is_closed_singleton), begin apply finite_subset (finite_union (finite_singleton ε) ((finite_singleton 0))), rintro _ ⟨a, rfl⟩, by_cases (f a ≥ ε); simp [h], end ⟩ @[simp] lemma char_prod_apply [measurable_space α]{f : α → ennreal}{ε : ennreal}(hf : measurable f)(eh : ε > 0) (a : α): (char_prod hf eh) a = if (f a ≥ ε) then ε else 0 := rfl /-- Markov's inequality. -/ theorem measure_fun_ge_le_integral [measurable_space α] [nonempty α] (m : measure α) {f : α → ennreal} (hf : measurable f) : ∀ (ε > 0), ε*m({x | f(x) ≥ ε}) ≤ ∫ f ðm := begin intros ε eh, let s := char_prod hf eh, have hsf : ∀ x, s x ≤ f x, { intro x, by_cases g : (f(x) ≥ ε), dsimp [s], split_ifs, exact g, dsimp [s], split_ifs, exact zero_le (f x), }, convert (integral_le_integral _ _ _ hsf), have seq : s = (simple_func.const α ε) * (χ ⟦{x : α | f x ≥ ε} ⟧),{ apply simple_func.ext, intro a, simp * at *, dunfold char_fun, rw [simple_func.restrict_apply, simple_func.const_apply], split_ifs, rw mul_one, rw mul_zero, apply (@measurable_le ennreal α _ _), exact measurable_const, assumption, }, rw seq, simp, rw [integral_const_mul m, integral_char_fun], apply (@measurable_le ennreal α _ _), exact measurable_const, assumption, apply simple_func.measurable, end /-- Chebyshev's inequality for a nondecreasing function `g`. -/ theorem measure_fun_ge_le_integral_comp [measurable_space α][nonempty α] (m : measure α) {f : α → ennreal} {g : ennreal → ennreal}(hf : measurable f) (hg : measurable g) (nondec : ∀ x y,x ≤ y → g x ≤ g y): ∀ (t > 0), g(t)*m({x | f(x) ≥ t}) ≤ ∫ g ∘ f ðm := begin intros t ht, have hsf : ∀ x, g(t) * (χ ⟦{x : α | f x ≥ t} ⟧ x) ≤ (g (f x)), { intro x, dunfold char_fun, rw [simple_func.restrict_apply, simple_func.const_apply], split_ifs, rw [mul_one], apply (@nondec _ _ h), finish, apply (@measurable_le ennreal α _ _), exact measurable_const, assumption, }, rw [←integral_char_fun, ←integral_const_mul m], apply (integral_le_integral m), exact hsf, apply simple_func.measurable, apply (@measurable_le ennreal α _ _), exact measurable_const, assumption, end end to_integration namespace giry_pi -- Auxilary results about infinite products of measure spaces. -- This section has to go back to `constructions` in `measure_theory/measurable_space`. Originally from Johannes' fork. instance pi.measurable_space (ι : Type*) (α : ι → Type*) [m : ∀i, measurable_space (α i)] : measurable_space (Πi, α i) := ⨆i, (m i).comap (λf, f i) instance pi.measurable_space_Prop (ι : Prop) (α : ι → Type*) [m : ∀i, measurable_space (α i)] : measurable_space (Πi, α i) := ⨆i, (m i).comap (λf, f i) lemma measurable_pi {ι : Type*} {α : ι → Type*} {β : Type*} [m : ∀i, measurable_space (α i)] [measurable_space β] {f : β → Πi, α i} : measurable f ↔ (∀i, measurable (λb, f b i)):= begin rw [measurable, pi.measurable_space, supr_le_iff], refine forall_congr (assume i, _), rw [measurable_space.comap_le_iff_le_map, measurable_space.map_comp], refl end lemma measurable_apply {ι : Type*} {α : ι → Type*} {β : Type*} [m : ∀i, measurable_space (α i)] [measurable_space β] (f : β → Πi, α i) (i : ι) (hf : measurable f) : measurable (λb, f b i) := measurable_pi.1 hf _ lemma measurable_pi_Prop {ι : Prop} {α : ι → Type*} {β : Type*} [m : ∀i, measurable_space (α i)] [measurable_space β] {f : β → Πi, α i} : measurable f ↔ (∀i, measurable (λb, f b i)):= begin rw [measurable, pi.measurable_space_Prop, supr_le_iff], refine forall_congr (assume i, _), rw [measurable_space.comap_le_iff_le_map, measurable_space.map_comp], refl end lemma measurable_apply_Prop {p : Prop} {α : p → Type*} {β : Type*} [m : ∀i, measurable_space (α i)] [measurable_space β] (f : β → Πi, α i) (h : p) (hf : measurable f) : measurable (λb, f b h) := measurable_pi_Prop.1 hf _ end giry_pi section giry_prod open to_integration variables {α : Type u} {β : Type u} {γ : Type v} /- Auxilary results about the Giry monad and binary products. The following results should go back to giry_monad.lean -/ /-- Right identity monad law for the Giry monad. -/ lemma giry.bind_return_comp [measurable_space α][measurable_space β] (D : measure α) {p : α → β} (hp : measurable p) : (doₐ (x : α) ←ₐ D ; ret (p x)) = p <$>ₐ D := measure.ext $ assume s hs, begin rw [measure.bind_apply hs _], rw [measure.map_apply hp hs], conv_lhs{congr, skip, funext, rw [measure.dirac_apply _ hs]}, transitivity, apply lintegral_supr_const, exact hp _ hs, rw one_mul, refl, exact measurable.comp measurable_dirac hp, end /-- Left identity monad law for compositions in the Giry monad -/ lemma giry.return_bind_comp [measurable_space α][measurable_space β] {p : α → measure β} {f : α → α} (hf : measurable f)(hp : measurable p) (a : α) : (doₐ x ←ₐ dirac a ; p (f x)) = p (f a) := measure.ext $ assume s hs, begin rw measure.bind_apply hs, rw measure.integral_dirac a, swap, exact measurable.comp hp hf, exact measurable.comp (measurable_coe hs) (measurable.comp hp hf), end def prod_measure [measurable_space α][measurable_space β] (μ : measure α) (ν : measure β) : measure (α × β) := doₐ x ←ₐ μ ; doₐ y ←ₐ ν ; ret (x, y) infixl ` ⊗ₐ `:55 := prod_measure instance prod.measure_space [measurable_space α] [measurable_space β] (μ : measure α) (ν : measure β) : measure_space (α × β) := ⟨ μ ⊗ₐ ν ⟩ lemma inl_measurable [measurable_space α][measurable_space β] : ∀ y : β, measurable (λ x : α, (x,y)) := assume y, begin apply measurable.prod, dsimp, exact measurable_id, dsimp, exact measurable_const, end lemma inr_measurable [measurable_space α][measurable_space β] : ∀ x : α, measurable (λ y : β, (x,y)) := assume y, begin apply measurable.prod, dsimp, exact measurable_const, dsimp, exact measurable_id, end lemma inl_measurable_dirac [measurable_space α][measurable_space β] : ∀ y : β, measurable (λ (x : α), ret (x, y)) := assume y, begin apply measurable_of_measurable_coe, intros s hs, simp [hs, lattice.supr_eq_if, mem_prod_eq], apply measurable_const.if _ measurable_const, apply measurable.preimage _ hs, apply measurable.prod, dsimp, exact measurable_id, dsimp, exact measurable_const, end lemma inr_measurable_dirac [measurable_space β][measurable_space α] : ∀ x : α, measurable (λ (y : β), ret (x, y)) := assume x, begin apply measurable_of_measurable_coe, intros s hs, simp [hs, lattice.supr_eq_if, mem_prod_eq], apply measurable_const.if _ measurable_const, apply measurable.preimage _ hs, apply measurable.prod, dsimp, exact measurable_const, dsimp, exact measurable_id, end lemma inr_section_is_measurable [measurable_space α] [measurable_space β] {E : set (α × β)} (hE : is_measurable E) (x : α) : is_measurable ({ y:β | (x,y) ∈ E}) := begin change (is_measurable ((λ z:β, (x,z))⁻¹' E)), apply inr_measurable, assumption, end lemma inl_section_is_measurable [measurable_space α] [measurable_space β] {E : set (α × β)} (hE : is_measurable E) (y : β) : is_measurable ({ x:α | (x,y) ∈ E}) := begin change (is_measurable ((λ z:α, (z,y))⁻¹' E)), apply inl_measurable, assumption, end lemma snd_comp_measurable [measurable_space α] [measurable_space β] [measurable_space γ] {f : α × β → γ} (hf : measurable f) (x : α) : measurable (λ y:β, f (x, y)) := (measurable.comp hf (inr_measurable _)) lemma fst_comp_measurable [measurable_space α] [measurable_space β] [measurable_space γ] {f : α × β → γ} (hf : measurable f) (y : β) : measurable ((λ x:α, f (x, y))) := (measurable.comp hf (inl_measurable _)) lemma measurable_pair_iff [measurable_space α] [measurable_space β] [measurable_space γ] (f : γ → α × β) : measurable f ↔ (measurable (prod.fst ∘ f) ∧ measurable (prod.snd ∘ f)) := iff.intro (assume h, and.intro (measurable_fst h) (measurable_snd h)) (assume ⟨h₁, h₂⟩, measurable.prod h₁ h₂) @[simp] lemma dirac.prod_apply [measurable_space α][measurable_space β]{A : set α} {B : set β} (hA : is_measurable A) (hB : is_measurable B) (a : α) (b : β) : (ret (a,b) : measure (α × β)) (A.prod B) = ((ret a : measure α) A) * ((ret b : measure β) B) := begin rw [dirac_apply, dirac_apply, dirac_apply, mem_prod_eq], dsimp, by_cases Ha: (a ∈ A); by_cases Hb: (b ∈ B), repeat {simp [Ha, Hb]}, repeat {assumption}, exact is_measurable_set_prod hA hB, end lemma prod.bind_ret_comp [measurable_space α] [measurable_space β] (μ : measure α) : ∀ y : β, (doₐ (x : α) ←ₐ μ; ret (x,y)) = (λ x, (x,y)) <$>ₐ μ := assume y, begin apply giry.bind_return_comp, apply measurable.prod, dsimp, exact measurable_id, dsimp, exact measurable_const, end -- TODO(Kody) : move this back to mathlib/measurable_space.lean lemma measure_rect_generate_from [measurable_space α] [measurable_space β] : prod.measurable_space = generate_from {E | ∃ (A : set α) (B : set β), E = A.prod B ∧ is_measurable A ∧ is_measurable B} := begin rw eq_iff_le_not_lt, split, { apply generate_from_le_generate_from, intros s hs, rcases hs with ⟨A₀, hA, rfl⟩ | ⟨B₀, hB, rfl⟩, existsi [A₀, univ], fsplit, ext1, cases x, simp, exact and.intro hA is_measurable.univ, existsi [univ, B₀], fsplit, ext1, cases x, simp, exact and.intro is_measurable.univ hB, }, { apply not_lt_of_le, apply measurable_space.generate_from_le, intros t ht, dsimp at ht, rcases ht with ⟨A, B, rfl, hA, hB⟩, exact is_measurable_set_prod hA hB, } end def measurable_prod_bind_ret [measurable_space α] [measurable_space β] (ν : probability_measure β): set(α × β) → Prop := λ s, measurable (λ (x : α), (doₚ (y : β) ←ₚ ν ; retₚ (x, y)) s) lemma measure_rect_inter [measurable_space α] [measurable_space β] : ∀t₁ t₂, t₁ ∈ {E | ∃ (A : set α) (B : set β), E = A.prod B ∧ is_measurable A ∧ is_measurable B} → t₂ ∈ {E | ∃ (A : set α) (B : set β), E = A.prod B ∧ is_measurable A ∧ is_measurable B} → t₁ ∩ t₂ ≠ ∅ → t₁ ∩ t₂ ∈ {E | ∃ (A : set α) (B : set β), E = A.prod B ∧ is_measurable A ∧ is_measurable B} := begin rintros t₁ t₂ ⟨A, B, rfl, hA, hB⟩ ⟨A', B', rfl, hA', hB'⟩ hI, rw prod_inter_prod, existsi [(A ∩ A'),(B ∩ B')], fsplit, refl, exact and.intro (is_measurable.inter hA hA') (is_measurable.inter hB hB'), end lemma measurable_prod_bind_ret_empty [measurable_space α] [measurable_space β] (ν : probability_measure β): measurable (λ (x : α), (doₚ (y : β) ←ₚ ν ; retₚ (x, y)) ∅):= by simp ; exact measurable_const lemma measurable_prod_bind_ret_compl [measurable_space α] [measurable_space β] (ν : probability_measure β) : ∀ t : set (α × β), is_measurable t → measurable (λ (x : α), (doₚ (y : β) ←ₚ ν ; retₚ (x, y)) t) → measurable (λ (x : α), (doₚ (y : β) ←ₚ ν ; retₚ (x, y)) (- t)) := begin intros t ht hA, rw compl_eq_univ_diff, conv{congr, funext, rw [probability_measure.prob_diff _ (subset_univ _) is_measurable.univ ht]}, simp, refine measurable.comp _ hA, refine measurable.comp _ (measurable_sub measurable_const _), exact measurable_of_real, exact measurable_of_continuous nnreal.continuous_coe, end lemma measurable_prod_bind_ret_basic [measurable_space α] [measurable_space β] (ν : probability_measure β) : ∀ (t : set (α × β)),t ∈ {E : set (α × β) | ∃ (A : set α) (B : set β), E = set.prod A B ∧ is_measurable A ∧ is_measurable B} → measurable (λ (x : α), (doₚ (y : β) ←ₚ ν ; retₚ (x, y)) t) := begin rintros t ⟨A, B, rfl, hA, hB⟩, conv{congr,funext,rw [_root_.bind_apply (is_measurable_set_prod hA hB) (prob_inr_measurable_dirac x)],}, refine measurable.comp _ _, exact measurable_to_nnreal, dsimp, conv{congr,funext,simp [coe_eq_to_measure]}, simp [prob.dirac_apply' hA hB], have h : measurable (λ (x : β), ((retₚ x).to_measure : measure β) B),{ conv{congr,funext,rw ret_to_measure,}, exact measurable_dirac_fun hB, }, conv {congr, funext, rw [integral_const_mul ν.to_measure h],}, refine measurable_mul _ _, conv{congr,funext, rw [ret_to_measure],},exact measurable_dirac_fun hA, exact measurable_const, end lemma measurable_prod_bind_ret_union [measurable_space α] [measurable_space β] (ν : probability_measure β): ∀h:ℕ → set (α × β), (∀i j, i ≠ j → h i ∩ h j ⊆ ∅) → (∀i, is_measurable (h i)) → (∀i, measurable(λ (x : α), (doₚ (y : β) ←ₚ ν ; retₚ (x, y)) (h i))) → measurable (λ (x : α), (doₚ (y : β) ←ₚ ν ; retₚ (x, y)) (⋃i, h i)) := begin rintros h hI hA hB, unfold_coes, refine measurable.comp (measurable_of_measurable_nnreal measurable_id) _, conv{congr,funext,rw [m_Union _ hA hI,ennreal.tsum_eq_supr_nat]}, apply measurable.supr, intro i, apply measurable_finset_sum, intros i, have h := hB i, clear hB, refine measurable_of_ne_top _ _ _, assume x, refine probability_measure.to_measure_ne_top _ _, assumption, end -- Push this back to ennreal.lean lemma to_nnreal_mul (a b : ennreal) : ennreal.to_nnreal(a*b) = ennreal.to_nnreal(a) * ennreal.to_nnreal(b) := begin cases a; cases b, { simp [none_eq_top] }, { by_cases h : b = 0; simp [none_eq_top, some_eq_coe, h, top_mul] }, { by_cases h : a = 0; simp [none_eq_top, some_eq_coe, h, mul_top] }, { simp [some_eq_coe, coe_mul.symm, -coe_mul] } end @[simp] theorem prod.prob_measure_apply [measurable_space α] [measurable_space β][nonempty α] [nonempty β] (μ : probability_measure α) (ν : probability_measure β) {A : set α} {B : set β} (hA : is_measurable A) (hB : is_measurable B) : (μ ⊗ₚ ν) (A.prod B) = μ (A) * ν (B) := begin dunfold prod.prob_measure, rw _root_.bind_apply (is_measurable_set_prod hA hB), conv_lhs{congr, congr, skip, funext, erw [_root_.bind_apply ( is_measurable_set_prod hA hB) (prob_inr_measurable_dirac a)]}, simp[coe_eq_to_measure, prob.dirac_apply' hA hB], -- move this to probability_theory have h : measurable (λ (x : β), ((retₚ x).to_measure : measure β) B), { conv{congr,funext,rw ret_to_measure,}, exact measurable_dirac_fun hB, }, conv {congr, funext, congr, congr, skip, funext, rw [integral_const_mul ν.to_measure h,ret_to_measure,mul_comm],}, rw [prob.dirac_char_fun hB, integral_char_fun ν.to_measure hB], -- move this to measurable_space have g : ∀ a:α, ((ret a : measure α) A) < ⊤, { assume a, rw dirac_apply _ hA, by_cases(a ∈ A), simp[h],exact lt_top_iff_ne_top.2 one_ne_top, simp[h], exact lt_top_iff_ne_top.2 zero_ne_top, }, conv_lhs{congr, congr, skip, funext, rw [coe_to_nnreal (lt_top_iff_ne_top.1 (mul_lt_top (to_measure_lt_top _ _) (g a)))]}, conv_lhs{congr, rw [integral_const_mul μ.to_measure (measurable_dirac_fun hA)]}, rw [dirac_char_fun hA, integral_char_fun _ hA, mul_comm, to_nnreal_mul], refl, apply prob.measurable_of_measurable_coe, exact ( @induction_on_inter _ (measurable_prod_bind_ret ν) ({E | ∃ (A : set α) (B : set β), (E = A.prod B) ∧ is_measurable A ∧ is_measurable B}) _ measure_rect_generate_from measure_rect_inter (measurable_prod_bind_ret_empty ν) (measurable_prod_bind_ret_basic ν) (measurable_prod_bind_ret_compl ν) (measurable_prod_bind_ret_union ν) ), end end giry_prod section fubini variables {α : Type u} {β : Type u} [measure_space α] [measure_space β] open to_integration local notation `∫` f `𝒹`m := integral m.to_measure f lemma integral_char_rect [measurable_space α] [measurable_space β] [n₁ : nonempty α] [n₂ : nonempty β](μ : probability_measure α) (ν : probability_measure β) {A : set α} {B : set β} (hA : is_measurable A) (hB : is_measurable B) : (∫ χ ⟦ A.prod B ⟧ 𝒹(μ ⊗ₚ ν)) = (μ A) * (ν B) := begin haveI := (nonempty_prod.2 (and.intro n₁ n₂)), rw [integral_char_fun _ (is_measurable_set_prod hA hB),←coe_eq_to_measure, (prod.prob_measure_apply _ _ hA hB)], simp, end end fubini section prod_measure_measurable /- This section aims to prove `measurable (λ x : α , f x ⊗ₚ g x)` using Dynkin's π-λ theorem. Push this back to giry_monad.lean -/ variables {α : Type u} {β : Type u} {γ : Type u} def measurable_prod_measure_pred [measurable_space α] [measurable_space β] [measurable_space γ] {f : α → probability_measure β} {g : α → probability_measure γ} (hf : measurable f) (hg : measurable g) : set (β × γ) → Prop := λ s : set (β × γ), measurable (λ b:α,(f b ⊗ₚ g b) s) lemma measurable_rect_empty {γ : Type u} [measurable_space α] [measurable_space β] [measurable_space γ] {f : α → probability_measure β} {g : α → probability_measure γ} (hf : measurable f) (hg : measurable g): measurable (λ b:α,(f b ⊗ₚ g b) ∅) := by simp ; exact measurable_const lemma measure_rect_union {γ : Type u} [measurable_space α] [measurable_space β] [measurable_space γ] (f : α → probability_measure β) (g : α → probability_measure γ) : ∀h:ℕ → set (β × γ), (∀i j, i ≠ j → h i ∩ h j ⊆ ∅) → (∀i, is_measurable (h i)) → (∀i, measurable (λ b:α,(f b ⊗ₚ g b) (h i))) → measurable (λ b:α,(f b ⊗ₚ g b) (⋃i, h i)) := begin rintros h hI hA hB, unfold_coes, conv{congr,funext,rw [m_Union _ hA hI]}, dsimp, conv{congr,funext,rw ennreal.tsum_eq_supr_nat,}, refine measurable.comp measurable_to_nnreal _, apply measurable.supr, intro i, apply measurable_finset_sum, assume i, refine measurable_of_ne_top _ _ _, assume a, refine probability_measure.to_measure_ne_top _ _, solve_by_elim, end lemma measurable_rect_compl {γ : Type u} [measurable_space α] [measurable_space β] [measurable_space γ](f : α → probability_measure β) (g : α → probability_measure γ) : ∀ t : set (β × γ), is_measurable t → measurable (λ b:α,(f b ⊗ₚ g b) t) → measurable (λ b:α,(f b ⊗ₚ g b) (- t)) := begin intros t ht hA, rw compl_eq_univ_diff, conv{congr, funext, rw [probability_measure.prob_diff _ (subset_univ _) is_measurable.univ ht]}, simp, refine measurable.comp _ hA, refine measurable.comp _ (measurable_sub measurable_const _), exact measurable_of_real, exact measurable_of_continuous nnreal.continuous_coe, end -- Move back to Giry monad lemma measurable_measure_kernel [measurable_space α] [measurable_space β] {f : α → measure β} {A : set β} (hf : measurable f) (hA : is_measurable A) : measurable (λ a, f a A) := measurable.comp (measurable_coe hA) hf lemma measurable_rect_basic {γ : Type u} [measurable_space α] [measurable_space β] [measurable_space γ] [nonempty β] [nonempty γ] {f : α → probability_measure β} {g : α → probability_measure γ} (hf : measurable f) (hg : measurable g) : ∀ (t : set (β × γ)),t ∈ {E : set (β × γ) | ∃ (A : set β) (B : set γ), E = set.prod A B ∧ is_measurable A ∧ is_measurable B} → measurable (λ b:α,(f b ⊗ₚ g b) t) := begin rintros t ⟨A, B, rfl, hA, hB⟩, simp [prod.prob_measure_apply _ _ hA hB], exact measure_theory.measurable_mul (prob.measurable_measure_kernel hf hA) (prob.measurable_measure_kernel hg hB), end theorem measurable_pair_measure {γ : Type u} [measurable_space α] [measurable_space β] [measurable_space γ] [nonempty β] [nonempty γ]{f : α → probability_measure β} {g : α → probability_measure γ} (hf : measurable f) (hg : measurable g) : measurable (λ x : α , f x ⊗ₚ g x) := begin apply prob.measurable_of_measurable_coe, exact @induction_on_inter _ (measurable_prod_measure_pred hf hg) ({E | ∃ (A : set β) (B : set γ), (E = A.prod B) ∧ is_measurable A ∧ is_measurable B}) _ (measure_rect_generate_from) (measure_rect_inter) (measurable_rect_empty hf hg) (measurable_rect_basic hf hg) (measurable_rect_compl f g) (measure_rect_union f g), end end prod_measure_measurable section giry_vec /- Auxilary lemmas about vectors as iterated binary prodcuts. -/ variable {α : Type u} def vec : Type u → ℕ → Type u | A 0 := A | A (succ k) := A × vec A k @[simp] def kth_projn : Π {n}, vec α n → dfin (succ n) → α | 0 x _ := x | (succ n) x dfin.fz := x.fst | (succ n) (x,xs) (dfin.fs k) := kth_projn xs k def vec.set_prod {n : ℕ}(A : set α) (B : set (vec α n)) : set (vec α (succ n)) := do l ← A, xs ← B, pure $ (l,xs) instance nonempty.vec [nonempty α] : ∀ n, nonempty (vec α n) := λ n, begin induction n with k ih, rwa vec, rw vec, apply nonempty_prod.2, exact (and.intro _inst_1 ih) end instance vec.measurable_space (n : ℕ) [m : measurable_space α]: measurable_space (vec α n) := begin induction n with k ih, exact m, rw vec, exact (m.comap prod.fst ⊔ ih.comap prod.snd) end noncomputable def vec.prod_measure [measurable_space α] (μ : probability_measure α) : Π n : ℕ, probability_measure (vec α n) | 0 := μ | (succ k) := doₚ x ←ₚ μ ; doₚ xs ←ₚ (vec.prod_measure k); retₚ (x,xs) instance vec.measure_space [measurable_space α] (μ : probability_measure α) : Π n:ℕ, measure_space (vec α n) | 0 := ⟨ μ.to_measure ⟩ | (succ k) := ⟨ (vec.prod_measure μ _).to_measure ⟩ -- Why doesn't refl work here?! @[simp] lemma vec.prod_measure_eq (n : ℕ) [measurable_space α](μ : probability_measure α) : (vec.prod_measure μ (n+1)) = μ ⊗ₚ (vec.prod_measure μ n) := by dunfold vec.prod_measure;refl lemma vec.inl_measurable [measurable_space α] (n : ℕ): ∀ xs : vec α n, measurable (λ x : α, (x, xs)) := inl_measurable lemma vec.inr_measurable [measurable_space α] (n : ℕ): ∀ x : α, measurable (λ xs : vec α n,(x,xs)) := inr_measurable lemma vec.dirac_prod_apply [measurable_space α]{A : set α} {n : ℕ} {B : set (vec α n)} (hA : is_measurable A) (hB : is_measurable B) (a : α) (as : vec α n) : (ret (a,as) : measure (vec α (succ n))) (A.prod B) = ((ret a : measure α) A) * ((ret as : measure (vec α n)) B) := dirac.prod_apply hA hB _ _ @[simp] lemma vec.prod_measure_apply {n : ℕ} [measurable_space α][nonempty α] (μ : probability_measure α) (ν : probability_measure (vec α n)) {A : set α} {B : set (vec α n)} (hA : is_measurable A) (hB : is_measurable B) : (μ ⊗ₚ ν) (A.prod B) = μ (A) * ν (B) := prod.prob_measure_apply _ _ hA hB def vec_map {α: Type} {β: Type} (f: α → β): Π n: ℕ, vec α n → vec β n | 0 := λ x, f x | (nat.succ n) := λ v, (f v.fst,vec_map n v.snd) lemma kth_projn_map_comm {α: Type} {β: Type}: ∀ f: α → β, ∀ n: ℕ, ∀ v: vec α n, ∀ i: dfin (succ n), f (kth_projn v i) = kth_projn (vec_map f n v) i := begin intros f n, induction n; intros, { dunfold vec_map, cases i, simp, refl, }, { cases v, cases i, { simp, dunfold vec_map, simp, }, { simp,rw n_ih, refl, } } end lemma measurable_map {α: Type} {β: Type} [measurable_space α] [measurable_space β]: ∀ n: ℕ, ∀ f: α → β, measurable f → measurable (vec_map f n) := begin intros, induction n, { intros, dunfold vec_map, assumption, }, { intros, dunfold vec_map, apply measurable.prod; simp, { apply measurable.comp, assumption, apply measurable_fst, apply measurable_id, }, { apply measurable.comp, assumption, apply measurable_snd, apply measurable_id, } }, end end giry_vec section hoeffding_aux open complex real lemma abs_le_one_iff_ge_neg_one_le_one {x : ℝ} : (complex.abs x ≤ 1) ↔ (-1 ≤ x ∧ x ≤ 1) := by rw abs_of_real ; apply abs_le lemma abs_neg_exp_sub_one_le_double {x : ℝ} (h₁ : complex.abs x ≤ 1)(h₂ : x ≥ 0): complex.abs(exp(-x) - 1) ≤ 2*x := calc complex.abs(exp(-x) - 1) ≤ 2*complex.abs(-x) : @abs_exp_sub_one_le (-x) ((complex.abs_neg x).symm ▸ h₁) ... = 2*complex.abs(x) : by rw (complex.abs_neg x) ... = 2*x : by rw [abs_of_real,((abs_eq h₂).2)]; left; refl lemma neg_exp_ge {x : ℝ} (h₀ : 0 ≤ x) (h₁ : x ≤ 1) : 1 - 2 * x ≤ exp (-x) := begin have h : -(2*x) ≤ exp(-x) -1, { apply (abs_le.1 _).left, rw ←abs_of_real, simp [-add_comm, -sub_eq_add_neg], apply abs_neg_exp_sub_one_le_double _ h₀, rw abs_le_one_iff_ge_neg_one_le_one, split, linarith, assumption, }, linarith, end end hoeffding_aux instance : conditionally_complete_linear_order nnreal := { Sup := Sup, Inf := Inf, le_cSup := assume s a x has, le_cSup x has, cSup_le := assume s a hs h,show Sup ((coe : nnreal → ℝ) '' s) ≤ a, from cSup_le (by simp [hs]) $ assume r ⟨b, hb, eq⟩, eq ▸ h _ hb, cInf_le := assume s a x has, cInf_le x has, le_cInf := assume s a hs h, show (↑a : ℝ) ≤ Inf ((coe : nnreal → ℝ) '' s), from le_cInf (by simp [hs]) $ assume r ⟨b, hb, eq⟩, eq ▸ h _ hb, decidable_le := begin assume x y, apply classical.dec end, .. nnreal.linear_ordered_semiring, .. lattice.lattice_of_decidable_linear_order, .. nnreal.lattice.order_bot }
707a7506f3155df0218bcc6ca935224bdb5b07b9
0c1546a496eccfb56620165cad015f88d56190c5
/library/init/data/sigma/basic.lean
25b13475cab27bcc9a3f472852deaee2ed07cdc0
[ "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
737
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, Jeremy Avigad, Floris van Doorn -/ prelude import init.logic init.wf notation `Σ` binders `, ` r:(scoped p, sigma p) := r notation `Σ'` binders `, ` r:(scoped p, psigma p) := r universe variables u v lemma ex_of_psig {α : Type u} {p : α → Prop} : (Σ' x, p x) → ∃ x, p x | ⟨x, hx⟩ := ⟨x, hx⟩ namespace sigma variables {α : Type u} {β : α → Type v} protected lemma eq : ∀ {p₁ p₂ : Σ a : α, β a} (h₁ : p₁.1 = p₂.1), (eq.rec_on h₁ p₁.2 : β p₂.1) = p₂.2 → p₁ = p₂ | ⟨a, b⟩ ⟨.a, .b⟩ rfl rfl := rfl end sigma
3c110f7dfb1263cad1086ac53e556545ef4bd40b
f3849be5d845a1cb97680f0bbbe03b85518312f0
/tests/lean/num2.lean
4b4dcf4bfd7901445c41f9acad4a4ca677790f5a
[ "Apache-2.0" ]
permissive
bjoeris/lean
0ed95125d762b17bfcb54dad1f9721f953f92eeb
4e496b78d5e73545fa4f9a807155113d8e6b0561
refs/heads/master
1,611,251,218,281
1,495,337,658,000
1,495,337,658,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
354
lean
prelude set_option pp.notation false definition Prop := Sort 0 constant eq {A : Type} : A → A → Prop infixl `=`:50 := eq constant N : Type constant z : N constant o : N constant b : N notation 0 := z notation 1 := o #check 1 #check 0 constant G : Type constant gz : G constant a : G notation 0 := gz #check a = 0 #check (0:G) = a #check b = 0
84750cf25145ab5ea3153005c2b30e2d64425817
4fa161becb8ce7378a709f5992a594764699e268
/src/category_theory/single_obj.lean
e4e8eb88a8044fcb3f9da62f98b809331ff3f25a
[ "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
5,294
lean
/- Copyright (c) 2019 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import category_theory.endomorphism import category_theory.category.Cat import algebra.category.Mon.basic /-! # Single-object category Single object category with a given monoid of endomorphisms. It is defined to facilitate transfering some definitions and lemmas (e.g., conjugacy etc.) from category theory to monoids and groups. ## Main definitions Given a type `α` with a monoid structure, `single_obj α` is `unit` type with `category` structure such that `End (single_obj α).star` is the monoid `α`. This can be extended to a functor `Mon ⥤ Cat`. If `α` is a group, then `single_obj α` is a groupoid. An element `x : α` can be reinterpreted as an element of `End (single_obj.star α)` using `single_obj.to_End`. ## Implementation notes - `category_struct.comp` on `End (single_obj.star α)` is `flip (*)`, not `(*)`. This way multiplication on `End` agrees with the multiplication on `α`. - By default, Lean puts instances into `category_theory` namespace instead of `category_theory.single_obj`, so we give all names explicitly. -/ universes u v w namespace category_theory /-- Type tag on `unit` used to define single-object categories and groupoids. -/ def single_obj (α : Type u) : Type := unit namespace single_obj variables (α : Type u) /-- One and `flip (*)` become `id` and `comp` for morphisms of the single object category. -/ instance category_struct [has_one α] [has_mul α] : category_struct (single_obj α) := { hom := λ _ _, α, comp := λ _ _ _ x y, y * x, id := λ _, 1 } /-- Monoid laws become category laws for the single object category. -/ instance category [monoid α] : category (single_obj α) := { comp_id' := λ _ _, one_mul, id_comp' := λ _ _, mul_one, assoc' := λ _ _ _ _ x y z, (mul_assoc z y x).symm } /-- Groupoid structure on `single_obj α` -/ instance groupoid [group α] : groupoid (single_obj α) := { inv := λ _ _ x, x⁻¹, inv_comp' := λ _ _, mul_right_inv, comp_inv' := λ _ _, mul_left_inv } protected def star : single_obj α := unit.star /-- The endomorphisms monoid of the only object in `single_obj α` is equivalent to the original monoid α. -/ def to_End [monoid α] : α ≃* End (single_obj.star α) := { map_mul' := λ x y, rfl, .. equiv.refl α } lemma to_End_def [monoid α] (x : α) : to_End α x = x := rfl /-- There is a 1-1 correspondence between monoid homomorphisms `α → β` and functors between the corresponding single-object categories. It means that `single_obj` is a fully faithful functor. -/ def map_hom (α : Type u) (β : Type v) [monoid α] [monoid β] : (α →* β) ≃ (single_obj α) ⥤ (single_obj β) := { to_fun := λ f, { obj := id, map := λ _ _, ⇑f, map_id' := λ _, f.map_one, map_comp' := λ _ _ _ x y, f.map_mul y x }, inv_fun := λ f, { to_fun := @functor.map _ _ _ _ f (single_obj.star α) (single_obj.star α), map_one' := f.map_id _, map_mul' := λ x y, f.map_comp y x }, left_inv := λ ⟨f, h₁, h₂⟩, rfl, right_inv := λ f, by cases f; obviously } lemma map_hom_id (α : Type u) [monoid α] : map_hom α α (monoid_hom.id α) = 𝟭 _ := rfl lemma map_hom_comp {α : Type u} {β : Type v} [monoid α] [monoid β] (f : α →* β) {γ : Type w} [monoid γ] (g : β →* γ) : map_hom α γ (g.comp f) = map_hom α β f ⋙ map_hom β γ g := rfl end single_obj end category_theory open category_theory namespace monoid_hom /-- Reinterpret a monoid homomorphism `f : α → β` as a functor `(single_obj α) ⥤ (single_obj β)`. See also `category_theory.single_obj.map_hom` for an equivalence between these types. -/ @[reducible] def to_functor {α : Type u} {β : Type v} [monoid α] [monoid β] (f : α →* β) : (single_obj α) ⥤ (single_obj β) := single_obj.map_hom α β f @[simp] lemma id_to_functor (α : Type u) [monoid α] : (id α).to_functor = 𝟭 _ := rfl @[simp] lemma comp_to_functor {α : Type u} {β : Type v} [monoid α] [monoid β] (f : α →* β) {γ : Type w} [monoid γ] (g : β →* γ) : (g.comp f).to_functor = f.to_functor ⋙ g.to_functor := rfl end monoid_hom namespace units variables (α : Type u) [monoid α] /-- The units in a monoid are (multiplicatively) equivalent to the automorphisms of `star` when we think of the monoid as a single-object category. -/ def to_Aut : units α ≃* Aut (single_obj.star α) := (units.map_equiv (single_obj.to_End α)).trans $ Aut.units_End_equiv_Aut _ @[simp] lemma to_Aut_hom (x : units α) : (to_Aut α x).hom = single_obj.to_End α x := rfl @[simp] lemma to_Aut_inv (x : units α) : (to_Aut α x).inv = single_obj.to_End α (x⁻¹ : units α) := rfl end units namespace Mon open category_theory /-- The fully faithful functor from `Mon` to `Cat`. -/ def to_Cat : Mon ⥤ Cat := { obj := λ x, Cat.of (single_obj x), map := λ x y f, single_obj.map_hom x y f } instance to_Cat_full : full to_Cat := { preimage := λ x y, (single_obj.map_hom x y).inv_fun, witness' := λ x y, by apply equiv.right_inv } instance to_Cat_faithful : faithful to_Cat := { map_injective' := λ x y, by apply equiv.injective } end Mon
3e49777bf66d8bb2d7a28221d3fe9a4df6d1dd82
82e44445c70db0f03e30d7be725775f122d72f3e
/src/deprecated/subring.lean
9f7135caca873593f840ea3981f013b6dd895e94
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
8,077
lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import deprecated.subgroup import deprecated.group import ring_theory.subring universes u v open group variables {R : Type u} [ring R] /-- `S` is a subring: a set containing 1 and closed under multiplication, addition and additive inverse. -/ structure is_subring (S : set R) extends is_add_subgroup S, is_submonoid S : Prop. /-- Construct a `subring` from a set satisfying `is_subring`. -/ def is_subring.subring {S : set R} (hs : is_subring S) : subring R := { carrier := S, one_mem' := hs.one_mem, mul_mem' := hs.mul_mem, zero_mem' := hs.zero_mem, add_mem' := hs.add_mem, neg_mem' := hs.neg_mem } namespace ring_hom lemma is_subring_preimage {R : Type u} {S : Type v} [ring R] [ring S] (f : R →+* S) {s : set S} (hs : is_subring s) : is_subring (f ⁻¹' s) := { ..is_add_group_hom.preimage f.to_is_add_group_hom hs.to_is_add_subgroup, ..is_submonoid.preimage f.to_is_monoid_hom hs.to_is_submonoid, } lemma is_subring_image {R : Type u} {S : Type v} [ring R] [ring S] (f : R →+* S) {s : set R} (hs : is_subring s) : is_subring (f '' s) := { ..is_add_group_hom.image_add_subgroup f.to_is_add_group_hom hs.to_is_add_subgroup, ..is_submonoid.image f.to_is_monoid_hom hs.to_is_submonoid, } lemma is_subring_set_range {R : Type u} {S : Type v} [ring R] [ring S] (f : R →+* S) : is_subring (set.range f) := { ..is_add_group_hom.range_add_subgroup f.to_is_add_group_hom, ..range.is_submonoid f.to_is_monoid_hom, } end ring_hom variables {cR : Type u} [comm_ring cR] lemma is_subring.inter {S₁ S₂ : set R} (hS₁ : is_subring S₁) (hS₂ : is_subring S₂) : is_subring (S₁ ∩ S₂) := { ..is_add_subgroup.inter hS₁.to_is_add_subgroup hS₂.to_is_add_subgroup, ..is_submonoid.inter hS₁.to_is_submonoid hS₂.to_is_submonoid } lemma is_subring.Inter {ι : Sort*} {S : ι → set R} (h : ∀ y : ι, is_subring (S y)) : is_subring (set.Inter S) := { ..is_add_subgroup.Inter (λ i, (h i).to_is_add_subgroup), ..is_submonoid.Inter (λ i, (h i).to_is_submonoid) } lemma is_subring_Union_of_directed {ι : Type*} [hι : nonempty ι] {s : ι → set R} (h : ∀ i, is_subring (s i)) (directed : ∀ i j, ∃ k, s i ⊆ s k ∧ s j ⊆ s k) : is_subring (⋃i, s i) := { to_is_add_subgroup := is_add_subgroup_Union_of_directed (λ i, (h i).to_is_add_subgroup) directed, to_is_submonoid := is_submonoid_Union_of_directed (λ i, (h i).to_is_submonoid) directed } namespace ring def closure (s : set R) := add_group.closure (monoid.closure s) variable {s : set R} local attribute [reducible] closure theorem exists_list_of_mem_closure {a : R} (h : a ∈ closure s) : (∃ L : list (list R), (∀ l ∈ L, ∀ x ∈ l, x ∈ s ∨ x = (-1:R)) ∧ (L.map list.prod).sum = a) := add_group.in_closure.rec_on h (λ x hx, match x, monoid.exists_list_of_mem_closure hx with | _, ⟨L, h1, rfl⟩ := ⟨[L], list.forall_mem_singleton.2 (λ r hr, or.inl (h1 r hr)), zero_add _⟩ end) ⟨[], list.forall_mem_nil _, rfl⟩ (λ b _ ih, match b, ih with | _, ⟨L1, h1, rfl⟩ := ⟨L1.map (list.cons (-1)), λ L2 h2, match L2, list.mem_map.1 h2 with | _, ⟨L3, h3, rfl⟩ := list.forall_mem_cons.2 ⟨or.inr rfl, h1 L3 h3⟩ end, by simp only [list.map_map, (∘), list.prod_cons, neg_one_mul]; exact list.rec_on L1 neg_zero.symm (λ hd tl ih, by rw [list.map_cons, list.sum_cons, ih, list.map_cons, list.sum_cons, neg_add])⟩ end) (λ r1 r2 hr1 hr2 ih1 ih2, match r1, r2, ih1, ih2 with | _, _, ⟨L1, h1, rfl⟩, ⟨L2, h2, rfl⟩ := ⟨L1 ++ L2, list.forall_mem_append.2 ⟨h1, h2⟩, by rw [list.map_append, list.sum_append]⟩ end) @[elab_as_eliminator] protected theorem in_closure.rec_on {C : R → Prop} {x : R} (hx : x ∈ closure s) (h1 : C 1) (hneg1 : C (-1)) (hs : ∀ z ∈ s, ∀ n, C n → C (z * n)) (ha : ∀ {x y}, C x → C y → C (x + y)) : C x := begin have h0 : C 0 := add_neg_self (1:R) ▸ ha h1 hneg1, rcases exists_list_of_mem_closure hx with ⟨L, HL, rfl⟩, clear hx, induction L with hd tl ih, { exact h0 }, rw list.forall_mem_cons at HL, suffices : C (list.prod hd), { rw [list.map_cons, list.sum_cons], exact ha this (ih HL.2) }, replace HL := HL.1, clear ih tl, suffices : ∃ L : list R, (∀ x ∈ L, x ∈ s) ∧ (list.prod hd = list.prod L ∨ list.prod hd = -list.prod L), { rcases this with ⟨L, HL', HP | HP⟩, { rw HP, clear HP HL hd, induction L with hd tl ih, { exact h1 }, rw list.forall_mem_cons at HL', rw list.prod_cons, exact hs _ HL'.1 _ (ih HL'.2) }, rw HP, clear HP HL hd, induction L with hd tl ih, { exact hneg1 }, rw [list.prod_cons, neg_mul_eq_mul_neg], rw list.forall_mem_cons at HL', exact hs _ HL'.1 _ (ih HL'.2) }, induction hd with hd tl ih, { exact ⟨[], list.forall_mem_nil _, or.inl rfl⟩ }, rw list.forall_mem_cons at HL, rcases ih HL.2 with ⟨L, HL', HP | HP⟩; cases HL.1 with hhd hhd, { exact ⟨hd :: L, list.forall_mem_cons.2 ⟨hhd, HL'⟩, or.inl $ by rw [list.prod_cons, list.prod_cons, HP]⟩ }, { exact ⟨L, HL', or.inr $ by rw [list.prod_cons, hhd, neg_one_mul, HP]⟩ }, { exact ⟨hd :: L, list.forall_mem_cons.2 ⟨hhd, HL'⟩, or.inr $ by rw [list.prod_cons, list.prod_cons, HP, neg_mul_eq_mul_neg]⟩ }, { exact ⟨L, HL', or.inl $ by rw [list.prod_cons, hhd, HP, neg_one_mul, neg_neg]⟩ } end lemma closure.is_subring : is_subring (closure s) := { one_mem := add_group.mem_closure $ is_submonoid.one_mem $ monoid.closure.is_submonoid _, mul_mem := λ a b ha hb, add_group.in_closure.rec_on hb ( λ c hc, add_group.in_closure.rec_on ha ( λ d hd, add_group.subset_closure ((monoid.closure.is_submonoid _).mul_mem hd hc)) ( (zero_mul c).symm ▸ (add_group.closure.is_add_subgroup _).zero_mem) ( λ d hd hdc, neg_mul_eq_neg_mul d c ▸ (add_group.closure.is_add_subgroup _).neg_mem hdc) ( λ d e hd he hdc hec, (add_mul d e c).symm ▸ ((add_group.closure.is_add_subgroup _).add_mem hdc hec))) ( (mul_zero a).symm ▸ (add_group.closure.is_add_subgroup _).zero_mem) ( λ c hc hac, neg_mul_eq_mul_neg a c ▸ (add_group.closure.is_add_subgroup _).neg_mem hac) ( λ c d hc hd hac had, (mul_add a c d).symm ▸ (add_group.closure.is_add_subgroup _).add_mem hac had), ..add_group.closure.is_add_subgroup _} theorem mem_closure {a : R} : a ∈ s → a ∈ closure s := add_group.mem_closure ∘ @monoid.subset_closure _ _ _ _ theorem subset_closure : s ⊆ closure s := λ _, mem_closure theorem closure_subset {t : set R} (ht : is_subring t) : s ⊆ t → closure s ⊆ t := (add_group.closure_subset ht.to_is_add_subgroup) ∘ (monoid.closure_subset ht.to_is_submonoid) theorem closure_subset_iff {s t : set R} (ht : is_subring t) : closure s ⊆ t ↔ s ⊆ t := (add_group.closure_subset_iff ht.to_is_add_subgroup).trans ⟨set.subset.trans monoid.subset_closure, monoid.closure_subset ht.to_is_submonoid⟩ theorem closure_mono {s t : set R} (H : s ⊆ t) : closure s ⊆ closure t := closure_subset closure.is_subring $ set.subset.trans H subset_closure lemma image_closure {S : Type*} [ring S] (f : R →+* S) (s : set R) : f '' closure s = closure (f '' s) := le_antisymm begin rintros _ ⟨x, hx, rfl⟩, apply in_closure.rec_on hx; intros, { rw [f.map_one], apply closure.is_subring.to_is_submonoid.one_mem }, { rw [f.map_neg, f.map_one], apply closure.is_subring.to_is_add_subgroup.neg_mem, apply closure.is_subring.to_is_submonoid.one_mem }, { rw [f.map_mul], apply closure.is_subring.to_is_submonoid.mul_mem; solve_by_elim [subset_closure, set.mem_image_of_mem] }, { rw [f.map_add], apply closure.is_subring.to_is_add_submonoid.add_mem, assumption' }, end (closure_subset (ring_hom.is_subring_image _ closure.is_subring) $ set.image_subset _ subset_closure) end ring
b4ff4276403d9b1f6794ec4e77bd67ce799df502
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/PrettyPrinter/Delaborator/SubExpr.lean
e09bddb5a62161f38573206dae8b31111e1ba05f
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach" ]
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
3,912
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich, Daniel Selsam, Wojciech Nawrocki -/ import Lean.Meta.Basic import Lean.SubExpr import Lean.Data.RBMap /-! # Subexpr utilities for delaborator. This file defines utilities for `MetaM` computations to traverse subexpressions of an expression in sync with the `Nat` "position" values that refer to them. -/ namespace Lean.PrettyPrinter.Delaborator abbrev OptionsPerPos := RBMap SubExpr.Pos Options compare namespace SubExpr open Lean.SubExpr variable {α : Type} [Inhabited α] variable {m : Type → Type} [Monad m] section Descend variable [MonadReaderOf SubExpr m] [MonadWithReaderOf SubExpr m] variable [MonadLiftT MetaM m] [MonadControlT MetaM m] variable [MonadLiftT IO m] def getExpr : m Expr := return (← readThe SubExpr).expr def getPos : m Pos := return (← readThe SubExpr).pos def descend (child : Expr) (childIdx : Nat) (x : m α) : m α := withTheReader SubExpr (fun cfg => { cfg with expr := child, pos := cfg.pos.push childIdx }) x def withAppFn (x : m α) : m α := do descend (← getExpr).appFn! 0 x def withAppArg (x : m α) : m α := do descend (← getExpr).appArg! 1 x def withType (x : m α) : m α := do descend (← Meta.inferType (← getExpr)) Pos.typeCoord x -- phantom positions for types partial def withAppFnArgs (xf : m α) (xa : α → m α) : m α := do if (← getExpr).isApp then let acc ← withAppFn (withAppFnArgs xf xa) withAppArg (xa acc) else xf def withBindingDomain (x : m α) : m α := do descend (← getExpr).bindingDomain! 0 x def withBindingBody (n : Name) (x : m α) : m α := do let e ← getExpr Meta.withLocalDecl n e.binderInfo e.bindingDomain! fun fvar => descend (e.bindingBody!.instantiate1 fvar) 1 x def withProj (x : m α) : m α := do let Expr.proj _ _ e ← getExpr | unreachable! descend e 0 x def withMDataExpr (x : m α) : m α := do let Expr.mdata _ e ← getExpr | unreachable! withTheReader SubExpr (fun ctx => { ctx with expr := e }) x def withLetVarType (x : m α) : m α := do let Expr.letE _ t _ _ _ ← getExpr | unreachable! descend t 0 x def withLetValue (x : m α) : m α := do let Expr.letE _ _ v _ _ ← getExpr | unreachable! descend v 1 x def withLetBody (x : m α) : m α := do let Expr.letE n t v b _ ← getExpr | unreachable! Meta.withLetDecl n t v fun fvar => let b := b.instantiate1 fvar descend b 2 x def withNaryFn (x : m α) : m α := do let e ← getExpr let newPos := (← getPos).pushNaryFn e.getAppNumArgs withTheReader SubExpr (fun cfg => { cfg with expr := e.getAppFn, pos := newPos }) x def withNaryArg (argIdx : Nat) (x : m α) : m α := do let e ← getExpr let args := e.getAppArgs let newPos := (← getPos).pushNaryArg args.size argIdx withTheReader SubExpr (fun cfg => { cfg with expr := args[argIdx]!, pos := newPos }) x end Descend structure HoleIterator where curr : Nat := 2 top : Nat := Pos.maxChildren deriving Inhabited section Hole variable {α : Type} [Inhabited α] variable {m : Type → Type} [Monad m] variable [MonadStateOf HoleIterator m] def HoleIterator.toPos (iter : HoleIterator) : Pos := iter.curr def HoleIterator.next (iter : HoleIterator) : HoleIterator := if (iter.curr+1) == iter.top then ⟨2*iter.top, Pos.maxChildren*iter.top⟩ else ⟨iter.curr+1, iter.top⟩ /-- The positioning scheme guarantees that there will be an infinite number of extra positions which are never used by `Expr`s. The `HoleIterator` always points at the next such "hole". We use these to attach additional `Elab.Info`. -/ def nextExtraPos : m Pos := do let iter ← getThe HoleIterator let pos := iter.toPos modifyThe HoleIterator HoleIterator.next return pos end Hole end SubExpr end Lean.PrettyPrinter.Delaborator
4b6ecc0e93a4247a6c797b9ef3bcdebb39968d99
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/meta/format_auto.lean
1e61535bed1f3531710c3b4d034cae5b24489b9e
[]
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
605
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.meta.options import Mathlib.Lean3Lib.init.function import Mathlib.Lean3Lib.init.data.to_string universes l namespace Mathlib inductive format.color where | red : format.color | green : format.color | orange : format.color | blue : format.color | pink : format.color | cyan : format.color | grey : format.color def format.color.to_string : format.color → string := sorry end Mathlib
875a2f40f256f0deae5586b78d0e372caa0faa2d
b7f22e51856f4989b970961f794f1c435f9b8f78
/library/tools/helper_tactics.lean
0a1bf7fcc3ee4eb029271e25c1053852633fde3a
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
391
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, Jeremy Avigad -- tools.helper_tactics -- ==================== -- Useful tactics. import logic.eq open tactic namespace helper_tactics definition apply_refl := apply eq.refl tactic_hint apply_refl end helper_tactics
f2d3ee2d64d244562e3617834d33cf608d1b253d
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/run/overload2.lean
cc9408d80ef44e75f93ec24d9d3f450f2a32e227
[ "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
715
lean
inductive F2 : Type | O : F2 | I : F2 namespace F2 definition add : F2 → F2 → F2 | O O := O | O I := I | I O := I | I I := O infix + := F2.add end F2 open F2 nat #reduce (1 : nat) + 1 #reduce (1 : nat) + (1 : nat) example : true := begin have H : (1 : nat) + (1 : nat) = 2, reflexivity, constructor end example : true := begin have H : 1 + 1 = 2, reflexivity, constructor end example : true := begin have H : (1:nat) + 1 = 2, reflexivity, constructor end example : true := begin have H : I + O = I, reflexivity, constructor end example : true := begin have H1 : I + O = I, reflexivity, have H2 : 1 + 0 = 1, reflexivity, have H3 : (1:int) + 0 = 1, reflexivity, constructor end
64f86cd2189be7df260515ffe951436d4e599a34
88fb7558b0636ec6b181f2a548ac11ad3919f8a5
/tests/lean/run/1315b.lean
a72fab19d667068ec10664d14ad024c87adefc5c
[ "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
1,069
lean
open nat def k : ℕ := 0 def fails : Π (n : ℕ) (m : ℕ), ℕ | 0 m := 0 | (succ n) m := match k with | 0 := 0 | (succ i) := let val := m+1 in match fails n val with | 0 := 0 | (succ l) := 0 end end def test (k : ℕ) : Π (n : ℕ) (m : ℕ), ℕ | 0 m := 0 | (succ n) m := match k with | 0 := 1 | (succ i) := let val := m+1 in match test n val with | 0 := 2 | (succ l) := 3 end end example (k m : ℕ) : test k 0 m = 0 := rfl example (m n : ℕ) : test 0 (succ n) m = 1 := rfl example (k m : ℕ) : test (succ k) 1 m = 2 := rfl example (k m : ℕ) : test (succ k) 2 m = 3 := rfl example (k m : ℕ) : test (succ k) 3 m = 3 := rfl open tactic run_cmd do t ← to_expr `(test._match_2) >>= infer_type, trace t, tactic.interactive.guard_expr_eq t `(nat → nat) example (k m n : ℕ) : test (succ k) (succ (succ n)) m = 3 := begin revert m, induction n with n', {intro, reflexivity}, {intro, simp [test] {zeta := ff}, dsimp, simp [ih_1], simp [nat.bit1_eq_succ_bit0, test]} end
0b8ed06cbe671912e7387feea9dce7509f54708c
9dc8cecdf3c4634764a18254e94d43da07142918
/src/topology/subset_properties.lean
627d55a1d3044ff58ff8e1448a6ce81168335231
[ "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
84,214
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Yury Kudryashov -/ import order.filter.pi import topology.bases import data.finset.order import data.set.accumulate import tactic.tfae import topology.bornology.basic /-! # Properties of subsets of topological spaces In this file we define various properties of subsets of a topological space, and some classes on topological spaces. ## Main definitions We define the following properties for sets in a topological space: * `is_compact`: each open cover has a finite subcover. This is defined in mathlib using filters. The main property of a compact set is `is_compact.elim_finite_subcover`. * `is_clopen`: a set that is both open and closed. * `is_irreducible`: a nonempty set that has contains no non-trivial pair of disjoint opens. See also the section below in the module doc. For each of these definitions (except for `is_clopen`), we also have a class stating that the whole space satisfies that property: `compact_space`, `irreducible_space` Furthermore, we have three more classes: * `locally_compact_space`: for every point `x`, every open neighborhood of `x` contains a compact neighborhood of `x`. The definition is formulated in terms of the neighborhood filter. * `sigma_compact_space`: a space that is the union of a countably many compact subspaces; * `noncompact_space`: a space that is not a compact space. ## On the definition of irreducible and connected sets/spaces In informal mathematics, irreducible spaces are assumed to be nonempty. We formalise the predicate without that assumption as `is_preirreducible`. In other words, the only difference is whether the empty space counts as irreducible. There are good reasons to consider the empty space to be “too simple to be simple” See also https://ncatlab.org/nlab/show/too+simple+to+be+simple, and in particular https://ncatlab.org/nlab/show/too+simple+to+be+simple#relationship_to_biased_definitions. -/ open set filter classical topological_space open_locale classical topological_space filter universes u v variables {α : Type u} {β : Type v} {ι : Type*} {π : ι → Type*} variables [topological_space α] [topological_space β] {s t : set α} /- compact sets -/ section compact /-- A set `s` is compact if for every nontrivial filter `f` that contains `s`, there exists `a ∈ s` such that every set of `f` meets every neighborhood of `a`. -/ def is_compact (s : set α) := ∀ ⦃f⦄ [ne_bot f], f ≤ 𝓟 s → ∃ a ∈ s, cluster_pt a f /-- The complement to a compact set belongs to a filter `f` if it belongs to each filter `𝓝 a ⊓ f`, `a ∈ s`. -/ lemma is_compact.compl_mem_sets (hs : is_compact s) {f : filter α} (hf : ∀ a ∈ s, sᶜ ∈ 𝓝 a ⊓ f) : sᶜ ∈ f := begin contrapose! hf, simp only [not_mem_iff_inf_principal_compl, compl_compl, inf_assoc, ← exists_prop] at hf ⊢, exact @hs _ hf inf_le_right end /-- The complement to a compact set belongs to a filter `f` if each `a ∈ s` has a neighborhood `t` within `s` such that `tᶜ` belongs to `f`. -/ lemma is_compact.compl_mem_sets_of_nhds_within (hs : is_compact s) {f : filter α} (hf : ∀ a ∈ s, ∃ t ∈ 𝓝[s] a, tᶜ ∈ f) : sᶜ ∈ f := begin refine hs.compl_mem_sets (λ a ha, _), rcases hf a ha with ⟨t, ht, hst⟩, replace ht := mem_inf_principal.1 ht, apply mem_inf_of_inter ht hst, rintros x ⟨h₁, h₂⟩ hs, exact h₂ (h₁ hs) end /-- If `p : set α → Prop` is stable under restriction and union, and each point `x` of a compact set `s` has a neighborhood `t` within `s` such that `p t`, then `p s` holds. -/ @[elab_as_eliminator] lemma is_compact.induction_on {s : set α} (hs : is_compact s) {p : set α → Prop} (he : p ∅) (hmono : ∀ ⦃s t⦄, s ⊆ t → p t → p s) (hunion : ∀ ⦃s t⦄, p s → p t → p (s ∪ t)) (hnhds : ∀ x ∈ s, ∃ t ∈ 𝓝[s] x, p t) : p s := let f : filter α := { sets := {t | p tᶜ}, univ_sets := by simpa, sets_of_superset := λ t₁ t₂ ht₁ ht, hmono (compl_subset_compl.2 ht) ht₁, inter_sets := λ t₁ t₂ ht₁ ht₂, by simp [compl_inter, hunion ht₁ ht₂] } in have sᶜ ∈ f, from hs.compl_mem_sets_of_nhds_within (by simpa using hnhds), by simpa /-- The intersection of a compact set and a closed set is a compact set. -/ lemma is_compact.inter_right (hs : is_compact s) (ht : is_closed t) : is_compact (s ∩ t) := begin introsI f hnf hstf, obtain ⟨a, hsa, ha⟩ : ∃ a ∈ s, cluster_pt a f := hs (le_trans hstf (le_principal_iff.2 (inter_subset_left _ _))), have : a ∈ t := (ht.mem_of_nhds_within_ne_bot $ ha.mono $ le_trans hstf (le_principal_iff.2 (inter_subset_right _ _))), exact ⟨a, ⟨hsa, this⟩, ha⟩ end /-- The intersection of a closed set and a compact set is a compact set. -/ lemma is_compact.inter_left (ht : is_compact t) (hs : is_closed s) : is_compact (s ∩ t) := inter_comm t s ▸ ht.inter_right hs /-- The set difference of a compact set and an open set is a compact set. -/ lemma is_compact.diff (hs : is_compact s) (ht : is_open t) : is_compact (s \ t) := hs.inter_right (is_closed_compl_iff.mpr ht) /-- A closed subset of a compact set is a compact set. -/ lemma compact_of_is_closed_subset (hs : is_compact s) (ht : is_closed t) (h : t ⊆ s) : is_compact t := inter_eq_self_of_subset_right h ▸ hs.inter_right ht lemma is_compact.image_of_continuous_on {f : α → β} (hs : is_compact s) (hf : continuous_on f s) : is_compact (f '' s) := begin intros l lne ls, have : ne_bot (l.comap f ⊓ 𝓟 s) := comap_inf_principal_ne_bot_of_image_mem lne (le_principal_iff.1 ls), obtain ⟨a, has, ha⟩ : ∃ a ∈ s, cluster_pt a (l.comap f ⊓ 𝓟 s) := @@hs this inf_le_right, use [f a, mem_image_of_mem f has], have : tendsto f (𝓝 a ⊓ (comap f l ⊓ 𝓟 s)) (𝓝 (f a) ⊓ l), { convert (hf a has).inf (@tendsto_comap _ _ f l) using 1, rw nhds_within, ac_refl }, exact @@tendsto.ne_bot _ this ha, end lemma is_compact.image {f : α → β} (hs : is_compact s) (hf : continuous f) : is_compact (f '' s) := hs.image_of_continuous_on hf.continuous_on lemma is_compact.adherence_nhdset {f : filter α} (hs : is_compact s) (hf₂ : f ≤ 𝓟 s) (ht₁ : is_open t) (ht₂ : ∀ a ∈ s, cluster_pt a f → a ∈ t) : t ∈ f := classical.by_cases mem_of_eq_bot $ assume : f ⊓ 𝓟 tᶜ ≠ ⊥, let ⟨a, ha, (hfa : cluster_pt a $ f ⊓ 𝓟 tᶜ)⟩ := @@hs ⟨this⟩ $ inf_le_of_left_le hf₂ in have a ∈ t, from ht₂ a ha (hfa.of_inf_left), have tᶜ ∩ t ∈ 𝓝[tᶜ] a, from inter_mem_nhds_within _ (is_open.mem_nhds ht₁ this), have A : 𝓝[tᶜ] a = ⊥, from empty_mem_iff_bot.1 $ compl_inter_self t ▸ this, have 𝓝[tᶜ] a ≠ ⊥, from hfa.of_inf_right.ne, absurd A this lemma is_compact_iff_ultrafilter_le_nhds : is_compact s ↔ (∀ f : ultrafilter α, ↑f ≤ 𝓟 s → ∃ a ∈ s, ↑f ≤ 𝓝 a) := begin refine (forall_ne_bot_le_iff _).trans _, { rintro f g hle ⟨a, has, haf⟩, exact ⟨a, has, haf.mono hle⟩ }, { simp only [ultrafilter.cluster_pt_iff] } end alias is_compact_iff_ultrafilter_le_nhds ↔ is_compact.ultrafilter_le_nhds _ /-- For every open directed cover of a compact set, there exists a single element of the cover which itself includes the set. -/ lemma is_compact.elim_directed_cover {ι : Type v} [hι : nonempty ι] (hs : is_compact s) (U : ι → set α) (hUo : ∀ i, is_open (U i)) (hsU : s ⊆ ⋃ i, U i) (hdU : directed (⊆) U) : ∃ i, s ⊆ U i := hι.elim $ λ i₀, is_compact.induction_on hs ⟨i₀, empty_subset _⟩ (λ s₁ s₂ hs ⟨i, hi⟩, ⟨i, subset.trans hs hi⟩) (λ s₁ s₂ ⟨i, hi⟩ ⟨j, hj⟩, let ⟨k, hki, hkj⟩ := hdU i j in ⟨k, union_subset (subset.trans hi hki) (subset.trans hj hkj)⟩) (λ x hx, let ⟨i, hi⟩ := mem_Union.1 (hsU hx) in ⟨U i, mem_nhds_within_of_mem_nhds (is_open.mem_nhds (hUo i) hi), i, subset.refl _⟩) /-- For every open cover of a compact set, there exists a finite subcover. -/ lemma is_compact.elim_finite_subcover {ι : Type v} (hs : is_compact s) (U : ι → set α) (hUo : ∀ i, is_open (U i)) (hsU : s ⊆ ⋃ i, U i) : ∃ t : finset ι, s ⊆ ⋃ i ∈ t, U i := hs.elim_directed_cover _ (λ t, is_open_bUnion $ λ i _, hUo i) (Union_eq_Union_finset U ▸ hsU) (directed_of_sup $ λ t₁ t₂ h, bUnion_subset_bUnion_left h) lemma is_compact.elim_nhds_subcover' (hs : is_compact s) (U : Π x ∈ s, set α) (hU : ∀ x ∈ s, U x ‹x ∈ s› ∈ 𝓝 x) : ∃ t : finset s, s ⊆ ⋃ x ∈ t, U (x : s) x.2 := (hs.elim_finite_subcover (λ x : s, interior (U x x.2)) (λ x, is_open_interior) (λ x hx, mem_Union.2 ⟨⟨x, hx⟩, mem_interior_iff_mem_nhds.2 $ hU _ _⟩)).imp $ λ t ht, subset.trans ht $ Union₂_mono $ λ _ _, interior_subset lemma is_compact.elim_nhds_subcover (hs : is_compact s) (U : α → set α) (hU : ∀ x ∈ s, U x ∈ 𝓝 x) : ∃ t : finset α, (∀ x ∈ t, x ∈ s) ∧ s ⊆ ⋃ x ∈ t, U x := let ⟨t, ht⟩ := hs.elim_nhds_subcover' (λ x _, U x) hU in ⟨t.image coe, λ x hx, let ⟨y, hyt, hyx⟩ := finset.mem_image.1 hx in hyx ▸ y.2, by rwa finset.set_bUnion_finset_image⟩ /-- For every family of closed sets whose intersection avoids a compact set, there exists a finite subfamily whose intersection avoids this compact set. -/ lemma is_compact.elim_finite_subfamily_closed {s : set α} {ι : Type v} (hs : is_compact s) (Z : ι → set α) (hZc : ∀ i, is_closed (Z i)) (hsZ : s ∩ (⋂ i, Z i) = ∅) : ∃ t : finset ι, s ∩ (⋂ i ∈ t, Z i) = ∅ := let ⟨t, ht⟩ := hs.elim_finite_subcover (λ i, (Z i)ᶜ) (λ i, (hZc i).is_open_compl) (by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, mem_Union, exists_prop, mem_inter_eq, not_and, iff_self, mem_Inter, mem_compl_eq] using hsZ) in ⟨t, by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, mem_Union, exists_prop, mem_inter_eq, not_and, iff_self, mem_Inter, mem_compl_eq] using ht⟩ /-- If `s` is a compact set in a topological space `α` and `f : ι → set α` is a locally finite family of sets, then `f i ∩ s` is nonempty only for a finitely many `i`. -/ lemma locally_finite.finite_nonempty_inter_compact {ι : Type*} {f : ι → set α} (hf : locally_finite f) {s : set α} (hs : is_compact s) : {i | (f i ∩ s).nonempty}.finite := begin choose U hxU hUf using hf, rcases hs.elim_nhds_subcover U (λ x _, hxU x) with ⟨t, -, hsU⟩, refine (t.finite_to_set.bUnion (λ x _, hUf x)).subset _, rintro i ⟨x, hx⟩, rcases mem_Union₂.1 (hsU hx.2) with ⟨c, hct, hcx⟩, exact mem_bUnion hct ⟨x, hx.1, hcx⟩ end /-- To show that a compact set intersects the intersection of a family of closed sets, it is sufficient to show that it intersects every finite subfamily. -/ lemma is_compact.inter_Inter_nonempty {s : set α} {ι : Type v} (hs : is_compact s) (Z : ι → set α) (hZc : ∀ i, is_closed (Z i)) (hsZ : ∀ t : finset ι, (s ∩ ⋂ i ∈ t, Z i).nonempty) : (s ∩ ⋂ i, Z i).nonempty := begin simp only [← ne_empty_iff_nonempty] at hsZ ⊢, apply mt (hs.elim_finite_subfamily_closed Z hZc), push_neg, exact hsZ end /-- Cantor's intersection theorem: the intersection of a directed family of nonempty compact closed sets is nonempty. -/ lemma is_compact.nonempty_Inter_of_directed_nonempty_compact_closed {ι : Type v} [hι : nonempty ι] (Z : ι → set α) (hZd : directed (⊇) Z) (hZn : ∀ i, (Z i).nonempty) (hZc : ∀ i, is_compact (Z i)) (hZcl : ∀ i, is_closed (Z i)) : (⋂ i, Z i).nonempty := begin apply hι.elim, intro i₀, let Z' := λ i, Z i ∩ Z i₀, suffices : (⋂ i, Z' i).nonempty, { exact this.mono (Inter_mono $ λ i, inter_subset_left (Z i) (Z i₀)) }, rw ← ne_empty_iff_nonempty, intro H, obtain ⟨t, ht⟩ : ∃ (t : finset ι), ((Z i₀) ∩ ⋂ (i ∈ t), Z' i) = ∅, from (hZc i₀).elim_finite_subfamily_closed Z' (assume i, is_closed.inter (hZcl i) (hZcl i₀)) (by rw [H, inter_empty]), obtain ⟨i₁, hi₁⟩ : ∃ i₁ : ι, Z i₁ ⊆ Z i₀ ∧ ∀ i ∈ t, Z i₁ ⊆ Z' i, { rcases directed.finset_le hZd t with ⟨i, hi⟩, rcases hZd i i₀ with ⟨i₁, hi₁, hi₁₀⟩, use [i₁, hi₁₀], intros j hj, exact subset_inter (subset.trans hi₁ (hi j hj)) hi₁₀ }, suffices : ((Z i₀) ∩ ⋂ (i ∈ t), Z' i).nonempty, { rw ← ne_empty_iff_nonempty at this, contradiction }, exact (hZn i₁).mono (subset_inter hi₁.left $ subset_Inter₂ hi₁.right), end /-- Cantor's intersection theorem for sequences indexed by `ℕ`: the intersection of a decreasing sequence of nonempty compact closed sets is nonempty. -/ lemma is_compact.nonempty_Inter_of_sequence_nonempty_compact_closed (Z : ℕ → set α) (hZd : ∀ i, Z (i+1) ⊆ Z i) (hZn : ∀ i, (Z i).nonempty) (hZ0 : is_compact (Z 0)) (hZcl : ∀ i, is_closed (Z i)) : (⋂ i, Z i).nonempty := have Zmono : antitone Z := antitone_nat_of_succ_le hZd, have hZd : directed (⊇) Z, from directed_of_sup Zmono, have ∀ i, Z i ⊆ Z 0, from assume i, Zmono $ zero_le i, have hZc : ∀ i, is_compact (Z i), from assume i, compact_of_is_closed_subset hZ0 (hZcl i) (this i), is_compact.nonempty_Inter_of_directed_nonempty_compact_closed Z hZd hZn hZc hZcl /-- For every open cover of a compact set, there exists a finite subcover. -/ lemma is_compact.elim_finite_subcover_image {b : set ι} {c : ι → set α} (hs : is_compact s) (hc₁ : ∀ i ∈ b, is_open (c i)) (hc₂ : s ⊆ ⋃ i ∈ b, c i) : ∃ b' ⊆ b, set.finite b' ∧ s ⊆ ⋃ i ∈ b', c i := begin rcases hs.elim_finite_subcover (λ i, c i : b → set α) _ _ with ⟨d, hd⟩; [skip, simpa using hc₁, simpa using hc₂], refine ⟨↑(d.image coe), _, finset.finite_to_set _, _⟩, { simp }, { rwa [finset.coe_image, bUnion_image] } end /-- A set `s` is compact if for every family of closed sets whose intersection avoids `s`, there exists a finite subfamily whose intersection avoids `s`. -/ theorem is_compact_of_finite_subfamily_closed (h : Π {ι : Type u} (Z : ι → (set α)), (∀ i, is_closed (Z i)) → s ∩ (⋂ i, Z i) = ∅ → (∃ (t : finset ι), s ∩ (⋂ i ∈ t, Z i) = ∅)) : is_compact s := assume f hfn hfs, classical.by_contradiction $ assume : ¬ (∃ x ∈ s, cluster_pt x f), have hf : ∀ x ∈ s, 𝓝 x ⊓ f = ⊥, by simpa only [cluster_pt, not_exists, not_not, ne_bot_iff], have ¬ ∃ x ∈ s, ∀ t ∈ f.sets, x ∈ closure t, from assume ⟨x, hxs, hx⟩, have ∅ ∈ 𝓝 x ⊓ f, by rw [empty_mem_iff_bot, hf x hxs], let ⟨t₁, ht₁, t₂, ht₂, ht⟩ := by rw [mem_inf_iff] at this; exact this in have ∅ ∈ 𝓝[t₂] x, by { rw [ht, inter_comm], exact inter_mem_nhds_within _ ht₁ }, have 𝓝[t₂] x = ⊥, by rwa [empty_mem_iff_bot] at this, by simp only [closure_eq_cluster_pts] at hx; exact (hx t₂ ht₂).ne this, let ⟨t, ht⟩ := h (λ i : f.sets, closure i.1) (λ i, is_closed_closure) (by simpa [eq_empty_iff_forall_not_mem, not_exists]) in have (⋂ i ∈ t, subtype.val i) ∈ f, from t.Inter_mem_sets.2 $ assume i hi, i.2, have s ∩ (⋂ i ∈ t, subtype.val i) ∈ f, from inter_mem (le_principal_iff.1 hfs) this, have ∅ ∈ f, from mem_of_superset this $ assume x ⟨hxs, hx⟩, let ⟨i, hit, hxi⟩ := (show ∃ i ∈ t, x ∉ closure (subtype.val i), by { rw [eq_empty_iff_forall_not_mem] at ht, simpa [hxs, not_forall] using ht x }) in have x ∈ closure i.val, from subset_closure (by { rw mem_Inter₂ at hx, exact hx i hit }), show false, from hxi this, hfn.ne $ by rwa [empty_mem_iff_bot] at this /-- A set `s` is compact if for every open cover of `s`, there exists a finite subcover. -/ lemma is_compact_of_finite_subcover (h : Π {ι : Type u} (U : ι → (set α)), (∀ i, is_open (U i)) → s ⊆ (⋃ i, U i) → (∃ (t : finset ι), s ⊆ (⋃ i ∈ t, U i))) : is_compact s := is_compact_of_finite_subfamily_closed $ assume ι Z hZc hsZ, let ⟨t, ht⟩ := h (λ i, (Z i)ᶜ) (assume i, is_open_compl_iff.mpr $ hZc i) (by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, mem_Union, exists_prop, mem_inter_eq, not_and, iff_self, mem_Inter, mem_compl_eq] using hsZ) in ⟨t, by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, mem_Union, exists_prop, mem_inter_eq, not_and, iff_self, mem_Inter, mem_compl_eq] using ht⟩ /-- A set `s` is compact if and only if for every open cover of `s`, there exists a finite subcover. -/ lemma is_compact_iff_finite_subcover : is_compact s ↔ (Π {ι : Type u} (U : ι → (set α)), (∀ i, is_open (U i)) → s ⊆ (⋃ i, U i) → (∃ (t : finset ι), s ⊆ (⋃ i ∈ t, U i))) := ⟨assume hs ι, hs.elim_finite_subcover, is_compact_of_finite_subcover⟩ /-- A set `s` is compact if and only if for every family of closed sets whose intersection avoids `s`, there exists a finite subfamily whose intersection avoids `s`. -/ theorem is_compact_iff_finite_subfamily_closed : is_compact s ↔ (Π {ι : Type u} (Z : ι → (set α)), (∀ i, is_closed (Z i)) → s ∩ (⋂ i, Z i) = ∅ → (∃ (t : finset ι), s ∩ (⋂ i ∈ t, Z i) = ∅)) := ⟨assume hs ι, hs.elim_finite_subfamily_closed, is_compact_of_finite_subfamily_closed⟩ /-- To show that `∀ y ∈ K, P x y` holds for `x` close enough to `x₀` when `K` is compact, it is sufficient to show that for all `y₀ ∈ K` there `P x y` holds for `(x, y)` close enough to `(x₀, y₀)`. -/ lemma is_compact.eventually_forall_of_forall_eventually {x₀ : α} {K : set β} (hK : is_compact K) {P : α → β → Prop} (hP : ∀ y ∈ K, ∀ᶠ (z : α × β) in 𝓝 (x₀, y), P z.1 z.2): ∀ᶠ x in 𝓝 x₀, ∀ y ∈ K, P x y := begin refine hK.induction_on _ _ _ _, { exact eventually_of_forall (λ x y, false.elim) }, { intros s t hst ht, refine ht.mono (λ x h y hys, h y $ hst hys) }, { intros s t hs ht, filter_upwards [hs, ht], rintro x h1 h2 y (hys|hyt), exacts [h1 y hys, h2 y hyt] }, { intros y hyK, specialize hP y hyK, rw [nhds_prod_eq, eventually_prod_iff] at hP, rcases hP with ⟨p, hp, q, hq, hpq⟩, exact ⟨{y | q y}, mem_nhds_within_of_mem_nhds hq, eventually_of_mem hp @hpq⟩ } end @[simp] lemma is_compact_empty : is_compact (∅ : set α) := assume f hnf hsf, not.elim hnf.ne $ empty_mem_iff_bot.1 $ le_principal_iff.1 hsf @[simp] lemma is_compact_singleton {a : α} : is_compact ({a} : set α) := λ f hf hfa, ⟨a, rfl, cluster_pt.of_le_nhds' (hfa.trans $ by simpa only [principal_singleton] using pure_le_nhds a) hf⟩ lemma set.subsingleton.is_compact {s : set α} (hs : s.subsingleton) : is_compact s := subsingleton.induction_on hs is_compact_empty $ λ x, is_compact_singleton lemma set.finite.compact_bUnion {s : set ι} {f : ι → set α} (hs : s.finite) (hf : ∀ i ∈ s, is_compact (f i)) : is_compact (⋃ i ∈ s, f i) := is_compact_of_finite_subcover $ assume ι U hUo hsU, have ∀ i : subtype s, ∃ t : finset ι, f i ⊆ (⋃ j ∈ t, U j), from assume ⟨i, hi⟩, (hf i hi).elim_finite_subcover _ hUo (calc f i ⊆ ⋃ i ∈ s, f i : subset_bUnion_of_mem hi ... ⊆ ⋃ j, U j : hsU), let ⟨finite_subcovers, h⟩ := axiom_of_choice this in by haveI : fintype (subtype s) := hs.fintype; exact let t := finset.bUnion finset.univ finite_subcovers in have (⋃ i ∈ s, f i) ⊆ (⋃ i ∈ t, U i), from Union₂_subset $ assume i hi, calc f i ⊆ (⋃ j ∈ finite_subcovers ⟨i, hi⟩, U j) : (h ⟨i, hi⟩) ... ⊆ (⋃ j ∈ t, U j) : bUnion_subset_bUnion_left $ assume j hj, finset.mem_bUnion.mpr ⟨_, finset.mem_univ _, hj⟩, ⟨t, this⟩ lemma finset.compact_bUnion (s : finset ι) {f : ι → set α} (hf : ∀ i ∈ s, is_compact (f i)) : is_compact (⋃ i ∈ s, f i) := s.finite_to_set.compact_bUnion hf lemma compact_accumulate {K : ℕ → set α} (hK : ∀ n, is_compact (K n)) (n : ℕ) : is_compact (accumulate K n) := (finite_le_nat n).compact_bUnion $ λ k _, hK k lemma compact_Union {f : ι → set α} [finite ι] (h : ∀ i, is_compact (f i)) : is_compact (⋃ i, f i) := by rw ← bUnion_univ; exact finite_univ.compact_bUnion (λ i _, h i) lemma set.finite.is_compact (hs : s.finite) : is_compact s := bUnion_of_singleton s ▸ hs.compact_bUnion (λ _ _, is_compact_singleton) lemma is_compact.finite_of_discrete [discrete_topology α] {s : set α} (hs : is_compact s) : s.finite := begin have : ∀ x : α, ({x} : set α) ∈ 𝓝 x, by simp [nhds_discrete], rcases hs.elim_nhds_subcover (λ x, {x}) (λ x hx, this x) with ⟨t, hts, hst⟩, simp only [← t.set_bUnion_coe, bUnion_of_singleton] at hst, exact t.finite_to_set.subset hst end lemma is_compact_iff_finite [discrete_topology α] {s : set α} : is_compact s ↔ s.finite := ⟨λ h, h.finite_of_discrete, λ h, h.is_compact⟩ lemma is_compact.union (hs : is_compact s) (ht : is_compact t) : is_compact (s ∪ t) := by rw union_eq_Union; exact compact_Union (λ b, by cases b; assumption) lemma is_compact.insert (hs : is_compact s) (a) : is_compact (insert a s) := is_compact_singleton.union hs /-- If `V : ι → set α` is a decreasing family of closed compact sets then any neighborhood of `⋂ i, V i` contains some `V i`. We assume each `V i` is compact *and* closed because `α` is not assumed to be Hausdorff. See `exists_subset_nhd_of_compact` for version assuming this. -/ lemma exists_subset_nhd_of_compact' {ι : Type*} [nonempty ι] {V : ι → set α} (hV : directed (⊇) V) (hV_cpct : ∀ i, is_compact (V i)) (hV_closed : ∀ i, is_closed (V i)) {U : set α} (hU : ∀ x ∈ ⋂ i, V i, U ∈ 𝓝 x) : ∃ i, V i ⊆ U := begin obtain ⟨W, hsubW, W_op, hWU⟩ := exists_open_set_nhds hU, rsuffices ⟨i, hi⟩ : ∃ i, V i ⊆ W, { exact ⟨i, hi.trans hWU⟩ }, by_contra' H, replace H : ∀ i, (V i ∩ Wᶜ).nonempty := λ i, set.inter_compl_nonempty_iff.mpr (H i), have : (⋂ i, V i ∩ Wᶜ).nonempty, { refine is_compact.nonempty_Inter_of_directed_nonempty_compact_closed _ (λ i j, _) H (λ i, (hV_cpct i).inter_right W_op.is_closed_compl) (λ i, (hV_closed i).inter W_op.is_closed_compl), rcases hV i j with ⟨k, hki, hkj⟩, refine ⟨k, ⟨λ x, _, λ x, _⟩⟩ ; simp only [and_imp, mem_inter_eq, mem_compl_eq] ; tauto }, have : ¬ (⋂ (i : ι), V i) ⊆ W, by simpa [← Inter_inter, inter_compl_nonempty_iff], contradiction end /-- If `α` has a basis consisting of compact opens, then an open set in `α` is compact open iff it is a finite union of some elements in the basis -/ lemma is_compact_open_iff_eq_finite_Union_of_is_topological_basis (b : ι → set α) (hb : is_topological_basis (set.range b)) (hb' : ∀ i, is_compact (b i)) (U : set α) : is_compact U ∧ is_open U ↔ ∃ (s : set ι), s.finite ∧ U = ⋃ i ∈ s, b i := begin classical, split, { rintro ⟨h₁, h₂⟩, obtain ⟨β, f, e, hf⟩ := hb.open_eq_Union h₂, choose f' hf' using hf, have : b ∘ f' = f := funext hf', subst this, obtain ⟨t, ht⟩ := h₁.elim_finite_subcover (b ∘ f') (λ i, hb.is_open (set.mem_range_self _)) (by rw e), refine ⟨t.image f', set.finite.intro infer_instance, le_antisymm _ _⟩, { refine set.subset.trans ht _, simp only [set.Union_subset_iff, coe_coe], intros i hi, erw ← set.Union_subtype (λ x : ι, x ∈ t.image f') (λ i, b i.1), exact set.subset_Union (λ i : t.image f', b i) ⟨_, finset.mem_image_of_mem _ hi⟩ }, { apply set.Union₂_subset, rintro i hi, obtain ⟨j, hj, rfl⟩ := finset.mem_image.mp hi, rw e, exact set.subset_Union (b ∘ f') j } }, { rintro ⟨s, hs, rfl⟩, split, { exact hs.compact_bUnion (λ i _, hb' i) }, { apply is_open_bUnion, intros i hi, exact hb.is_open (set.mem_range_self _) } }, end namespace filter /-- `filter.cocompact` is the filter generated by complements to compact sets. -/ def cocompact (α : Type*) [topological_space α] : filter α := ⨅ (s : set α) (hs : is_compact s), 𝓟 (sᶜ) lemma has_basis_cocompact : (cocompact α).has_basis is_compact compl := has_basis_binfi_principal' (λ s hs t ht, ⟨s ∪ t, hs.union ht, compl_subset_compl.2 (subset_union_left s t), compl_subset_compl.2 (subset_union_right s t)⟩) ⟨∅, is_compact_empty⟩ lemma mem_cocompact : s ∈ cocompact α ↔ ∃ t, is_compact t ∧ tᶜ ⊆ s := has_basis_cocompact.mem_iff.trans $ exists_congr $ λ t, exists_prop lemma mem_cocompact' : s ∈ cocompact α ↔ ∃ t, is_compact t ∧ sᶜ ⊆ t := mem_cocompact.trans $ exists_congr $ λ t, and_congr_right $ λ ht, compl_subset_comm lemma _root_.is_compact.compl_mem_cocompact (hs : is_compact s) : sᶜ ∈ filter.cocompact α := has_basis_cocompact.mem_of_mem hs lemma cocompact_le_cofinite : cocompact α ≤ cofinite := λ s hs, compl_compl s ▸ hs.is_compact.compl_mem_cocompact lemma cocompact_eq_cofinite (α : Type*) [topological_space α] [discrete_topology α] : cocompact α = cofinite := has_basis_cocompact.eq_of_same_basis $ by { convert has_basis_cofinite, ext s, exact is_compact_iff_finite } @[simp] lemma _root_.nat.cocompact_eq : cocompact ℕ = at_top := (cocompact_eq_cofinite ℕ).trans nat.cofinite_eq_at_top lemma tendsto.is_compact_insert_range_of_cocompact {f : α → β} {b} (hf : tendsto f (cocompact α) (𝓝 b)) (hfc : continuous f) : is_compact (insert b (range f)) := begin introsI l hne hle, by_cases hb : cluster_pt b l, { exact ⟨b, or.inl rfl, hb⟩ }, simp only [cluster_pt_iff, not_forall, ← not_disjoint_iff_nonempty_inter, not_not] at hb, rcases hb with ⟨s, hsb, t, htl, hd⟩, rcases mem_cocompact.1 (hf hsb) with ⟨K, hKc, hKs⟩, have : f '' K ∈ l, { filter_upwards [htl, le_principal_iff.1 hle] with y hyt hyf, rcases hyf with (rfl|⟨x, rfl⟩), exacts [(hd ⟨mem_of_mem_nhds hsb, hyt⟩).elim, mem_image_of_mem _ (not_not.1 $ λ hxK, hd ⟨hKs hxK, hyt⟩)] }, rcases hKc.image hfc (le_principal_iff.2 this) with ⟨y, hy, hyl⟩, exact ⟨y, or.inr $ image_subset_range _ _ hy, hyl⟩ end lemma tendsto.is_compact_insert_range_of_cofinite {f : ι → α} {a} (hf : tendsto f cofinite (𝓝 a)) : is_compact (insert a (range f)) := begin letI : topological_space ι := ⊥, haveI : discrete_topology ι := ⟨rfl⟩, rw ← cocompact_eq_cofinite at hf, exact hf.is_compact_insert_range_of_cocompact continuous_of_discrete_topology end lemma tendsto.is_compact_insert_range {f : ℕ → α} {a} (hf : tendsto f at_top (𝓝 a)) : is_compact (insert a (range f)) := filter.tendsto.is_compact_insert_range_of_cofinite $ nat.cofinite_eq_at_top.symm ▸ hf /-- `filter.coclosed_compact` is the filter generated by complements to closed compact sets. In a Hausdorff space, this is the same as `filter.cocompact`. -/ def coclosed_compact (α : Type*) [topological_space α] : filter α := ⨅ (s : set α) (h₁ : is_closed s) (h₂ : is_compact s), 𝓟 (sᶜ) lemma has_basis_coclosed_compact : (filter.coclosed_compact α).has_basis (λ s, is_closed s ∧ is_compact s) compl := begin simp only [filter.coclosed_compact, infi_and'], refine has_basis_binfi_principal' _ ⟨∅, is_closed_empty, is_compact_empty⟩, rintro s ⟨hs₁, hs₂⟩ t ⟨ht₁, ht₂⟩, exact ⟨s ∪ t, ⟨⟨hs₁.union ht₁, hs₂.union ht₂⟩, compl_subset_compl.2 (subset_union_left _ _), compl_subset_compl.2 (subset_union_right _ _)⟩⟩ end lemma mem_coclosed_compact : s ∈ coclosed_compact α ↔ ∃ t, is_closed t ∧ is_compact t ∧ tᶜ ⊆ s := by simp [has_basis_coclosed_compact.mem_iff, and_assoc] lemma mem_coclosed_compact' : s ∈ coclosed_compact α ↔ ∃ t, is_closed t ∧ is_compact t ∧ sᶜ ⊆ t := by simp only [mem_coclosed_compact, compl_subset_comm] lemma cocompact_le_coclosed_compact : cocompact α ≤ coclosed_compact α := infi_mono $ λ s, le_infi $ λ _, le_rfl lemma _root_.is_compact.compl_mem_coclosed_compact_of_is_closed (hs : is_compact s) (hs' : is_closed s) : sᶜ ∈ filter.coclosed_compact α := has_basis_coclosed_compact.mem_of_mem ⟨hs', hs⟩ end filter namespace bornology variable (α) /-- Sets that are contained in a compact set form a bornology. Its `cobounded` filter is `filter.cocompact`. See also `bornology.relatively_compact` the bornology of sets with compact closure. -/ def in_compact : bornology α := { cobounded := filter.cocompact α, le_cofinite := filter.cocompact_le_cofinite } variable {α} lemma in_compact.is_bounded_iff : @is_bounded _ (in_compact α) s ↔ ∃ t, is_compact t ∧ s ⊆ t := begin change sᶜ ∈ filter.cocompact α ↔ _, rw filter.mem_cocompact, simp end end bornology section tube_lemma /-- `nhds_contain_boxes s t` means that any open neighborhood of `s × t` in `α × β` includes a product of an open neighborhood of `s` by an open neighborhood of `t`. -/ def nhds_contain_boxes (s : set α) (t : set β) : Prop := ∀ (n : set (α × β)) (hn : is_open n) (hp : s ×ˢ t ⊆ n), ∃ (u : set α) (v : set β), is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ u ×ˢ v ⊆ n lemma nhds_contain_boxes.symm {s : set α} {t : set β} : nhds_contain_boxes s t → nhds_contain_boxes t s := assume H n hn hp, let ⟨u, v, uo, vo, su, tv, p⟩ := H (prod.swap ⁻¹' n) (hn.preimage continuous_swap) (by rwa [←image_subset_iff, image_swap_prod]) in ⟨v, u, vo, uo, tv, su, by rwa [←image_subset_iff, image_swap_prod] at p⟩ lemma nhds_contain_boxes.comm {s : set α} {t : set β} : nhds_contain_boxes s t ↔ nhds_contain_boxes t s := iff.intro nhds_contain_boxes.symm nhds_contain_boxes.symm lemma nhds_contain_boxes_of_singleton {x : α} {y : β} : nhds_contain_boxes ({x} : set α) ({y} : set β) := assume n hn hp, let ⟨u, v, uo, vo, xu, yv, hp'⟩ := is_open_prod_iff.mp hn x y (hp $ by simp) in ⟨u, v, uo, vo, by simpa, by simpa, hp'⟩ lemma nhds_contain_boxes_of_compact {s : set α} (hs : is_compact s) (t : set β) (H : ∀ x ∈ s, nhds_contain_boxes ({x} : set α) t) : nhds_contain_boxes s t := assume n hn hp, have ∀ x : s, ∃ uv : set α × set β, is_open uv.1 ∧ is_open uv.2 ∧ {↑x} ⊆ uv.1 ∧ t ⊆ uv.2 ∧ uv.1 ×ˢ uv.2 ⊆ n, from assume ⟨x, hx⟩, have ({x} : set α) ×ˢ t ⊆ n, from subset.trans (prod_mono (by simpa) subset.rfl) hp, let ⟨ux,vx,H1⟩ := H x hx n hn this in ⟨⟨ux,vx⟩,H1⟩, let ⟨uvs, h⟩ := classical.axiom_of_choice this in have us_cover : s ⊆ ⋃ i, (uvs i).1, from assume x hx, subset_Union _ ⟨x,hx⟩ (by simpa using (h ⟨x,hx⟩).2.2.1), let ⟨s0, s0_cover⟩ := hs.elim_finite_subcover _ (λi, (h i).1) us_cover in let u := ⋃(i ∈ s0), (uvs i).1 in let v := ⋂(i ∈ s0), (uvs i).2 in have is_open u, from is_open_bUnion (λi _, (h i).1), have is_open v, from is_open_bInter s0.finite_to_set (λi _, (h i).2.1), have t ⊆ v, from subset_Inter₂ (λi _, (h i).2.2.2.1), have u ×ˢ v ⊆ n, from assume ⟨x',y'⟩ ⟨hx',hy'⟩, have ∃ i ∈ s0, x' ∈ (uvs i).1, by simpa using hx', let ⟨i,is0,hi⟩ := this in (h i).2.2.2.2 ⟨hi, (bInter_subset_of_mem is0 : v ⊆ (uvs i).2) hy'⟩, ⟨u, v, ‹is_open u›, ‹is_open v›, s0_cover, ‹t ⊆ v›, ‹u ×ˢ v ⊆ n›⟩ /-- If `s` and `t` are compact sets and `n` is an open neighborhood of `s × t`, then there exist open neighborhoods `u ⊇ s` and `v ⊇ t` such that `u × v ⊆ n`. -/ lemma generalized_tube_lemma {s : set α} (hs : is_compact s) {t : set β} (ht : is_compact t) {n : set (α × β)} (hn : is_open n) (hp : s ×ˢ t ⊆ n) : ∃ (u : set α) (v : set β), is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ u ×ˢ v ⊆ n := have _, from nhds_contain_boxes_of_compact hs t $ assume x _, nhds_contain_boxes.symm $ nhds_contain_boxes_of_compact ht {x} $ assume y _, nhds_contain_boxes_of_singleton, this n hn hp end tube_lemma /-- Type class for compact spaces. Separation is sometimes included in the definition, especially in the French literature, but we do not include it here. -/ class compact_space (α : Type*) [topological_space α] : Prop := (compact_univ : is_compact (univ : set α)) @[priority 10] -- see Note [lower instance priority] instance subsingleton.compact_space [subsingleton α] : compact_space α := ⟨subsingleton_univ.is_compact⟩ lemma is_compact_univ_iff : is_compact (univ : set α) ↔ compact_space α := ⟨λ h, ⟨h⟩, λ h, h.1⟩ lemma compact_univ [h : compact_space α] : is_compact (univ : set α) := h.compact_univ lemma cluster_point_of_compact [compact_space α] (f : filter α) [ne_bot f] : ∃ x, cluster_pt x f := by simpa using compact_univ (show f ≤ 𝓟 univ, by simp) lemma compact_space.elim_nhds_subcover [compact_space α] (U : α → set α) (hU : ∀ x, U x ∈ 𝓝 x) : ∃ t : finset α, (⋃ x ∈ t, U x) = ⊤ := begin obtain ⟨t, -, s⟩ := is_compact.elim_nhds_subcover compact_univ U (λ x m, hU x), exact ⟨t, by { rw eq_top_iff, exact s }⟩, end theorem compact_space_of_finite_subfamily_closed (h : Π {ι : Type u} (Z : ι → (set α)), (∀ i, is_closed (Z i)) → (⋂ i, Z i) = ∅ → ∃ (t : finset ι), (⋂ i ∈ t, Z i) = ∅) : compact_space α := { compact_univ := begin apply is_compact_of_finite_subfamily_closed, intros ι Z, specialize h Z, simpa using h end } lemma is_closed.is_compact [compact_space α] {s : set α} (h : is_closed s) : is_compact s := compact_of_is_closed_subset compact_univ h (subset_univ _) /-- `α` is a noncompact topological space if it not a compact space. -/ class noncompact_space (α : Type*) [topological_space α] : Prop := (noncompact_univ [] : ¬is_compact (univ : set α)) export noncompact_space (noncompact_univ) lemma is_compact.ne_univ [noncompact_space α] {s : set α} (hs : is_compact s) : s ≠ univ := λ h, noncompact_univ α (h ▸ hs) instance [noncompact_space α] : ne_bot (filter.cocompact α) := begin refine filter.has_basis_cocompact.ne_bot_iff.2 (λ s hs, _), contrapose hs, rw [not_nonempty_iff_eq_empty, compl_empty_iff] at hs, rw hs, exact noncompact_univ α end @[simp] lemma filter.cocompact_eq_bot [compact_space α] : filter.cocompact α = ⊥ := filter.has_basis_cocompact.eq_bot_iff.mpr ⟨set.univ, compact_univ, set.compl_univ⟩ instance [noncompact_space α] : ne_bot (filter.coclosed_compact α) := ne_bot_of_le filter.cocompact_le_coclosed_compact lemma noncompact_space_of_ne_bot (h : ne_bot (filter.cocompact α)) : noncompact_space α := ⟨λ h', (filter.nonempty_of_mem h'.compl_mem_cocompact).ne_empty compl_univ⟩ lemma filter.cocompact_ne_bot_iff : ne_bot (filter.cocompact α) ↔ noncompact_space α := ⟨noncompact_space_of_ne_bot, @filter.cocompact.filter.ne_bot _ _⟩ lemma not_compact_space_iff : ¬compact_space α ↔ noncompact_space α := ⟨λ h₁, ⟨λ h₂, h₁ ⟨h₂⟩⟩, λ ⟨h₁⟩ ⟨h₂⟩, h₁ h₂⟩ instance : noncompact_space ℤ := noncompact_space_of_ne_bot $ by simp only [filter.cocompact_eq_cofinite, filter.cofinite_ne_bot] -- Note: We can't make this into an instance because it loops with `finite.compact_space`. /-- A compact discrete space is finite. -/ lemma finite_of_compact_of_discrete [compact_space α] [discrete_topology α] : finite α := finite.of_finite_univ $ compact_univ.finite_of_discrete lemma finite_cover_nhds_interior [compact_space α] {U : α → set α} (hU : ∀ x, U x ∈ 𝓝 x) : ∃ t : finset α, (⋃ x ∈ t, interior (U x)) = univ := let ⟨t, ht⟩ := compact_univ.elim_finite_subcover (λ x, interior (U x)) (λ x, is_open_interior) (λ x _, mem_Union.2 ⟨x, mem_interior_iff_mem_nhds.2 (hU x)⟩) in ⟨t, univ_subset_iff.1 ht⟩ lemma finite_cover_nhds [compact_space α] {U : α → set α} (hU : ∀ x, U x ∈ 𝓝 x) : ∃ t : finset α, (⋃ x ∈ t, U x) = univ := let ⟨t, ht⟩ := finite_cover_nhds_interior hU in ⟨t, univ_subset_iff.1 $ ht.symm.subset.trans $ Union₂_mono $ λ x hx, interior_subset⟩ /-- If `α` is a compact space, then a locally finite family of sets of `α` can have only finitely many nonempty elements. -/ lemma locally_finite.finite_nonempty_of_compact {ι : Type*} [compact_space α] {f : ι → set α} (hf : locally_finite f) : {i | (f i).nonempty}.finite := by simpa only [inter_univ] using hf.finite_nonempty_inter_compact compact_univ /-- If `α` is a compact space, then a locally finite family of nonempty sets of `α` can have only finitely many elements, `set.finite` version. -/ lemma locally_finite.finite_of_compact {ι : Type*} [compact_space α] {f : ι → set α} (hf : locally_finite f) (hne : ∀ i, (f i).nonempty) : (univ : set ι).finite := by simpa only [hne] using hf.finite_nonempty_of_compact /-- If `α` is a compact space, then a locally finite family of nonempty sets of `α` can have only finitely many elements, `fintype` version. -/ noncomputable def locally_finite.fintype_of_compact {ι : Type*} [compact_space α] {f : ι → set α} (hf : locally_finite f) (hne : ∀ i, (f i).nonempty) : fintype ι := fintype_of_finite_univ (hf.finite_of_compact hne) /-- The comap of the cocompact filter on `β` by a continuous function `f : α → β` is less than or equal to the cocompact filter on `α`. This is a reformulation of the fact that images of compact sets are compact. -/ lemma filter.comap_cocompact_le {f : α → β} (hf : continuous f) : (filter.cocompact β).comap f ≤ filter.cocompact α := begin rw (filter.has_basis_cocompact.comap f).le_basis_iff filter.has_basis_cocompact, intros t ht, refine ⟨f '' t, ht.image hf, _⟩, simpa using t.subset_preimage_image f end lemma is_compact_range [compact_space α] {f : α → β} (hf : continuous f) : is_compact (range f) := by rw ← image_univ; exact compact_univ.image hf lemma is_compact_diagonal [compact_space α] : is_compact (diagonal α) := @range_diag α ▸ is_compact_range (continuous_id.prod_mk continuous_id) /-- If X is is_compact then pr₂ : X × Y → Y is a closed map -/ theorem is_closed_proj_of_is_compact {X : Type*} [topological_space X] [compact_space X] {Y : Type*} [topological_space Y] : is_closed_map (prod.snd : X × Y → Y) := begin set πX := (prod.fst : X × Y → X), set πY := (prod.snd : X × Y → Y), assume C (hC : is_closed C), rw is_closed_iff_cluster_pt at hC ⊢, assume y (y_closure : cluster_pt y $ 𝓟 (πY '' C)), haveI : ne_bot (map πX (comap πY (𝓝 y) ⊓ 𝓟 C)), { suffices : ne_bot (map πY (comap πY (𝓝 y) ⊓ 𝓟 C)), by simpa only [map_ne_bot_iff], convert y_closure, calc map πY (comap πY (𝓝 y) ⊓ 𝓟 C) = 𝓝 y ⊓ map πY (𝓟 C) : filter.push_pull' _ _ _ ... = 𝓝 y ⊓ 𝓟 (πY '' C) : by rw map_principal }, obtain ⟨x, hx⟩ : ∃ x, cluster_pt x (map πX (comap πY (𝓝 y) ⊓ 𝓟 C)), from cluster_point_of_compact _, refine ⟨⟨x, y⟩, _, by simp [πY]⟩, apply hC, rw [cluster_pt, ← filter.map_ne_bot_iff πX], convert hx, calc map πX (𝓝 (x, y) ⊓ 𝓟 C) = map πX (comap πX (𝓝 x) ⊓ comap πY (𝓝 y) ⊓ 𝓟 C) : by rw [nhds_prod_eq, filter.prod] ... = map πX (comap πY (𝓝 y) ⊓ 𝓟 C ⊓ comap πX (𝓝 x)) : by ac_refl ... = map πX (comap πY (𝓝 y) ⊓ 𝓟 C) ⊓ 𝓝 x : by rw filter.push_pull ... = 𝓝 x ⊓ map πX (comap πY (𝓝 y) ⊓ 𝓟 C) : by rw inf_comm end lemma exists_subset_nhd_of_compact_space [compact_space α] {ι : Type*} [nonempty ι] {V : ι → set α} (hV : directed (⊇) V) (hV_closed : ∀ i, is_closed (V i)) {U : set α} (hU : ∀ x ∈ ⋂ i, V i, U ∈ 𝓝 x) : ∃ i, V i ⊆ U := exists_subset_nhd_of_compact' hV (λ i, (hV_closed i).is_compact) hV_closed hU /-- If `f : α → β` is an `inducing` map, then the image `f '' s` of a set `s` is compact if and only if the set `s` is closed. -/ lemma inducing.is_compact_iff {f : α → β} (hf : inducing f) {s : set α} : is_compact (f '' s) ↔ is_compact s := begin refine ⟨_, λ hs, hs.image hf.continuous⟩, introsI hs F F_ne_bot F_le, obtain ⟨_, ⟨x, x_in : x ∈ s, rfl⟩, hx : cluster_pt (f x) (map f F)⟩ := hs (calc map f F ≤ map f (𝓟 s) : map_mono F_le ... = 𝓟 (f '' s) : map_principal), use [x, x_in], suffices : (map f (𝓝 x ⊓ F)).ne_bot, by simpa [filter.map_ne_bot_iff], rwa calc map f (𝓝 x ⊓ F) = map f ((comap f $ 𝓝 $ f x) ⊓ F) : by rw hf.nhds_eq_comap ... = 𝓝 (f x) ⊓ map f F : filter.push_pull' _ _ _ end /-- If `f : α → β` is an `embedding` (or more generally, an `inducing` map, see `inducing.is_compact_iff`), then the image `f '' s` of a set `s` is compact if and only if the set `s` is closed. -/ lemma embedding.is_compact_iff_is_compact_image {f : α → β} (hf : embedding f) : is_compact s ↔ is_compact (f '' s) := hf.to_inducing.is_compact_iff.symm /-- The preimage of a compact set under a closed embedding is a compact set. -/ lemma closed_embedding.is_compact_preimage {f : α → β} (hf : closed_embedding f) {K : set β} (hK : is_compact K) : is_compact (f ⁻¹' K) := begin replace hK := hK.inter_right hf.closed_range, rwa [← hf.to_inducing.is_compact_iff, image_preimage_eq_inter_range] end /-- A closed embedding is proper, ie, inverse images of compact sets are contained in compacts. Moreover, the preimage of a compact set is compact, see `closed_embedding.is_compact_preimage`. -/ lemma closed_embedding.tendsto_cocompact {f : α → β} (hf : closed_embedding f) : tendsto f (filter.cocompact α) (filter.cocompact β) := filter.has_basis_cocompact.tendsto_right_iff.mpr $ λ K hK, (hf.is_compact_preimage hK).compl_mem_cocompact lemma compact_iff_compact_in_subtype {p : α → Prop} {s : set {a // p a}} : is_compact s ↔ is_compact ((coe : _ → α) '' s) := embedding_subtype_coe.is_compact_iff_is_compact_image lemma is_compact_iff_is_compact_univ {s : set α} : is_compact s ↔ is_compact (univ : set s) := by rw [compact_iff_compact_in_subtype, image_univ, subtype.range_coe]; refl lemma is_compact_iff_compact_space {s : set α} : is_compact s ↔ compact_space s := is_compact_iff_is_compact_univ.trans ⟨λ h, ⟨h⟩, @compact_space.compact_univ _ _⟩ protected lemma closed_embedding.noncompact_space [noncompact_space α] {f : α → β} (hf : closed_embedding f) : noncompact_space β := noncompact_space_of_ne_bot hf.tendsto_cocompact.ne_bot protected lemma closed_embedding.compact_space [h : compact_space β] {f : α → β} (hf : closed_embedding f) : compact_space α := by { unfreezingI { contrapose! h, rw not_compact_space_iff at h ⊢ }, exact hf.noncompact_space } lemma is_compact.prod {s : set α} {t : set β} (hs : is_compact s) (ht : is_compact t) : is_compact (s ×ˢ t) := begin rw is_compact_iff_ultrafilter_le_nhds at hs ht ⊢, intros f hfs, rw le_principal_iff at hfs, obtain ⟨a : α, sa : a ∈ s, ha : map prod.fst ↑f ≤ 𝓝 a⟩ := hs (f.map prod.fst) (le_principal_iff.2 $ mem_map.2 $ mem_of_superset hfs (λ x, and.left)), obtain ⟨b : β, tb : b ∈ t, hb : map prod.snd ↑f ≤ 𝓝 b⟩ := ht (f.map prod.snd) (le_principal_iff.2 $ mem_map.2 $ mem_of_superset hfs (λ x, and.right)), rw map_le_iff_le_comap at ha hb, refine ⟨⟨a, b⟩, ⟨sa, tb⟩, _⟩, rw nhds_prod_eq, exact le_inf ha hb end /-- Finite topological spaces are compact. -/ @[priority 100] instance finite.compact_space [finite α] : compact_space α := { compact_univ := finite_univ.is_compact } /-- The product of two compact spaces is compact. -/ instance [compact_space α] [compact_space β] : compact_space (α × β) := ⟨by { rw ← univ_prod_univ, exact compact_univ.prod compact_univ }⟩ /-- The disjoint union of two compact spaces is compact. -/ instance [compact_space α] [compact_space β] : compact_space (α ⊕ β) := ⟨begin rw ← range_inl_union_range_inr, exact (is_compact_range continuous_inl).union (is_compact_range continuous_inr) end⟩ instance [finite ι] [Π i, topological_space (π i)] [∀ i, compact_space (π i)] : compact_space (Σ i, π i) := begin refine ⟨_⟩, rw sigma.univ, exact compact_Union (λ i, is_compact_range continuous_sigma_mk), end /-- The coproduct of the cocompact filters on two topological spaces is the cocompact filter on their product. -/ lemma filter.coprod_cocompact : (filter.cocompact α).coprod (filter.cocompact β) = filter.cocompact (α × β) := begin ext S, simp only [mem_coprod_iff, exists_prop, mem_comap, filter.mem_cocompact], split, { rintro ⟨⟨A, ⟨t, ht, hAt⟩, hAS⟩, B, ⟨t', ht', hBt'⟩, hBS⟩, refine ⟨t ×ˢ t', ht.prod ht', _⟩, refine subset.trans _ (union_subset hAS hBS), rw compl_subset_comm at ⊢ hAt hBt', refine subset.trans _ (set.prod_mono hAt hBt'), intros x, simp only [compl_union, mem_inter_eq, mem_prod, mem_preimage, mem_compl_eq], tauto }, { rintros ⟨t, ht, htS⟩, refine ⟨⟨(prod.fst '' t)ᶜ, _, _⟩, ⟨(prod.snd '' t)ᶜ, _, _⟩⟩, { exact ⟨prod.fst '' t, ht.image continuous_fst, subset.rfl⟩ }, { rw preimage_compl, rw compl_subset_comm at ⊢ htS, exact subset.trans htS (subset_preimage_image prod.fst _) }, { exact ⟨prod.snd '' t, ht.image continuous_snd, subset.rfl⟩ }, { rw preimage_compl, rw compl_subset_comm at ⊢ htS, exact subset.trans htS (subset_preimage_image prod.snd _) } } end lemma prod.noncompact_space_iff : noncompact_space (α × β) ↔ noncompact_space α ∧ nonempty β ∨ nonempty α ∧ noncompact_space β := by simp [← filter.cocompact_ne_bot_iff, ← filter.coprod_cocompact, filter.coprod_ne_bot_iff] @[priority 100] -- See Note [lower instance priority] instance prod.noncompact_space_left [noncompact_space α] [nonempty β] : noncompact_space (α × β) := prod.noncompact_space_iff.2 (or.inl ⟨‹_›, ‹_›⟩) @[priority 100] -- See Note [lower instance priority] instance prod.noncompact_space_right [nonempty α] [noncompact_space β] : noncompact_space (α × β) := prod.noncompact_space_iff.2 (or.inr ⟨‹_›, ‹_›⟩) section tychonoff variables [Π i, topological_space (π i)] /-- **Tychonoff's theorem**: product of compact sets is compact. -/ lemma is_compact_pi_infinite {s : Π i, set (π i)} : (∀ i, is_compact (s i)) → is_compact {x : Π i, π i | ∀ i, x i ∈ s i} := begin simp only [is_compact_iff_ultrafilter_le_nhds, nhds_pi, filter.pi, exists_prop, mem_set_of_eq, le_infi_iff, le_principal_iff], intros h f hfs, have : ∀ i:ι, ∃ a, a ∈ s i ∧ tendsto (λx:Πi:ι, π i, x i) f (𝓝 a), { refine λ i, h i (f.map _) (mem_map.2 _), exact mem_of_superset hfs (λ x hx, hx i) }, choose a ha, exact ⟨a, assume i, (ha i).left, assume i, (ha i).right.le_comap⟩ end /-- **Tychonoff's theorem** formulated using `set.pi`: product of compact sets is compact. -/ lemma is_compact_univ_pi {s : Π i, set (π i)} (h : ∀ i, is_compact (s i)) : is_compact (pi univ s) := by { convert is_compact_pi_infinite h, simp only [← mem_univ_pi, set_of_mem_eq] } instance pi.compact_space [∀ i, compact_space (π i)] : compact_space (Πi, π i) := ⟨by { rw [← pi_univ univ], exact is_compact_univ_pi (λ i, compact_univ) }⟩ /-- **Tychonoff's theorem** formulated in terms of filters: `filter.cocompact` on an indexed product type `Π d, κ d` the `filter.Coprod` of filters `filter.cocompact` on `κ d`. -/ lemma filter.Coprod_cocompact {δ : Type*} {κ : δ → Type*} [Π d, topological_space (κ d)] : filter.Coprod (λ d, filter.cocompact (κ d)) = filter.cocompact (Π d, κ d) := begin refine le_antisymm (supr_le $ λ i, filter.comap_cocompact_le (continuous_apply i)) _, refine compl_surjective.forall.2 (λ s H, _), simp only [compl_mem_Coprod, filter.mem_cocompact, compl_subset_compl, image_subset_iff] at H ⊢, choose K hKc htK using H, exact ⟨set.pi univ K, is_compact_univ_pi hKc, λ f hf i hi, htK i hf⟩ end end tychonoff instance quot.compact_space {r : α → α → Prop} [compact_space α] : compact_space (quot r) := ⟨by { rw ← range_quot_mk, exact is_compact_range continuous_quot_mk }⟩ instance quotient.compact_space {s : setoid α} [compact_space α] : compact_space (quotient s) := quot.compact_space /-- There are various definitions of "locally compact space" in the literature, which agree for Hausdorff spaces but not in general. This one is the precise condition on X needed for the evaluation `map C(X, Y) × X → Y` to be continuous for all `Y` when `C(X, Y)` is given the compact-open topology. -/ class locally_compact_space (α : Type*) [topological_space α] : Prop := (local_compact_nhds : ∀ (x : α) (n ∈ 𝓝 x), ∃ s ∈ 𝓝 x, s ⊆ n ∧ is_compact s) lemma compact_basis_nhds [locally_compact_space α] (x : α) : (𝓝 x).has_basis (λ s, s ∈ 𝓝 x ∧ is_compact s) (λ s, s) := has_basis_self.2 $ by simpa only [and_comm] using locally_compact_space.local_compact_nhds x lemma local_compact_nhds [locally_compact_space α] {x : α} {n : set α} (h : n ∈ 𝓝 x) : ∃ s ∈ 𝓝 x, s ⊆ n ∧ is_compact s := locally_compact_space.local_compact_nhds _ _ h lemma locally_compact_space_of_has_basis {ι : α → Type*} {p : Π x, ι x → Prop} {s : Π x, ι x → set α} (h : ∀ x, (𝓝 x).has_basis (p x) (s x)) (hc : ∀ x i, p x i → is_compact (s x i)) : locally_compact_space α := ⟨λ x t ht, let ⟨i, hp, ht⟩ := (h x).mem_iff.1 ht in ⟨s x i, (h x).mem_of_mem hp, ht, hc x i hp⟩⟩ instance locally_compact_space.prod (α : Type*) (β : Type*) [topological_space α] [topological_space β] [locally_compact_space α] [locally_compact_space β] : locally_compact_space (α × β) := have _ := λ x : α × β, (compact_basis_nhds x.1).prod_nhds' (compact_basis_nhds x.2), locally_compact_space_of_has_basis this $ λ x s ⟨⟨_, h₁⟩, _, h₂⟩, h₁.prod h₂ section pi variables [Π i, topological_space (π i)] [∀ i, locally_compact_space (π i)] /--In general it suffices that all but finitely many of the spaces are compact, but that's not straightforward to state and use. -/ instance locally_compact_space.pi_finite [finite ι] : locally_compact_space (Π i, π i) := ⟨λ t n hn, begin rw [nhds_pi, filter.mem_pi] at hn, obtain ⟨s, hs, n', hn', hsub⟩ := hn, choose n'' hn'' hsub' hc using λ i, locally_compact_space.local_compact_nhds (t i) (n' i) (hn' i), refine ⟨(set.univ : set ι).pi n'', _, subset_trans (λ _ h, _) hsub, is_compact_univ_pi hc⟩, { exact (set_pi_mem_nhds_iff (@set.finite_univ ι _) _).mpr (λ i hi, hn'' i), }, { exact λ i hi, hsub' i (h i trivial), }, end⟩ /-- For spaces that are not Hausdorff. -/ instance locally_compact_space.pi [∀ i, compact_space (π i)] : locally_compact_space (Π i, π i) := ⟨λ t n hn, begin rw [nhds_pi, filter.mem_pi] at hn, obtain ⟨s, hs, n', hn', hsub⟩ := hn, choose n'' hn'' hsub' hc using λ i, locally_compact_space.local_compact_nhds (t i) (n' i) (hn' i), refine ⟨s.pi n'', _, subset_trans (λ _, _) hsub, _⟩, { exact (set_pi_mem_nhds_iff hs _).mpr (λ i _, hn'' i), }, { exact forall₂_imp (λ i hi hi', hsub' i hi'), }, { rw ← set.univ_pi_ite, refine is_compact_univ_pi (λ i, _), by_cases i ∈ s, { rw if_pos h, exact hc i, }, { rw if_neg h, exact compact_space.compact_univ, } }, end⟩ end pi /-- A reformulation of the definition of locally compact space: In a locally compact space, every open set containing `x` has a compact subset containing `x` in its interior. -/ lemma exists_compact_subset [locally_compact_space α] {x : α} {U : set α} (hU : is_open U) (hx : x ∈ U) : ∃ (K : set α), is_compact K ∧ x ∈ interior K ∧ K ⊆ U := begin rcases locally_compact_space.local_compact_nhds x U (hU.mem_nhds hx) with ⟨K, h1K, h2K, h3K⟩, exact ⟨K, h3K, mem_interior_iff_mem_nhds.2 h1K, h2K⟩, end /-- In a locally compact space every point has a compact neighborhood. -/ lemma exists_compact_mem_nhds [locally_compact_space α] (x : α) : ∃ K, is_compact K ∧ K ∈ 𝓝 x := let ⟨K, hKc, hx, H⟩ := exists_compact_subset is_open_univ (mem_univ x) in ⟨K, hKc, mem_interior_iff_mem_nhds.1 hx⟩ /-- In a locally compact space, for every containement `K ⊆ U` of a compact set `K` in an open set `U`, there is a compact neighborhood `L` such that `K ⊆ L ⊆ U`: equivalently, there is a compact `L` such that `K ⊆ interior L` and `L ⊆ U`. -/ lemma exists_compact_between [hα : locally_compact_space α] {K U : set α} (hK : is_compact K) (hU : is_open U) (h_KU : K ⊆ U) : ∃ L, is_compact L ∧ K ⊆ interior L ∧ L ⊆ U := begin choose V hVc hxV hKV using λ x : K, exists_compact_subset hU (h_KU x.2), have : K ⊆ ⋃ x, interior (V x), from λ x hx, mem_Union.2 ⟨⟨x, hx⟩, hxV _⟩, rcases hK.elim_finite_subcover _ (λ x, @is_open_interior α _ (V x)) this with ⟨t, ht⟩, refine ⟨_, t.compact_bUnion (λ x _, hVc x), λ x hx, _, set.Union₂_subset (λ i _, hKV i)⟩, rcases mem_Union₂.1 (ht hx) with ⟨y, hyt, hy⟩, exact interior_mono (subset_bUnion_of_mem hyt) hy, end /-- In a locally compact space, every compact set is contained in the interior of a compact set. -/ lemma exists_compact_superset [locally_compact_space α] {K : set α} (hK : is_compact K) : ∃ K', is_compact K' ∧ K ⊆ interior K' := let ⟨L, hLc, hKL, _⟩ := exists_compact_between hK is_open_univ K.subset_univ in ⟨L, hLc, hKL⟩ protected lemma closed_embedding.locally_compact_space [locally_compact_space β] {f : α → β} (hf : closed_embedding f) : locally_compact_space α := begin have : ∀ x : α, (𝓝 x).has_basis (λ s, s ∈ 𝓝 (f x) ∧ is_compact s) (λ s, f ⁻¹' s), { intro x, rw hf.to_embedding.to_inducing.nhds_eq_comap, exact (compact_basis_nhds _).comap _ }, exact locally_compact_space_of_has_basis this (λ x s hs, hf.is_compact_preimage hs.2) end protected lemma is_closed.locally_compact_space [locally_compact_space α] {s : set α} (hs : is_closed s) : locally_compact_space s := (closed_embedding_subtype_coe hs).locally_compact_space protected lemma open_embedding.locally_compact_space [locally_compact_space β] {f : α → β} (hf : open_embedding f) : locally_compact_space α := begin have : ∀ x : α, (𝓝 x).has_basis (λ s, (s ∈ 𝓝 (f x) ∧ is_compact s) ∧ s ⊆ range f) (λ s, f ⁻¹' s), { intro x, rw hf.to_embedding.to_inducing.nhds_eq_comap, exact ((compact_basis_nhds _).restrict_subset $ hf.open_range.mem_nhds $ mem_range_self _).comap _ }, refine locally_compact_space_of_has_basis this (λ x s hs, _), rw [← hf.to_inducing.is_compact_iff, image_preimage_eq_of_subset hs.2], exact hs.1.2 end protected lemma is_open.locally_compact_space [locally_compact_space α] {s : set α} (hs : is_open s) : locally_compact_space s := hs.open_embedding_subtype_coe.locally_compact_space lemma ultrafilter.le_nhds_Lim [compact_space α] (F : ultrafilter α) : ↑F ≤ 𝓝 (@Lim _ _ (F : filter α).nonempty_of_ne_bot F) := begin rcases compact_univ.ultrafilter_le_nhds F (by simp) with ⟨x, -, h⟩, exact le_nhds_Lim ⟨x,h⟩, end theorem is_closed.exists_minimal_nonempty_closed_subset [compact_space α] {S : set α} (hS : is_closed S) (hne : S.nonempty) : ∃ (V : set α), V ⊆ S ∧ V.nonempty ∧ is_closed V ∧ (∀ (V' : set α), V' ⊆ V → V'.nonempty → is_closed V' → V' = V) := begin let opens := {U : set α | Sᶜ ⊆ U ∧ is_open U ∧ Uᶜ.nonempty}, obtain ⟨U, ⟨Uc, Uo, Ucne⟩, h⟩ := zorn_subset opens (λ c hc hz, begin by_cases hcne : c.nonempty, { obtain ⟨U₀, hU₀⟩ := hcne, haveI : nonempty {U // U ∈ c} := ⟨⟨U₀, hU₀⟩⟩, obtain ⟨U₀compl, U₀opn, U₀ne⟩ := hc hU₀, use ⋃₀ c, refine ⟨⟨_, _, _⟩, λ U hU a ha, ⟨U, hU, ha⟩⟩, { exact λ a ha, ⟨U₀, hU₀, U₀compl ha⟩ }, { exact is_open_sUnion (λ _ h, (hc h).2.1) }, { convert_to (⋂(U : {U // U ∈ c}), U.1ᶜ).nonempty, { ext, simp only [not_exists, exists_prop, not_and, set.mem_Inter, subtype.forall, mem_set_of_eq, mem_compl_eq, mem_sUnion] }, apply is_compact.nonempty_Inter_of_directed_nonempty_compact_closed, { rintros ⟨U, hU⟩ ⟨U', hU'⟩, obtain ⟨V, hVc, hVU, hVU'⟩ := hz.directed_on U hU U' hU', exact ⟨⟨V, hVc⟩, set.compl_subset_compl.mpr hVU, set.compl_subset_compl.mpr hVU'⟩, }, { exact λ U, (hc U.2).2.2, }, { exact λ U, (is_closed_compl_iff.mpr (hc U.2).2.1).is_compact, }, { exact λ U, (is_closed_compl_iff.mpr (hc U.2).2.1), } } }, { use Sᶜ, refine ⟨⟨set.subset.refl _, is_open_compl_iff.mpr hS, _⟩, λ U Uc, (hcne ⟨U, Uc⟩).elim⟩, rw compl_compl, exact hne, } end), refine ⟨Uᶜ, set.compl_subset_comm.mp Uc, Ucne, is_closed_compl_iff.mpr Uo, _⟩, intros V' V'sub V'ne V'cls, have : V'ᶜ = U, { refine h V'ᶜ ⟨_, is_open_compl_iff.mpr V'cls, _⟩ (set.subset_compl_comm.mp V'sub), exact set.subset.trans Uc (set.subset_compl_comm.mp V'sub), simp only [compl_compl, V'ne], }, rw [←this, compl_compl], end /-- A σ-compact space is a space that is the union of a countable collection of compact subspaces. Note that a locally compact separable T₂ space need not be σ-compact. The sequence can be extracted using `topological_space.compact_covering`. -/ class sigma_compact_space (α : Type*) [topological_space α] : Prop := (exists_compact_covering : ∃ K : ℕ → set α, (∀ n, is_compact (K n)) ∧ (⋃ n, K n) = univ) @[priority 200] -- see Note [lower instance priority] instance compact_space.sigma_compact [compact_space α] : sigma_compact_space α := ⟨⟨λ _, univ, λ _, compact_univ, Union_const _⟩⟩ lemma sigma_compact_space.of_countable (S : set (set α)) (Hc : S.countable) (Hcomp : ∀ s ∈ S, is_compact s) (HU : ⋃₀ S = univ) : sigma_compact_space α := ⟨(exists_seq_cover_iff_countable ⟨_, is_compact_empty⟩).2 ⟨S, Hc, Hcomp, HU⟩⟩ @[priority 100] -- see Note [lower instance priority] instance sigma_compact_space_of_locally_compact_second_countable [locally_compact_space α] [second_countable_topology α] : sigma_compact_space α := begin choose K hKc hxK using λ x : α, exists_compact_mem_nhds x, rcases countable_cover_nhds hxK with ⟨s, hsc, hsU⟩, refine sigma_compact_space.of_countable _ (hsc.image K) (ball_image_iff.2 $ λ x _, hKc x) _, rwa sUnion_image end variables (α) [sigma_compact_space α] open sigma_compact_space /-- A choice of compact covering for a `σ`-compact space, chosen to be monotone. -/ def compact_covering : ℕ → set α := accumulate exists_compact_covering.some lemma is_compact_compact_covering (n : ℕ) : is_compact (compact_covering α n) := compact_accumulate (classical.some_spec sigma_compact_space.exists_compact_covering).1 n lemma Union_compact_covering : (⋃ n, compact_covering α n) = univ := begin rw [compact_covering, Union_accumulate], exact (classical.some_spec sigma_compact_space.exists_compact_covering).2 end @[mono] lemma compact_covering_subset ⦃m n : ℕ⦄ (h : m ≤ n) : compact_covering α m ⊆ compact_covering α n := monotone_accumulate h variable {α} lemma exists_mem_compact_covering (x : α) : ∃ n, x ∈ compact_covering α n := Union_eq_univ_iff.mp (Union_compact_covering α) x /-- If `α` is a `σ`-compact space, then a locally finite family of nonempty sets of `α` can have only countably many elements, `set.countable` version. -/ protected lemma locally_finite.countable_univ {ι : Type*} {f : ι → set α} (hf : locally_finite f) (hne : ∀ i, (f i).nonempty) : (univ : set ι).countable := begin have := λ n, hf.finite_nonempty_inter_compact (is_compact_compact_covering α n), refine (countable_Union (λ n, (this n).countable)).mono (λ i hi, _), rcases hne i with ⟨x, hx⟩, rcases Union_eq_univ_iff.1 (Union_compact_covering α) x with ⟨n, hn⟩, exact mem_Union.2 ⟨n, x, hx, hn⟩ end /-- If `f : ι → set α` is a locally finite covering of a σ-compact topological space by nonempty sets, then the index type `ι` is encodable. -/ protected noncomputable def locally_finite.encodable {ι : Type*} {f : ι → set α} (hf : locally_finite f) (hne : ∀ i, (f i).nonempty) : encodable ι := @encodable.of_equiv _ _ (hf.countable_univ hne).to_encodable (equiv.set.univ _).symm /-- In a topological space with sigma compact topology, if `f` is a function that sends each point `x` of a closed set `s` to a neighborhood of `x` within `s`, then for some countable set `t ⊆ s`, the neighborhoods `f x`, `x ∈ t`, cover the whole set `s`. -/ lemma countable_cover_nhds_within_of_sigma_compact {f : α → set α} {s : set α} (hs : is_closed s) (hf : ∀ x ∈ s, f x ∈ 𝓝[s] x) : ∃ t ⊆ s, t.countable ∧ s ⊆ ⋃ x ∈ t, f x := begin simp only [nhds_within, mem_inf_principal] at hf, choose t ht hsub using λ n, ((is_compact_compact_covering α n).inter_right hs).elim_nhds_subcover _ (λ x hx, hf x hx.right), refine ⟨⋃ n, (t n : set α), Union_subset $ λ n x hx, (ht n x hx).2, countable_Union $ λ n, (t n).countable_to_set, λ x hx, mem_Union₂.2 _⟩, rcases exists_mem_compact_covering x with ⟨n, hn⟩, rcases mem_Union₂.1 (hsub n ⟨hn, hx⟩) with ⟨y, hyt : y ∈ t n, hyf : x ∈ s → x ∈ f y⟩, exact ⟨y, mem_Union.2 ⟨n, hyt⟩, hyf hx⟩ end /-- In a topological space with sigma compact topology, if `f` is a function that sends each point `x` to a neighborhood of `x`, then for some countable set `s`, the neighborhoods `f x`, `x ∈ s`, cover the whole space. -/ lemma countable_cover_nhds_of_sigma_compact {f : α → set α} (hf : ∀ x, f x ∈ 𝓝 x) : ∃ s : set α, s.countable ∧ (⋃ x ∈ s, f x) = univ := begin simp only [← nhds_within_univ] at hf, rcases countable_cover_nhds_within_of_sigma_compact is_closed_univ (λ x _, hf x) with ⟨s, -, hsc, hsU⟩, exact ⟨s, hsc, univ_subset_iff.1 hsU⟩ end end compact /-- An [exhaustion by compact sets](https://en.wikipedia.org/wiki/Exhaustion_by_compact_sets) of a topological space is a sequence of compact sets `K n` such that `K n ⊆ interior (K (n + 1))` and `(⋃ n, K n) = univ`. If `X` is a locally compact sigma compact space, then `compact_exhaustion.choice X` provides a choice of an exhaustion by compact sets. This choice is also available as `(default : compact_exhaustion X)`. -/ structure compact_exhaustion (X : Type*) [topological_space X] := (to_fun : ℕ → set X) (is_compact' : ∀ n, is_compact (to_fun n)) (subset_interior_succ' : ∀ n, to_fun n ⊆ interior (to_fun (n + 1))) (Union_eq' : (⋃ n, to_fun n) = univ) namespace compact_exhaustion instance : has_coe_to_fun (compact_exhaustion α) (λ _, ℕ → set α) := ⟨to_fun⟩ variables {α} (K : compact_exhaustion α) protected lemma is_compact (n : ℕ) : is_compact (K n) := K.is_compact' n lemma subset_interior_succ (n : ℕ) : K n ⊆ interior (K (n + 1)) := K.subset_interior_succ' n lemma subset_succ (n : ℕ) : K n ⊆ K (n + 1) := subset.trans (K.subset_interior_succ n) interior_subset @[mono] protected lemma subset ⦃m n : ℕ⦄ (h : m ≤ n) : K m ⊆ K n := show K m ≤ K n, from monotone_nat_of_le_succ K.subset_succ h lemma subset_interior ⦃m n : ℕ⦄ (h : m < n) : K m ⊆ interior (K n) := subset.trans (K.subset_interior_succ m) $ interior_mono $ K.subset h lemma Union_eq : (⋃ n, K n) = univ := K.Union_eq' lemma exists_mem (x : α) : ∃ n, x ∈ K n := Union_eq_univ_iff.1 K.Union_eq x /-- The minimal `n` such that `x ∈ K n`. -/ protected noncomputable def find (x : α) : ℕ := nat.find (K.exists_mem x) lemma mem_find (x : α) : x ∈ K (K.find x) := nat.find_spec (K.exists_mem x) lemma mem_iff_find_le {x : α} {n : ℕ} : x ∈ K n ↔ K.find x ≤ n := ⟨λ h, nat.find_min' (K.exists_mem x) h, λ h, K.subset h $ K.mem_find x⟩ /-- Prepend the empty set to a compact exhaustion `K n`. -/ def shiftr : compact_exhaustion α := { to_fun := λ n, nat.cases_on n ∅ K, is_compact' := λ n, nat.cases_on n is_compact_empty K.is_compact, subset_interior_succ' := λ n, nat.cases_on n (empty_subset _) K.subset_interior_succ, Union_eq' := Union_eq_univ_iff.2 $ λ x, ⟨K.find x + 1, K.mem_find x⟩ } @[simp] lemma find_shiftr (x : α) : K.shiftr.find x = K.find x + 1 := nat.find_comp_succ _ _ (not_mem_empty _) lemma mem_diff_shiftr_find (x : α) : x ∈ K.shiftr (K.find x + 1) \ K.shiftr (K.find x) := ⟨K.mem_find _, mt K.shiftr.mem_iff_find_le.1 $ by simp only [find_shiftr, not_le, nat.lt_succ_self]⟩ /-- A choice of an [exhaustion by compact sets](https://en.wikipedia.org/wiki/Exhaustion_by_compact_sets) of a locally compact sigma compact space. -/ noncomputable def choice (X : Type*) [topological_space X] [locally_compact_space X] [sigma_compact_space X] : compact_exhaustion X := begin apply classical.choice, let K : ℕ → {s : set X // is_compact s} := λ n, nat.rec_on n ⟨∅, is_compact_empty⟩ (λ n s, ⟨(exists_compact_superset s.2).some ∪ compact_covering X n, (exists_compact_superset s.2).some_spec.1.union (is_compact_compact_covering _ _)⟩), refine ⟨⟨λ n, K n, λ n, (K n).2, λ n, _, _⟩⟩, { exact subset.trans (exists_compact_superset (K n).2).some_spec.2 (interior_mono $ subset_union_left _ _) }, { refine univ_subset_iff.1 (Union_compact_covering X ▸ _), exact Union_mono' (λ n, ⟨n + 1, subset_union_right _ _⟩) } end noncomputable instance [locally_compact_space α] [sigma_compact_space α] : inhabited (compact_exhaustion α) := ⟨compact_exhaustion.choice α⟩ end compact_exhaustion section clopen /-- A set is clopen if it is both open and closed. -/ def is_clopen (s : set α) : Prop := is_open s ∧ is_closed s protected lemma is_clopen.is_open (hs : is_clopen s) : is_open s := hs.1 protected lemma is_clopen.is_closed (hs : is_clopen s) : is_closed s := hs.2 lemma is_clopen_iff_frontier_eq_empty {s : set α} : is_clopen s ↔ frontier s = ∅ := begin rw [is_clopen, ← closure_eq_iff_is_closed, ← interior_eq_iff_open, frontier, diff_eq_empty], refine ⟨λ h, (h.2.trans h.1.symm).subset, λ h, _⟩, exact ⟨interior_subset.antisymm (subset_closure.trans h), (h.trans interior_subset).antisymm subset_closure⟩ end alias is_clopen_iff_frontier_eq_empty ↔ is_clopen.frontier_eq _ theorem is_clopen.union {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s ∪ t) := ⟨hs.1.union ht.1, hs.2.union ht.2⟩ theorem is_clopen.inter {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s ∩ t) := ⟨hs.1.inter ht.1, hs.2.inter ht.2⟩ @[simp] theorem is_clopen_empty : is_clopen (∅ : set α) := ⟨is_open_empty, is_closed_empty⟩ @[simp] theorem is_clopen_univ : is_clopen (univ : set α) := ⟨is_open_univ, is_closed_univ⟩ theorem is_clopen.compl {s : set α} (hs : is_clopen s) : is_clopen sᶜ := ⟨hs.2.is_open_compl, hs.1.is_closed_compl⟩ @[simp] theorem is_clopen_compl_iff {s : set α} : is_clopen sᶜ ↔ is_clopen s := ⟨λ h, compl_compl s ▸ is_clopen.compl h, is_clopen.compl⟩ theorem is_clopen.diff {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s \ t) := hs.inter ht.compl lemma is_clopen.prod {s : set α} {t : set β} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s ×ˢ t) := ⟨hs.1.prod ht.1, hs.2.prod ht.2⟩ lemma is_clopen_Union {β : Type*} [finite β] {s : β → set α} (h : ∀ i, is_clopen (s i)) : is_clopen (⋃ i, s i) := ⟨is_open_Union (forall_and_distrib.1 h).1, is_closed_Union (forall_and_distrib.1 h).2⟩ lemma is_clopen_bUnion {β : Type*} {s : set β} {f : β → set α} (hs : s.finite) (h : ∀ i ∈ s, is_clopen $ f i) : is_clopen (⋃ i ∈ s, f i) := ⟨is_open_bUnion (λ i hi, (h i hi).1), is_closed_bUnion hs (λ i hi, (h i hi).2)⟩ lemma is_clopen_bUnion_finset {β : Type*} {s : finset β} {f : β → set α} (h : ∀ i ∈ s, is_clopen $ f i) : is_clopen (⋃ i ∈ s, f i) := is_clopen_bUnion s.finite_to_set h lemma is_clopen_Inter {β : Type*} [finite β] {s : β → set α} (h : ∀ i, is_clopen (s i)) : is_clopen (⋂ i, s i) := ⟨(is_open_Inter (forall_and_distrib.1 h).1), (is_closed_Inter (forall_and_distrib.1 h).2)⟩ lemma is_clopen_bInter {β : Type*} {s : set β} (hs : s.finite) {f : β → set α} (h : ∀ i ∈ s, is_clopen (f i)) : is_clopen (⋂ i ∈ s, f i) := ⟨is_open_bInter hs (λ i hi, (h i hi).1), is_closed_bInter (λ i hi, (h i hi).2)⟩ lemma is_clopen_bInter_finset {β : Type*} {s : finset β} {f : β → set α} (h : ∀ i ∈ s, is_clopen (f i)) : is_clopen (⋂ i ∈ s, f i) := is_clopen_bInter s.finite_to_set h lemma continuous_on.preimage_clopen_of_clopen {f : α → β} {s : set α} {t : set β} (hf : continuous_on f s) (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s ∩ f⁻¹' t) := ⟨continuous_on.preimage_open_of_open hf hs.1 ht.1, continuous_on.preimage_closed_of_closed hf hs.2 ht.2⟩ /-- The intersection of a disjoint covering by two open sets of a clopen set will be clopen. -/ theorem is_clopen_inter_of_disjoint_cover_clopen {Z a b : set α} (h : is_clopen Z) (cover : Z ⊆ a ∪ b) (ha : is_open a) (hb : is_open b) (hab : disjoint a b) : is_clopen (Z ∩ a) := begin refine ⟨is_open.inter h.1 ha, _⟩, have : is_closed (Z ∩ bᶜ) := is_closed.inter h.2 (is_closed_compl_iff.2 hb), convert this using 1, refine (inter_subset_inter_right Z hab.subset_compl_right).antisymm _, rintro x ⟨hx₁, hx₂⟩, exact ⟨hx₁, by simpa [not_mem_of_mem_compl hx₂] using cover hx₁⟩, end @[simp] lemma is_clopen_discrete [discrete_topology α] (x : set α) : is_clopen x := ⟨is_open_discrete _, is_closed_discrete _⟩ lemma clopen_range_sigma_mk {ι : Type*} {σ : ι → Type*} [Π i, topological_space (σ i)] {i : ι} : is_clopen (set.range (@sigma.mk ι σ i)) := ⟨open_embedding_sigma_mk.open_range, closed_embedding_sigma_mk.closed_range⟩ protected lemma quotient_map.is_clopen_preimage {f : α → β} (hf : quotient_map f) {s : set β} : is_clopen (f ⁻¹' s) ↔ is_clopen s := and_congr hf.is_open_preimage hf.is_closed_preimage end clopen section preirreducible /-- A preirreducible set `s` is one where there is no non-trivial pair of disjoint opens on `s`. -/ def is_preirreducible (s : set α) : Prop := ∀ (u v : set α), is_open u → is_open v → (s ∩ u).nonempty → (s ∩ v).nonempty → (s ∩ (u ∩ v)).nonempty /-- An irreducible set `s` is one that is nonempty and where there is no non-trivial pair of disjoint opens on `s`. -/ def is_irreducible (s : set α) : Prop := s.nonempty ∧ is_preirreducible s lemma is_irreducible.nonempty {s : set α} (h : is_irreducible s) : s.nonempty := h.1 lemma is_irreducible.is_preirreducible {s : set α} (h : is_irreducible s) : is_preirreducible s := h.2 theorem is_preirreducible_empty : is_preirreducible (∅ : set α) := λ _ _ _ _ _ ⟨x, h1, h2⟩, h1.elim lemma set.subsingleton.is_preirreducible {s : set α} (hs : s.subsingleton) : is_preirreducible s := λ u v hu hv ⟨x, hxs, hxu⟩ ⟨y, hys, hyv⟩, ⟨y, hys, hs hxs hys ▸ hxu, hyv⟩ theorem is_irreducible_singleton {x} : is_irreducible ({x} : set α) := ⟨singleton_nonempty x, subsingleton_singleton.is_preirreducible⟩ theorem is_preirreducible.closure {s : set α} (H : is_preirreducible s) : is_preirreducible (closure s) := λ u v hu hv ⟨y, hycs, hyu⟩ ⟨z, hzcs, hzv⟩, let ⟨p, hpu, hps⟩ := mem_closure_iff.1 hycs u hu hyu in let ⟨q, hqv, hqs⟩ := mem_closure_iff.1 hzcs v hv hzv in let ⟨r, hrs, hruv⟩ := H u v hu hv ⟨p, hps, hpu⟩ ⟨q, hqs, hqv⟩ in ⟨r, subset_closure hrs, hruv⟩ lemma is_irreducible.closure {s : set α} (h : is_irreducible s) : is_irreducible (closure s) := ⟨h.nonempty.closure, h.is_preirreducible.closure⟩ theorem exists_preirreducible (s : set α) (H : is_preirreducible s) : ∃ t : set α, is_preirreducible t ∧ s ⊆ t ∧ ∀ u, is_preirreducible u → t ⊆ u → u = t := let ⟨m, hm, hsm, hmm⟩ := zorn_subset_nonempty {t : set α | is_preirreducible t} (λ c hc hcc hcn, let ⟨t, htc⟩ := hcn in ⟨⋃₀ c, λ u v hu hv ⟨y, hy, hyu⟩ ⟨z, hz, hzv⟩, let ⟨p, hpc, hyp⟩ := mem_sUnion.1 hy, ⟨q, hqc, hzq⟩ := mem_sUnion.1 hz in or.cases_on (hcc.total hpc hqc) (assume hpq : p ⊆ q, let ⟨x, hxp, hxuv⟩ := hc hqc u v hu hv ⟨y, hpq hyp, hyu⟩ ⟨z, hzq, hzv⟩ in ⟨x, mem_sUnion_of_mem hxp hqc, hxuv⟩) (assume hqp : q ⊆ p, let ⟨x, hxp, hxuv⟩ := hc hpc u v hu hv ⟨y, hyp, hyu⟩ ⟨z, hqp hzq, hzv⟩ in ⟨x, mem_sUnion_of_mem hxp hpc, hxuv⟩), λ x hxc, subset_sUnion_of_mem hxc⟩) s H in ⟨m, hm, hsm, λ u hu hmu, hmm _ hu hmu⟩ /-- A maximal irreducible set that contains a given point. -/ def irreducible_component (x : α) : set α := classical.some (exists_preirreducible {x} is_irreducible_singleton.is_preirreducible) lemma irreducible_component_property (x : α) : is_preirreducible (irreducible_component x) ∧ {x} ⊆ (irreducible_component x) ∧ ∀ u, is_preirreducible u → (irreducible_component x) ⊆ u → u = (irreducible_component x) := classical.some_spec (exists_preirreducible {x} is_irreducible_singleton.is_preirreducible) theorem mem_irreducible_component {x : α} : x ∈ irreducible_component x := singleton_subset_iff.1 (irreducible_component_property x).2.1 theorem is_irreducible_irreducible_component {x : α} : is_irreducible (irreducible_component x) := ⟨⟨x, mem_irreducible_component⟩, (irreducible_component_property x).1⟩ theorem eq_irreducible_component {x : α} : ∀ {s : set α}, is_preirreducible s → irreducible_component x ⊆ s → s = irreducible_component x := (irreducible_component_property x).2.2 theorem is_closed_irreducible_component {x : α} : is_closed (irreducible_component x) := closure_eq_iff_is_closed.1 $ eq_irreducible_component is_irreducible_irreducible_component.is_preirreducible.closure subset_closure /-- A preirreducible space is one where there is no non-trivial pair of disjoint opens. -/ class preirreducible_space (α : Type u) [topological_space α] : Prop := (is_preirreducible_univ [] : is_preirreducible (univ : set α)) /-- An irreducible space is one that is nonempty and where there is no non-trivial pair of disjoint opens. -/ class irreducible_space (α : Type u) [topological_space α] extends preirreducible_space α : Prop := (to_nonempty [] : nonempty α) -- see Note [lower instance priority] attribute [instance, priority 50] irreducible_space.to_nonempty lemma irreducible_space.is_irreducible_univ (α : Type u) [topological_space α] [irreducible_space α] : is_irreducible (⊤ : set α) := ⟨by simp, preirreducible_space.is_preirreducible_univ α⟩ lemma irreducible_space_def (α : Type u) [topological_space α] : irreducible_space α ↔ is_irreducible (⊤ : set α) := ⟨@@irreducible_space.is_irreducible_univ α _, λ h, by { haveI : preirreducible_space α := ⟨h.2⟩, exact ⟨⟨h.1.some⟩⟩ }⟩ theorem nonempty_preirreducible_inter [preirreducible_space α] {s t : set α} : is_open s → is_open t → s.nonempty → t.nonempty → (s ∩ t).nonempty := by simpa only [univ_inter, univ_subset_iff] using @preirreducible_space.is_preirreducible_univ α _ _ s t theorem is_preirreducible.image {s : set α} (H : is_preirreducible s) (f : α → β) (hf : continuous_on f s) : is_preirreducible (f '' s) := begin rintros u v hu hv ⟨_, ⟨⟨x, hx, rfl⟩, hxu⟩⟩ ⟨_, ⟨⟨y, hy, rfl⟩, hyv⟩⟩, rw ← mem_preimage at hxu hyv, rcases continuous_on_iff'.1 hf u hu with ⟨u', hu', u'_eq⟩, rcases continuous_on_iff'.1 hf v hv with ⟨v', hv', v'_eq⟩, have := H u' v' hu' hv', rw [inter_comm s u', ← u'_eq] at this, rw [inter_comm s v', ← v'_eq] at this, rcases this ⟨x, hxu, hx⟩ ⟨y, hyv, hy⟩ with ⟨z, hzs, hzu', hzv'⟩, refine ⟨f z, mem_image_of_mem f hzs, _, _⟩, all_goals { rw ← mem_preimage, apply mem_of_mem_inter_left, show z ∈ _ ∩ s, simp [*] } end theorem is_irreducible.image {s : set α} (H : is_irreducible s) (f : α → β) (hf : continuous_on f s) : is_irreducible (f '' s) := ⟨nonempty_image_iff.mpr H.nonempty, H.is_preirreducible.image f hf⟩ lemma subtype.preirreducible_space {s : set α} (h : is_preirreducible s) : preirreducible_space s := { is_preirreducible_univ := begin intros u v hu hv hsu hsv, rw is_open_induced_iff at hu hv, rcases hu with ⟨u, hu, rfl⟩, rcases hv with ⟨v, hv, rfl⟩, rcases hsu with ⟨⟨x, hxs⟩, hxs', hxu⟩, rcases hsv with ⟨⟨y, hys⟩, hys', hyv⟩, rcases h u v hu hv ⟨x, hxs, hxu⟩ ⟨y, hys, hyv⟩ with ⟨z, hzs, ⟨hzu, hzv⟩⟩, exact ⟨⟨z, hzs⟩, ⟨set.mem_univ _, ⟨hzu, hzv⟩⟩⟩ end } lemma subtype.irreducible_space {s : set α} (h : is_irreducible s) : irreducible_space s := { is_preirreducible_univ := (subtype.preirreducible_space h.is_preirreducible).is_preirreducible_univ, to_nonempty := h.nonempty.to_subtype } /-- A set `s` is irreducible if and only if for every finite collection of open sets all of whose members intersect `s`, `s` also intersects the intersection of the entire collection (i.e., there is an element of `s` contained in every member of the collection). -/ lemma is_irreducible_iff_sInter {s : set α} : is_irreducible s ↔ ∀ (U : finset (set α)) (hU : ∀ u ∈ U, is_open u) (H : ∀ u ∈ U, (s ∩ u).nonempty), (s ∩ ⋂₀ ↑U).nonempty := begin split; intro h, { intro U, apply finset.induction_on U, { intros, simpa using h.nonempty }, { intros u U hu IH hU H, rw [finset.coe_insert, sInter_insert], apply h.2, { solve_by_elim [finset.mem_insert_self] }, { apply is_open_sInter (finset.finite_to_set U), intros, solve_by_elim [finset.mem_insert_of_mem] }, { solve_by_elim [finset.mem_insert_self] }, { apply IH, all_goals { intros, solve_by_elim [finset.mem_insert_of_mem] } } } }, { split, { simpa using h ∅ _ _; intro u; simp }, intros u v hu hv hu' hv', simpa using h {u,v} _ _, all_goals { intro t, rw [finset.mem_insert, finset.mem_singleton], rintro (rfl|rfl); assumption } } end /-- A set is preirreducible if and only if for every cover by two closed sets, it is contained in one of the two covering sets. -/ lemma is_preirreducible_iff_closed_union_closed {s : set α} : is_preirreducible s ↔ ∀ (z₁ z₂ : set α), is_closed z₁ → is_closed z₂ → s ⊆ z₁ ∪ z₂ → s ⊆ z₁ ∨ s ⊆ z₂ := begin split, all_goals { intros h t₁ t₂ ht₁ ht₂, specialize h t₁ᶜ t₂ᶜ, simp only [is_open_compl_iff, is_closed_compl_iff] at h, specialize h ht₁ ht₂ }, { contrapose!, simp only [not_subset], rintro ⟨⟨x, hx, hx'⟩, ⟨y, hy, hy'⟩⟩, rcases h ⟨x, hx, hx'⟩ ⟨y, hy, hy'⟩ with ⟨z, hz, hz'⟩, rw ← compl_union at hz', exact ⟨z, hz, hz'⟩ }, { rintro ⟨x, hx, hx'⟩ ⟨y, hy, hy'⟩, rw ← compl_inter at h, delta set.nonempty, rw imp_iff_not_or at h, contrapose! h, split, { intros z hz hz', exact h z ⟨hz, hz'⟩ }, { split; intro H; refine H _ ‹_›; assumption } } end /-- A set is irreducible if and only if for every cover by a finite collection of closed sets, it is contained in one of the members of the collection. -/ lemma is_irreducible_iff_sUnion_closed {s : set α} : is_irreducible s ↔ ∀ (Z : finset (set α)) (hZ : ∀ z ∈ Z, is_closed z) (H : s ⊆ ⋃₀ ↑Z), ∃ z ∈ Z, s ⊆ z := begin rw [is_irreducible, is_preirreducible_iff_closed_union_closed], split; intro h, { intro Z, apply finset.induction_on Z, { intros, rw [finset.coe_empty, sUnion_empty] at H, rcases h.1 with ⟨x, hx⟩, exfalso, tauto }, { intros z Z hz IH hZ H, cases h.2 z (⋃₀ ↑Z) _ _ _ with h' h', { exact ⟨z, finset.mem_insert_self _ _, h'⟩ }, { rcases IH _ h' with ⟨z', hz', hsz'⟩, { exact ⟨z', finset.mem_insert_of_mem hz', hsz'⟩ }, { intros, solve_by_elim [finset.mem_insert_of_mem] } }, { solve_by_elim [finset.mem_insert_self] }, { rw sUnion_eq_bUnion, apply is_closed_bUnion (finset.finite_to_set Z), { intros, solve_by_elim [finset.mem_insert_of_mem] } }, { simpa using H } } }, { split, { by_contradiction hs, simpa using h ∅ _ _, { intro z, simp }, { simpa [set.nonempty] using hs } }, intros z₁ z₂ hz₁ hz₂ H, have := h {z₁, z₂} _ _, simp only [exists_prop, finset.mem_insert, finset.mem_singleton] at this, { rcases this with ⟨z, rfl|rfl, hz⟩; tauto }, { intro t, rw [finset.mem_insert, finset.mem_singleton], rintro (rfl|rfl); assumption }, { simpa using H } } end /-- A nonemtpy open subset of a preirreducible subspace is dense in the subspace. -/ lemma subset_closure_inter_of_is_preirreducible_of_is_open {S U : set α} (hS : is_preirreducible S) (hU : is_open U) (h : (S ∩ U).nonempty) : S ⊆ closure (S ∩ U) := begin by_contra h', obtain ⟨x, h₁, h₂, h₃⟩ := hS _ (closure (S ∩ U))ᶜ hU (is_open_compl_iff.mpr is_closed_closure) h (set.inter_compl_nonempty_iff.mpr h'), exact h₃ (subset_closure ⟨h₁, h₂⟩) end /-- If `∅ ≠ U ⊆ S ⊆ Z` such that `U` is open and `Z` is preirreducible, then `S` is irreducible. -/ lemma is_preirreducible.subset_irreducible {S U Z : set α} (hZ : is_preirreducible Z) (hU : U.nonempty) (hU' : is_open U) (h₁ : U ⊆ S) (h₂ : S ⊆ Z) : is_irreducible S := begin classical, obtain ⟨z, hz⟩ := hU, replace hZ : is_irreducible Z := ⟨⟨z, h₂ (h₁ hz)⟩, hZ⟩, refine ⟨⟨z, h₁ hz⟩, _⟩, rintros u v hu hv ⟨x, hx, hx'⟩ ⟨y, hy, hy'⟩, obtain ⟨a, -, ha'⟩ := is_irreducible_iff_sInter.mp hZ {U, u, v} (by tidy) _, replace ha' : a ∈ U ∧ a ∈ u ∧ a ∈ v := by simpa using ha', exact ⟨a, h₁ ha'.1, ha'.2⟩, { intros U H, simp only [finset.mem_insert, finset.mem_singleton] at H, rcases H with (rfl|rfl|rfl), exacts [⟨z, h₂ (h₁ hz), hz⟩, ⟨x, h₂ hx, hx'⟩, ⟨y, h₂ hy, hy'⟩] } end lemma is_preirreducible.open_subset {Z U : set α} (hZ : is_preirreducible Z) (hU : is_open U) (hU' : U ⊆ Z) : is_preirreducible U := U.eq_empty_or_nonempty.elim (λ h, h.symm ▸ is_preirreducible_empty) (λ h, (hZ.subset_irreducible h hU (λ _, id) hU').2) lemma is_preirreducible.interior {Z : set α} (hZ : is_preirreducible Z) : is_preirreducible (interior Z) := hZ.open_subset is_open_interior interior_subset lemma is_preirreducible.preimage {Z : set α} (hZ : is_preirreducible Z) {f : β → α} (hf : open_embedding f) : is_preirreducible (f ⁻¹' Z) := begin rintros U V hU hV ⟨x, hx, hx'⟩ ⟨y, hy, hy'⟩, obtain ⟨_, h₁, ⟨z, h₂, rfl⟩, ⟨z', h₃, h₄⟩⟩ := hZ _ _ (hf.is_open_map _ hU) (hf.is_open_map _ hV) ⟨f x, hx, set.mem_image_of_mem f hx'⟩ ⟨f y, hy, set.mem_image_of_mem f hy'⟩, cases hf.inj h₄, exact ⟨z, h₁, h₂, h₃⟩ end end preirreducible
f0840e6163ff5b41a93b2f4fe5512aa55e4e906d
ac89c256db07448984849346288e0eeffe8b20d0
/stage0/src/Lean/Elab/Structure.lean
9ffeb64ceb8f9e8e9e0c26c3e555cf0014167f0b
[ "Apache-2.0" ]
permissive
chepinzhang/lean4
002cc667f35417a418f0ebc9cb4a44559bb0ccac
24fe2875c68549b5481f07c57eab4ad4a0ae5305
refs/heads/master
1,688,942,838,326
1,628,801,942,000
1,628,801,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
44,112
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Parser.Command import Lean.Meta.Closure import Lean.Meta.SizeOf import Lean.Meta.Injective import Lean.Meta.Structure import Lean.Meta.AppBuilder import Lean.Elab.Command import Lean.Elab.DeclModifiers import Lean.Elab.DeclUtil import Lean.Elab.Inductive import Lean.Elab.DeclarationRange import Lean.Elab.Binders namespace Lean.Elab.Command open Meta /- Recall that the `structure command syntax is ``` leading_parser (structureTk <|> classTk) >> declId >> many Term.bracketedBinder >> optional «extends» >> Term.optType >> optional (" := " >> optional structCtor >> structFields) ``` -/ structure StructCtorView where ref : Syntax modifiers : Modifiers inferMod : Bool -- true if `{}` is used in the constructor declaration name : Name declName : Name structure StructFieldView where ref : Syntax modifiers : Modifiers binderInfo : BinderInfo inferMod : Bool declName : Name name : Name binders : Syntax type? : Option Syntax value? : Option Syntax structure StructView where ref : Syntax modifiers : Modifiers scopeLevelNames : List Name -- All `universe` declarations in the current scope allUserLevelNames : List Name -- `scopeLevelNames` ++ explicit universe parameters provided in the `structure` command isClass : Bool declName : Name scopeVars : Array Expr -- All `variable` declaration in the current scope params : Array Expr -- Explicit parameters provided in the `structure` command parents : Array Syntax type : Syntax ctor : StructCtorView fields : Array StructFieldView inductive StructFieldKind where | newField | copiedField | fromParent | subobject deriving Inhabited, BEq structure StructFieldInfo where name : Name declName : Name -- Remark: for `fromParent` fields, `declName` is only relevant in the generation of auxiliary "default value" functions. fvar : Expr kind : StructFieldKind inferMod : Bool := false value? : Option Expr := none deriving Inhabited def StructFieldInfo.isFromParent (info : StructFieldInfo) : Bool := match info.kind with | StructFieldKind.fromParent => true | _ => false def StructFieldInfo.isSubobject (info : StructFieldInfo) : Bool := match info.kind with | StructFieldKind.subobject => true | _ => false /- Auxiliary declaration for `mkProjections` -/ structure ProjectionInfo where declName : Name inferMod : Bool structure ElabStructResult where decl : Declaration projInfos : List ProjectionInfo projInstances : List Name -- projections (to parent classes) that must be marked as instances. mctx : MetavarContext lctx : LocalContext localInsts : LocalInstances defaultAuxDecls : Array (Name × Expr × Expr) private def defaultCtorName := `mk /- The structure constructor syntax is ``` leading_parser try (declModifiers >> ident >> optional inferMod >> " :: ") ``` -/ private def expandCtor (structStx : Syntax) (structModifiers : Modifiers) (structDeclName : Name) : TermElabM StructCtorView := do let useDefault := do let declName := structDeclName ++ defaultCtorName addAuxDeclarationRanges declName structStx[2] structStx[2] pure { ref := structStx, modifiers := {}, inferMod := false, name := defaultCtorName, declName } if structStx[5].isNone then useDefault else let optCtor := structStx[5][1] if optCtor.isNone then useDefault else let ctor := optCtor[0] withRef ctor do let ctorModifiers ← elabModifiers ctor[0] checkValidCtorModifier ctorModifiers if ctorModifiers.isPrivate && structModifiers.isPrivate then throwError "invalid 'private' constructor in a 'private' structure" if ctorModifiers.isProtected && structModifiers.isPrivate then throwError "invalid 'protected' constructor in a 'private' structure" let inferMod := !ctor[2].isNone let name := ctor[1].getId let declName := structDeclName ++ name let declName ← applyVisibility ctorModifiers.visibility declName addDocString' declName ctorModifiers.docString? addAuxDeclarationRanges declName ctor[1] ctor[1] pure { ref := ctor, name, modifiers := ctorModifiers, inferMod, declName } def checkValidFieldModifier (modifiers : Modifiers) : TermElabM Unit := do if modifiers.isNoncomputable then throwError "invalid use of 'noncomputable' in field declaration" if modifiers.isPartial then throwError "invalid use of 'partial' in field declaration" if modifiers.isUnsafe then throwError "invalid use of 'unsafe' in field declaration" if modifiers.attrs.size != 0 then throwError "invalid use of attributes in field declaration" /- ``` def structExplicitBinder := leading_parser atomic (declModifiers true >> "(") >> many1 ident >> optional inferMod >> optDeclSig >> optional (Term.binderTactic <|> Term.binderDefault) >> ")" def structImplicitBinder := leading_parser atomic (declModifiers true >> "{") >> many1 ident >> optional inferMod >> declSig >> "}" def structInstBinder := leading_parser atomic (declModifiers true >> "[") >> many1 ident >> optional inferMod >> declSig >> "]" def structSimpleBinder := leading_parser atomic (declModifiers true >> ident) >> optional inferMod >> optDeclSig >> optional (Term.binderTactic <|> Term.binderDefault) def structFields := leading_parser many (structExplicitBinder <|> structImplicitBinder <|> structInstBinder) ``` -/ private def expandFields (structStx : Syntax) (structModifiers : Modifiers) (structDeclName : Name) : TermElabM (Array StructFieldView) := let fieldBinders := if structStx[5].isNone then #[] else structStx[5][2][0].getArgs fieldBinders.foldlM (init := #[]) fun (views : Array StructFieldView) fieldBinder => withRef fieldBinder do let mut fieldBinder := fieldBinder if fieldBinder.getKind == ``Parser.Command.structSimpleBinder then fieldBinder := Syntax.node ``Parser.Command.structExplicitBinder #[ fieldBinder[0], mkAtomFrom fieldBinder "(", mkNullNode #[ fieldBinder[1] ], fieldBinder[2], fieldBinder[3], fieldBinder[4], mkAtomFrom fieldBinder ")" ] let k := fieldBinder.getKind let binfo ← if k == ``Parser.Command.structExplicitBinder then pure BinderInfo.default else if k == ``Parser.Command.structImplicitBinder then pure BinderInfo.implicit else if k == ``Parser.Command.structInstBinder then pure BinderInfo.instImplicit else throwError "unexpected kind of structure field" let fieldModifiers ← elabModifiers fieldBinder[0] checkValidFieldModifier fieldModifiers if fieldModifiers.isPrivate && structModifiers.isPrivate then throwError "invalid 'private' field in a 'private' structure" if fieldModifiers.isProtected && structModifiers.isPrivate then throwError "invalid 'protected' field in a 'private' structure" let inferMod := !fieldBinder[3].isNone let (binders, type?) ← if binfo == BinderInfo.default then let (binders, type?) := expandOptDeclSig fieldBinder[4] let optBinderTacticDefault := fieldBinder[5] if optBinderTacticDefault.isNone then pure (binders, type?) else if optBinderTacticDefault[0].getKind != ``Parser.Term.binderTactic then pure (binders, type?) else let binderTactic := optBinderTacticDefault[0] match type? with | none => throwErrorAt binderTactic "invalid field declaration, type must be provided when auto-param (tactic) is used" | some type => let tac := binderTactic[2] let name ← Term.declareTacticSyntax tac -- The tactic should be for binders+type. -- It is safe to reset the binders to a "null" node since there is no value to be elaborated let type ← `(forall $(binders.getArgs):bracketedBinder*, $type) let type ← `(autoParam $type $(mkIdentFrom tac name)) pure (mkNullNode, some type) else let (binders, type) := expandDeclSig fieldBinder[4] pure (binders, some type) let value? ← if binfo != BinderInfo.default then pure none else let optBinderTacticDefault := fieldBinder[5] -- trace[Elab.struct] ">>> {optBinderTacticDefault}" if optBinderTacticDefault.isNone then pure none else if optBinderTacticDefault[0].getKind == ``Parser.Term.binderTactic then pure none else -- binderDefault := leading_parser " := " >> termParser pure (some optBinderTacticDefault[0][1]) let idents := fieldBinder[2].getArgs idents.foldlM (init := views) fun (views : Array StructFieldView) ident => withRef ident do let name := ident.getId.eraseMacroScopes unless name.isAtomic do throwErrorAt ident "invalid field name '{name.eraseMacroScopes}', field names must be atomic" let declName := structDeclName ++ name let declName ← applyVisibility fieldModifiers.visibility declName addDocString' declName fieldModifiers.docString? return views.push { ref := ident modifiers := fieldModifiers binderInfo := binfo inferMod declName name binders type? value? } private def validStructType (type : Expr) : Bool := match type with | Expr.sort .. => true | _ => false private def findFieldInfo? (infos : Array StructFieldInfo) (fieldName : Name) : Option StructFieldInfo := infos.find? fun info => info.name == fieldName private def containsFieldName (infos : Array StructFieldInfo) (fieldName : Name) : Bool := (findFieldInfo? infos fieldName).isSome private def updateFieldInfoVal (infos : Array StructFieldInfo) (fieldName : Name) (value : Expr) : Array StructFieldInfo := infos.map fun info => if info.name == fieldName then { info with value? := value } else info register_builtin_option structureDiamondWarning : Bool := { defValue := false descr := "enable/disable warning messages for structure diamonds" } /-- Return `some fieldName` if field `fieldName` of the parent structure `parentStructName` is already in `infos` -/ private def findExistingField? (infos : Array StructFieldInfo) (parentStructName : Name) : CoreM (Option Name) := do let fieldNames := getStructureFieldsFlattened (← getEnv) parentStructName for fieldName in fieldNames do if containsFieldName infos fieldName then return some fieldName return none private partial def processSubfields (structDeclName : Name) (parentFVar : Expr) (parentStructName : Name) (subfieldNames : Array Name) (infos : Array StructFieldInfo) (k : Array StructFieldInfo → TermElabM α) : TermElabM α := go 0 infos where go (i : Nat) (infos : Array StructFieldInfo) := do if h : i < subfieldNames.size then let subfieldName := subfieldNames.get ⟨i, h⟩ if containsFieldName infos subfieldName then throwError "field '{subfieldName}' from '{parentStructName}' has already been declared" let val ← mkProjection parentFVar subfieldName let type ← inferType val withLetDecl subfieldName type val fun subfieldFVar => /- The following `declName` is only used for creating the `_default` auxiliary declaration name when its default value is overwritten in the structure. If the default value is not overwritten, then its value is irrelevant. -/ let declName := structDeclName ++ subfieldName let infos := infos.push { name := subfieldName, declName, fvar := subfieldFVar, kind := StructFieldKind.fromParent } go (i+1) infos else k infos /-- Return `some (structName, fieldName, struct)` if `e` is a projection function application -/ private def isProjFnApp? (e : Expr) : MetaM (Option (Name × Name × Expr)) := do match e.getAppFn with | Expr.const declName .. => match (← getProjectionFnInfo? declName) with | some { ctorName := ctorName, numParams := n, .. } => if declName.isStr && e.getAppNumArgs == n+1 then let ConstantInfo.ctorInfo ctorVal ← getConstInfo ctorName | unreachable! return some (ctorVal.induct, declName.getString!, e.appArg!) else return none | _ => return none | _ => return none /-- Return `some fieldName`, if `e` is an expression that represents an access to field `fieldName` of the structure `s`. The name of the structure type must be `structName`. -/ private partial def isProjectionOf? (e : Expr) (structName : Name) (s : Expr) : MetaM (Option Name) := do if let some (baseStructName, fieldName, e) ← isProjFnApp? e then if let some path ← visit e #[] then if let some path' := getPathToBaseStructure? (← getEnv) baseStructName structName then if path'.toArray == path.reverse then return some fieldName return none where visit (e : Expr) (path : Array Name) : MetaM (Option (Array Name)) := do if e == s then return some path -- Check whether `e` is a `toParent` field if let some (_, _, e') ← isProjFnApp? e then visit e' (path.push e.getAppFn.constName!) else return none private def getFieldType (infos : Array StructFieldInfo) (parentStructName : Name) (parentType : Expr) (fieldName : Name) : MetaM Expr := do withLocalDeclD (← mkFreshId) parentType fun parent => do let proj ← mkProjection parent fieldName let projType ← inferType proj /- Eliminate occurrences of `parent`. This may happen when structure contains dependent fields -/ let visit (e : Expr) : MetaM TransformStep := do if let some fieldName ← isProjectionOf? e parentStructName parent then -- trace[Meta.debug] "field '{fieldName}' of {e}" match (← findFieldInfo? infos fieldName) with | some existingFieldInfo => return TransformStep.done existingFieldInfo.fvar | none => throwError "unexpected field access {indentExpr e}" else return TransformStep.visit e Meta.transform projType (pre := visit) private def toVisibility (fieldInfo : StructureFieldInfo) : CoreM Visibility := do if isProtected (← getEnv) fieldInfo.projFn then return Visibility.protected else if isPrivateName fieldInfo.projFn then return Visibility.private else return Visibility.regular abbrev FieldMap := NameMap Expr -- Map from field name to expression representing the field /-- Reduce projetions of the structures in `structNames` -/ private def reduceProjs (e : Expr) (structNames : NameSet) : MetaM Expr := let reduce (e : Expr) : MetaM TransformStep := do match (← reduceProjOf? e structNames.contains) with | some v => return TransformStep.done v | _ => return TransformStep.done e transform e (post := reduce) /-- Copy the default value for field `fieldName` set at structure `structName`. The arguments for the `_default` auxiliary function are provided by `fieldMap`. Recall some of the entries in `fieldMap` are constructor applications, and they needed to be reduced using `reduceProjs`. Otherwise, the produced default value may be "cyclic". That is, we reduce projections of the structures in `expandedStructNames`. Here is an example that shows why the reduction is needed. ``` structure A where a : Nat structure B where a : Nat b : Nat c : Nat structure C extends B where d : Nat c := b + d structure D extends A, C #print D.c._default ``` Without the reduction, it produces ``` def D.c._default : A → Nat → Nat → Nat → Nat := fun toA b c d => id ({ a := toA.a, b := b, c := c : B }.b + d) ``` -/ private partial def copyDefaultValue? (fieldMap : FieldMap) (expandedStructNames : NameSet) (structName : Name) (fieldName : Name) : TermElabM (Option Expr) := do match getDefaultFnForField? (← getEnv) structName fieldName with | none => return none | some defaultFn => let cinfo ← getConstInfo defaultFn let us ← mkFreshLevelMVarsFor cinfo go? (cinfo.instantiateValueLevelParams us) where failed : TermElabM (Option Expr) := do logWarning s!"ignoring default value for field '{fieldName}' defined at '{structName}'" return none go? (e : Expr) : TermElabM (Option Expr) := do match e with | Expr.lam n d b c => if c.binderInfo.isExplicit then let fieldName := n match fieldMap.find? n with | none => failed | some val => let valType ← inferType val if (← isDefEq valType d) then go? (b.instantiate1 val) else failed else let arg ← mkFreshExprMVar d go? (b.instantiate1 arg) | e => let r := if e.isAppOfArity ``id 2 then e.appArg! else e return some (← reduceProjs (← instantiateMVars e.appArg!) expandedStructNames) private partial def copyNewFieldsFrom (structDeclName : Name) (infos : Array StructFieldInfo) (parentType : Expr) (k : Array StructFieldInfo → TermElabM α) : TermElabM α := do copyFields infos {} parentType fun infos _ _ => k infos where copyFields (infos : Array StructFieldInfo) (expandedStructNames : NameSet) (parentType : Expr) (k : Array StructFieldInfo → FieldMap → NameSet → TermElabM α) : TermElabM α := do let parentStructName ← getStructureName parentType let fieldNames := getStructureFields (← getEnv) parentStructName let rec copy (i : Nat) (infos : Array StructFieldInfo) (fieldMap : FieldMap) (expandedStructNames : NameSet) : TermElabM α := do if h : i < fieldNames.size then let fieldName := fieldNames.get ⟨i, h⟩ let fieldType ← getFieldType infos parentStructName parentType fieldName match (← findFieldInfo? infos fieldName) with | some existingFieldInfo => let existingFieldType ← inferType existingFieldInfo.fvar unless (← isDefEq fieldType existingFieldType) do throwError "parent field type mismatch, field '{fieldName}' from parent '{parentStructName}' {← mkHasTypeButIsExpectedMsg fieldType existingFieldType}" /- Remark: if structure has a default value for this field, it will be set at the `processOveriddenDefaultValues` below. -/ copy (i+1) infos (fieldMap.insert fieldName existingFieldInfo.fvar) expandedStructNames | none => let some fieldInfo ← getFieldInfo? (← getEnv) parentStructName fieldName | unreachable! let addNewField : TermElabM α := do let value? ← copyDefaultValue? fieldMap expandedStructNames parentStructName fieldName withLocalDecl fieldName fieldInfo.binderInfo fieldType fun fieldFVar => do let fieldDeclName := structDeclName ++ fieldName let fieldDeclName ← applyVisibility (← toVisibility fieldInfo) fieldDeclName let infos := infos.push { name := fieldName, declName := fieldDeclName, fvar := fieldFVar, value?, kind := StructFieldKind.copiedField, inferMod := fieldInfo.inferMod } copy (i+1) infos (fieldMap.insert fieldName fieldFVar) expandedStructNames if fieldInfo.subobject?.isSome then let fieldParentStructName ← getStructureName fieldType if (← findExistingField? infos fieldParentStructName).isSome then -- See comment at `copyDefaultValue?` let expandedStructNames := expandedStructNames.insert fieldParentStructName copyFields infos expandedStructNames fieldType fun infos nestedFieldMap expandedStructNames => do let fieldVal ← mkCompositeField fieldType nestedFieldMap trace[Meta.debug] "composite, {fieldName} := {fieldVal}" copy (i+1) infos (fieldMap.insert fieldName fieldVal) expandedStructNames else addNewField else addNewField else let infos ← processOveriddenDefaultValues infos fieldMap expandedStructNames parentStructName k infos fieldMap expandedStructNames copy 0 infos {} expandedStructNames processOveriddenDefaultValues (infos : Array StructFieldInfo) (fieldMap : FieldMap) (expandedStructNames : NameSet) (parentStructName : Name) : TermElabM (Array StructFieldInfo) := infos.mapM fun info => do match (← copyDefaultValue? fieldMap expandedStructNames parentStructName info.name) with | some value => return { info with value? := value } | none => return info mkCompositeField (parentType : Expr) (fieldMap : FieldMap) : TermElabM Expr := do let env ← getEnv let Expr.const parentStructName us _ ← pure parentType.getAppFn | unreachable! let parentCtor := getStructureCtor env parentStructName let mut result := mkAppN (mkConst parentCtor.name us) parentType.getAppArgs for fieldName in getStructureFields env parentStructName do match fieldMap.find? fieldName with | some val => result := mkApp result val | none => throwError "failed to copied fields from parent structure{indentExpr parentType}" -- TODO improve error message return result private partial def mkToParentName (parentStructName : Name) (p : Name → Bool) : Name := do let base := Name.mkSimple $ "to" ++ parentStructName.eraseMacroScopes.getString! if p base then base else let rec go (i : Nat) : Name := let curr := base.appendIndexAfter i if p curr then curr else go (i+1) go 1 private partial def withParents (view : StructView) (k : Array StructFieldInfo → Array Expr → TermElabM α) : TermElabM α := do go 0 #[] #[] where go (i : Nat) (infos : Array StructFieldInfo) (copiedParents : Array Expr) : TermElabM α := do if h : i < view.parents.size then let parentStx := view.parents.get ⟨i, h⟩ withRef parentStx do let parentType ← Term.elabType parentStx let parentStructName ← getStructureName parentType if let some existingFieldName ← findExistingField? infos parentStructName then if structureDiamondWarning.get (← getOptions) then logWarning s!"field '{existingFieldName}' from '{parentStructName}' has already been declared" copyNewFieldsFrom view.declName infos parentType fun infos => go (i+1) infos (copiedParents.push parentType) -- TODO: if `class`, then we need to create a let-decl that stores the local instance for the `parentStructure` else let env ← getEnv let subfieldNames := getStructureFieldsFlattened env parentStructName let toParentName := mkToParentName parentStructName fun n => !containsFieldName infos n && !subfieldNames.contains n let binfo := if view.isClass && isClass env parentStructName then BinderInfo.instImplicit else BinderInfo.default withLocalDecl toParentName binfo parentType fun parentFVar => let infos := infos.push { name := toParentName, declName := view.declName ++ toParentName, fvar := parentFVar, kind := StructFieldKind.subobject } processSubfields view.declName parentFVar parentStructName subfieldNames infos fun infos => go (i+1) infos copiedParents else k infos copiedParents private def elabFieldTypeValue (view : StructFieldView) : TermElabM (Option Expr × Option Expr) := do Term.withAutoBoundImplicit <| Term.elabBinders view.binders.getArgs fun params => do match view.type? with | none => match view.value? with | none => return (none, none) | some valStx => Term.synthesizeSyntheticMVarsNoPostponing let params ← Term.addAutoBoundImplicits params let value ← Term.elabTerm valStx none let value ← mkLambdaFVars params value return (none, value) | some typeStx => let type ← Term.elabType typeStx Term.synthesizeSyntheticMVarsNoPostponing let params ← Term.addAutoBoundImplicits params match view.value? with | none => let type ← mkForallFVars params type return (type, none) | some valStx => let value ← Term.elabTermEnsuringType valStx type Term.synthesizeSyntheticMVarsNoPostponing let type ← mkForallFVars params type let value ← mkLambdaFVars params value return (type, value) private partial def withFields (views : Array StructFieldView) (infos : Array StructFieldInfo) (k : Array StructFieldInfo → TermElabM α) : TermElabM α := do go 0 {} infos where go (i : Nat) (defaultValsOverridden : NameSet) (infos : Array StructFieldInfo) : TermElabM α := do if h : i < views.size then let view := views.get ⟨i, h⟩ withRef view.ref do match findFieldInfo? infos view.name with | none => let (type?, value?) ← elabFieldTypeValue view match type?, value? with | none, none => throwError "invalid field, type expected" | some type, _ => withLocalDecl view.name view.binderInfo type fun fieldFVar => let infos := infos.push { name := view.name, declName := view.declName, fvar := fieldFVar, value? := value?, kind := StructFieldKind.newField, inferMod := view.inferMod } go (i+1) defaultValsOverridden infos | none, some value => let type ← inferType value withLocalDecl view.name view.binderInfo type fun fieldFVar => let infos := infos.push { name := view.name, declName := view.declName, fvar := fieldFVar, value? := value, kind := StructFieldKind.newField, inferMod := view.inferMod } go (i+1) defaultValsOverridden infos | some info => let updateDefaultValue (fromParent : Bool) : TermElabM α := do match view.value? with | none => throwError "field '{view.name}' has been declared in parent structure" | some valStx => if let some type := view.type? then throwErrorAt type "omit field '{view.name}' type to set default value" else if defaultValsOverridden.contains info.name then throwError "field '{view.name}' new default value has already been set" let defaultValsOverridden := defaultValsOverridden.insert info.name let mut valStx := valStx if view.binders.getArgs.size > 0 then valStx ← `(fun $(view.binders.getArgs)* => $valStx:term) let fvarType ← inferType info.fvar let value ← Term.elabTermEnsuringType valStx fvarType let infos := updateFieldInfoVal infos info.name value go (i+1) defaultValsOverridden infos match info.kind with | StructFieldKind.newField => throwError "field '{view.name}' has already been declared" | StructFieldKind.subobject => throwError "unexpected subobject field reference" -- improve error message | StructFieldKind.copiedField => updateDefaultValue false | StructFieldKind.fromParent => updateDefaultValue true else k infos private def getResultUniverse (type : Expr) : TermElabM Level := do let type ← whnf type match type with | Expr.sort u _ => pure u | _ => throwError "unexpected structure resulting type" private def collectUsed (params : Array Expr) (fieldInfos : Array StructFieldInfo) : StateRefT CollectFVars.State MetaM Unit := do params.forM fun p => do let type ← inferType p Term.collectUsedFVars type fieldInfos.forM fun info => do let fvarType ← inferType info.fvar Term.collectUsedFVars fvarType match info.value? with | none => pure () | some value => Term.collectUsedFVars value private def removeUnused (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo) : TermElabM (LocalContext × LocalInstances × Array Expr) := do let (_, used) ← (collectUsed params fieldInfos).run {} Term.removeUnused scopeVars used private def withUsed {α} (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo) (k : Array Expr → TermElabM α) : TermElabM α := do let (lctx, localInsts, vars) ← removeUnused scopeVars params fieldInfos withLCtx lctx localInsts <| k vars private def levelMVarToParamFVar (fvar : Expr) : StateRefT Nat TermElabM Unit := do let type ← inferType fvar discard <| Term.levelMVarToParam' type private def levelMVarToParamFVars (fvars : Array Expr) : StateRefT Nat TermElabM Unit := fvars.forM levelMVarToParamFVar private def levelMVarToParamAux (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo) : StateRefT Nat TermElabM (Array StructFieldInfo) := do levelMVarToParamFVars scopeVars levelMVarToParamFVars params fieldInfos.mapM fun info => do levelMVarToParamFVar info.fvar match info.value? with | none => pure info | some value => let value ← Term.levelMVarToParam' value pure { info with value? := value } private def levelMVarToParam (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo) : TermElabM (Array StructFieldInfo) := (levelMVarToParamAux scopeVars params fieldInfos).run' 1 private partial def collectUniversesFromFields (r : Level) (rOffset : Nat) (fieldInfos : Array StructFieldInfo) : TermElabM (Array Level) := do fieldInfos.foldlM (init := #[]) fun (us : Array Level) (info : StructFieldInfo) => do let type ← inferType info.fvar let u ← getLevel type let u ← instantiateLevelMVars u accLevelAtCtor u r rOffset us private def updateResultingUniverse (fieldInfos : Array StructFieldInfo) (type : Expr) : TermElabM Expr := do let r ← getResultUniverse type let rOffset : Nat := r.getOffset let r : Level := r.getLevelOffset match r with | Level.mvar mvarId _ => let us ← collectUniversesFromFields r rOffset fieldInfos let rNew := mkResultUniverse us rOffset assignLevelMVar mvarId rNew instantiateMVars type | _ => throwError "failed to compute resulting universe level of structure, provide universe explicitly" private def collectLevelParamsInFVar (s : CollectLevelParams.State) (fvar : Expr) : TermElabM CollectLevelParams.State := do let type ← inferType fvar let type ← instantiateMVars type return collectLevelParams s type private def collectLevelParamsInFVars (fvars : Array Expr) (s : CollectLevelParams.State) : TermElabM CollectLevelParams.State := fvars.foldlM collectLevelParamsInFVar s private def collectLevelParamsInStructure (structType : Expr) (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo) : TermElabM (Array Name) := do let s := collectLevelParams {} structType let s ← collectLevelParamsInFVars scopeVars s let s ← collectLevelParamsInFVars params s let s ← fieldInfos.foldlM (init := s) fun s info => collectLevelParamsInFVar s info.fvar return s.params private def addCtorFields (fieldInfos : Array StructFieldInfo) : Nat → Expr → TermElabM Expr | 0, type => pure type | i+1, type => do let info := fieldInfos[i] let decl ← Term.getFVarLocalDecl! info.fvar let type ← instantiateMVars type let type := type.abstract #[info.fvar] match info.kind with | StructFieldKind.fromParent => let val := decl.value addCtorFields fieldInfos i (type.instantiate1 val) | _ => addCtorFields fieldInfos i (mkForall decl.userName decl.binderInfo decl.type type) private def mkCtor (view : StructView) (levelParams : List Name) (params : Array Expr) (fieldInfos : Array StructFieldInfo) : TermElabM Constructor := withRef view.ref do let type := mkAppN (mkConst view.declName (levelParams.map mkLevelParam)) params let type ← addCtorFields fieldInfos fieldInfos.size type let type ← mkForallFVars params type let type ← instantiateMVars type let type := type.inferImplicit params.size !view.ctor.inferMod -- trace[Meta.debug] "ctor type {type}" pure { name := view.ctor.declName, type } @[extern "lean_mk_projections"] private constant mkProjections (env : Environment) (structName : Name) (projs : List ProjectionInfo) (isClass : Bool) : Except KernelException Environment private def addProjections (structName : Name) (projs : List ProjectionInfo) (isClass : Bool) : TermElabM Unit := do let env ← getEnv match mkProjections env structName projs isClass with | Except.ok env => setEnv env | Except.error ex => throwKernelException ex private def registerStructure (structName : Name) (infos : Array StructFieldInfo) : TermElabM Unit := do let fields ← infos.filterMapM fun info => do if info.kind == StructFieldKind.fromParent then return none else return some { fieldName := info.name projFn := info.declName inferMod := info.inferMod binderInfo := (← getFVarLocalDecl info.fvar).binderInfo subobject? := if info.kind == StructFieldKind.subobject then match (← getEnv).find? info.declName with | some (ConstantInfo.defnInfo val) => match val.type.getForallBody.getAppFn with | Expr.const parentName .. => some parentName | _ => panic! "ill-formed structure" | _ => panic! "ill-formed environment" else none } modifyEnv fun env => Lean.registerStructure env { structName, fields } private def mkAuxConstructions (declName : Name) : TermElabM Unit := do let env ← getEnv let hasUnit := env.contains `PUnit let hasEq := env.contains `Eq let hasHEq := env.contains `HEq mkRecOn declName if hasUnit then mkCasesOn declName if hasUnit && hasEq && hasHEq then mkNoConfusion declName private def addDefaults (lctx : LocalContext) (defaultAuxDecls : Array (Name × Expr × Expr)) : TermElabM Unit := do let localInsts ← getLocalInstances withLCtx lctx localInsts do defaultAuxDecls.forM fun (declName, type, value) => do let value ← instantiateMVars value if value.hasExprMVar then throwError "invalid default value for field, it contains metavariables{indentExpr value}" /- The identity function is used as "marker". -/ let value ← mkId value discard <| mkAuxDefinition declName type value (zeta := true) setReducibleAttribute declName private partial def mkCoercionToCopiedParent (levelParams : List Name) (params : Array Expr) (view : StructView) (parentType : Expr) : MetaM Unit := do let env ← getEnv let structName := view.declName let sourceFieldNames := getStructureFieldsFlattened env structName let structType ← mkAppN (Lean.mkConst structName (levelParams.map mkLevelParam)) params let Expr.const parentStructName us _ ← pure parentType.getAppFn | unreachable! let binfo := if view.isClass && isClass env parentStructName then BinderInfo.instImplicit else BinderInfo.default withLocalDecl `self binfo structType fun source => do let declType ← instantiateMVars (← mkForallFVars params (← mkForallFVars #[source] parentType)) let declType := declType.inferImplicit params.size true let rec copyFields (parentType : Expr) : MetaM Expr := do let Expr.const parentStructName us _ ← pure parentType.getAppFn | unreachable! let parentCtor := getStructureCtor env parentStructName let mut result := mkAppN (mkConst parentCtor.name us) parentType.getAppArgs for fieldName in getStructureFields env parentStructName do if sourceFieldNames.contains fieldName then let fieldVal ← mkProjection source fieldName result := mkApp result fieldVal else -- fieldInfo must be a field of `parentStructName` let some fieldInfo ← getFieldInfo? env parentStructName fieldName | unreachable! if fieldInfo.subobject?.isNone then throwError "failed to build coercion to parent structure" let resultType ← whnfD (← inferType result) unless resultType.isForall do throwError "failed to build coercion to parent structure, unexpect type{indentExpr resultType}" let fieldVal ← copyFields resultType.bindingDomain! result := mkApp result fieldVal return result let declVal ← instantiateMVars (← mkLambdaFVars params (← mkLambdaFVars #[source] (← copyFields parentType))) let declName := structName ++ mkToParentName (← getStructureName parentType) fun n => !env.contains (structName ++ n) addAndCompile <| Declaration.defnDecl { name := declName levelParams := levelParams type := declType value := declVal hints := ReducibilityHints.abbrev safety := if view.modifiers.isUnsafe then DefinitionSafety.unsafe else DefinitionSafety.safe } if binfo.isInstImplicit then addInstance declName AttributeKind.global (eval_prio default) else setReducibleAttribute declName private def elabStructureView (view : StructView) : TermElabM Unit := do view.fields.forM fun field => do if field.declName == view.ctor.declName then throwErrorAt field.ref "invalid field name '{field.name}', it is equal to structure constructor name" addAuxDeclarationRanges field.declName field.ref field.ref let numExplicitParams := view.params.size let type ← Term.elabType view.type unless validStructType type do throwErrorAt view.type "expected Type" withRef view.ref do withParents view fun fieldInfos copiedParents => do withFields view.fields fieldInfos fun fieldInfos => do Term.synthesizeSyntheticMVarsNoPostponing let u ← getResultUniverse type let inferLevel ← shouldInferResultUniverse u withUsed view.scopeVars view.params fieldInfos fun scopeVars => do let numParams := scopeVars.size + numExplicitParams let fieldInfos ← levelMVarToParam scopeVars view.params fieldInfos let type ← withRef view.ref do if inferLevel then updateResultingUniverse fieldInfos type else checkResultingUniverse (← getResultUniverse type) pure type trace[Elab.structure] "type: {type}" let usedLevelNames ← collectLevelParamsInStructure type scopeVars view.params fieldInfos match sortDeclLevelParams view.scopeLevelNames view.allUserLevelNames usedLevelNames with | Except.error msg => withRef view.ref <| throwError msg | Except.ok levelParams => let params := scopeVars ++ view.params let ctor ← mkCtor view levelParams params fieldInfos let type ← mkForallFVars params type let type ← instantiateMVars type let indType := { name := view.declName, type := type, ctors := [ctor] : InductiveType } let decl := Declaration.inductDecl levelParams params.size [indType] view.modifiers.isUnsafe Term.ensureNoUnassignedMVars decl addDecl decl let projInfos := (fieldInfos.filter fun (info : StructFieldInfo) => !info.isFromParent).toList.map fun (info : StructFieldInfo) => { declName := info.declName, inferMod := info.inferMod : ProjectionInfo } addProjections view.declName projInfos view.isClass registerStructure view.declName fieldInfos mkAuxConstructions view.declName let instParents ← fieldInfos.filterM fun info => do let decl ← Term.getFVarLocalDecl! info.fvar pure (info.isSubobject && decl.binderInfo.isInstImplicit) let projInstances := instParents.toList.map fun info => info.declName Term.applyAttributesAt view.declName view.modifiers.attrs AttributeApplicationTime.afterTypeChecking projInstances.forM fun declName => addInstance declName AttributeKind.global (eval_prio default) copiedParents.forM fun parent => mkCoercionToCopiedParent levelParams params view parent let lctx ← getLCtx let fieldsWithDefault := fieldInfos.filter fun info => info.value?.isSome let defaultAuxDecls ← fieldsWithDefault.mapM fun info => do let type ← inferType info.fvar pure (mkDefaultFnOfProjFn info.declName, type, info.value?.get!) /- The `lctx` and `defaultAuxDecls` are used to create the auxiliary "default value" declarations The parameters `params` for these definitions must be marked as implicit, and all others as explicit. -/ let lctx := params.foldl (init := lctx) fun (lctx : LocalContext) (p : Expr) => lctx.setBinderInfo p.fvarId! BinderInfo.implicit let lctx := fieldInfos.foldl (init := lctx) fun (lctx : LocalContext) (info : StructFieldInfo) => if info.isFromParent then lctx -- `fromParent` fields are elaborated as let-decls, and are zeta-expanded when creating "default value" auxiliary functions else lctx.setBinderInfo info.fvar.fvarId! BinderInfo.default addDefaults lctx defaultAuxDecls /- leading_parser (structureTk <|> classTk) >> declId >> many Term.bracketedBinder >> optional «extends» >> Term.optType >> " := " >> optional structCtor >> structFields >> optDeriving where def «extends» := leading_parser " extends " >> sepBy1 termParser ", " def typeSpec := leading_parser " : " >> termParser def optType : Parser := optional typeSpec def structFields := leading_parser many (structExplicitBinder <|> structImplicitBinder <|> structInstBinder) def structCtor := leading_parser try (declModifiers >> ident >> optional inferMod >> " :: ") -/ def elabStructure (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do checkValidInductiveModifier modifiers let isClass := stx[0].getKind == ``Parser.Command.classTk let modifiers := if isClass then modifiers.addAttribute { name := `class } else modifiers let declId := stx[1] let params := stx[2].getArgs let exts := stx[3] let parents := if exts.isNone then #[] else exts[0][1].getSepArgs let optType := stx[4] let derivingClassViews ← getOptDerivingClasses stx[6] let type ← if optType.isNone then `(Sort _) else pure optType[0][1] let declName ← runTermElabM none fun scopeVars => do let scopeLevelNames ← Term.getLevelNames let ⟨name, declName, allUserLevelNames⟩ ← Elab.expandDeclId (← getCurrNamespace) scopeLevelNames declId modifiers addDeclarationRanges declName stx Term.withDeclName declName do let ctor ← expandCtor stx modifiers declName let fields ← expandFields stx modifiers declName Term.withLevelNames allUserLevelNames <| Term.withAutoBoundImplicit <| Term.elabBinders params fun params => do Term.synthesizeSyntheticMVarsNoPostponing let params ← Term.addAutoBoundImplicits params let allUserLevelNames ← Term.getLevelNames elabStructureView { ref := stx modifiers scopeLevelNames allUserLevelNames declName isClass scopeVars params parents type ctor fields } unless isClass do mkSizeOfInstances declName mkInjectiveTheorems declName return declName derivingClassViews.forM fun view => view.applyHandlers #[declName] builtin_initialize registerTraceClass `Elab.structure end Lean.Elab.Command
d35c6950f2196519aabfb3bb3e59d4c01c1a5632
618003631150032a5676f229d13a079ac875ff77
/src/data/int/basic.lean
1ce1347e4ea04b2f32c935f692c966dd06866762
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
53,716
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad The integers, with addition, multiplication, and subtraction. -/ import algebra.char_zero import init_.data.int.order import algebra.ring import data.list.range open nat namespace int instance : inhabited ℤ := ⟨int.zero⟩ @[simp] lemma default_eq_zero : default ℤ = 0 := rfl meta instance : has_to_format ℤ := ⟨λ z, to_string z⟩ meta instance : has_reflect ℤ := by tactic.mk_has_reflect_instance attribute [simp] int.coe_nat_add int.coe_nat_mul int.coe_nat_zero int.coe_nat_one int.coe_nat_succ attribute [simp] int.of_nat_eq_coe int.bodd @[simp] theorem add_def {a b : ℤ} : int.add a b = a + b := rfl @[simp] theorem mul_def {a b : ℤ} : int.mul a b = a * b := rfl @[simp] theorem coe_nat_mul_neg_succ (m n : ℕ) : (m : ℤ) * -[1+ n] = -(m * succ n) := rfl @[simp] theorem neg_succ_mul_coe_nat (m n : ℕ) : -[1+ m] * n = -(succ m * n) := rfl @[simp] theorem neg_succ_mul_neg_succ (m n : ℕ) : -[1+ m] * -[1+ n] = succ m * succ n := rfl @[simp, norm_cast] theorem coe_nat_le {m n : ℕ} : (↑m : ℤ) ≤ ↑n ↔ m ≤ n := coe_nat_le_coe_nat_iff m n @[simp, norm_cast] theorem coe_nat_lt {m n : ℕ} : (↑m : ℤ) < ↑n ↔ m < n := coe_nat_lt_coe_nat_iff m n @[simp, norm_cast] theorem coe_nat_inj' {m n : ℕ} : (↑m : ℤ) = ↑n ↔ m = n := int.coe_nat_eq_coe_nat_iff m n @[simp] theorem coe_nat_pos {n : ℕ} : (0 : ℤ) < n ↔ 0 < n := by rw [← int.coe_nat_zero, coe_nat_lt] @[simp] theorem coe_nat_eq_zero {n : ℕ} : (n : ℤ) = 0 ↔ n = 0 := by rw [← int.coe_nat_zero, coe_nat_inj'] theorem coe_nat_ne_zero {n : ℕ} : (n : ℤ) ≠ 0 ↔ n ≠ 0 := not_congr coe_nat_eq_zero lemma coe_nat_nonneg (n : ℕ) : 0 ≤ (n : ℤ) := coe_nat_le.2 (nat.zero_le _) lemma coe_nat_ne_zero_iff_pos {n : ℕ} : (n : ℤ) ≠ 0 ↔ 0 < n := ⟨λ h, nat.pos_of_ne_zero (coe_nat_ne_zero.1 h), λ h, (ne_of_lt (coe_nat_lt.2 h)).symm⟩ lemma coe_nat_succ_pos (n : ℕ) : 0 < (n.succ : ℤ) := int.coe_nat_pos.2 (succ_pos n) @[simp, norm_cast] theorem coe_nat_abs (n : ℕ) : abs (n : ℤ) = n := abs_of_nonneg (coe_nat_nonneg n) /- succ and pred -/ /-- Immediate successor of an integer: `succ n = n + 1` -/ def succ (a : ℤ) := a + 1 /-- Immediate predecessor of an integer: `pred n = n - 1` -/ def pred (a : ℤ) := a - 1 theorem nat_succ_eq_int_succ (n : ℕ) : (nat.succ n : ℤ) = int.succ n := rfl theorem pred_succ (a : ℤ) : pred (succ a) = a := add_sub_cancel _ _ theorem succ_pred (a : ℤ) : succ (pred a) = a := sub_add_cancel _ _ theorem neg_succ (a : ℤ) : -succ a = pred (-a) := neg_add _ _ theorem succ_neg_succ (a : ℤ) : succ (-succ a) = -a := by rw [neg_succ, succ_pred] theorem neg_pred (a : ℤ) : -pred a = succ (-a) := by rw [eq_neg_of_eq_neg (neg_succ (-a)).symm, neg_neg] theorem pred_neg_pred (a : ℤ) : pred (-pred a) = -a := by rw [neg_pred, pred_succ] theorem pred_nat_succ (n : ℕ) : pred (nat.succ n) = n := pred_succ n theorem neg_nat_succ (n : ℕ) : -(nat.succ n : ℤ) = pred (-n) := neg_succ n theorem succ_neg_nat_succ (n : ℕ) : succ (-nat.succ n) = -n := succ_neg_succ n theorem lt_succ_self (a : ℤ) : a < succ a := lt_add_of_pos_right _ zero_lt_one theorem pred_self_lt (a : ℤ) : pred a < a := sub_lt_self _ zero_lt_one theorem add_one_le_iff {a b : ℤ} : a + 1 ≤ b ↔ a < b := iff.rfl theorem lt_add_one_iff {a b : ℤ} : a < b + 1 ↔ a ≤ b := @add_le_add_iff_right _ _ a b 1 theorem sub_one_lt_iff {a b : ℤ} : a - 1 < b ↔ a ≤ b := sub_lt_iff_lt_add.trans lt_add_one_iff theorem le_sub_one_iff {a b : ℤ} : a ≤ b - 1 ↔ a < b := le_sub_iff_add_le @[elab_as_eliminator] protected lemma induction_on {p : ℤ → Prop} (i : ℤ) (hz : p 0) (hp : ∀i : ℕ, p i → p (i + 1)) (hn : ∀i : ℕ, p (-i) → p (-i - 1)) : p i := begin induction i, { induction i, { exact hz }, { exact hp _ i_ih } }, { have : ∀n:ℕ, p (- n), { intro n, induction n, { simp [hz] }, { convert hn _ n_ih using 1, simp [sub_eq_neg_add] } }, exact this (i + 1) } end protected def induction_on' {C : ℤ → Sort*} (z : ℤ) (b : ℤ) : C b → (∀ k, b ≤ k → C k → C (k + 1)) → (∀ k ≤ b, C k → C (k - 1)) → C z := λ H0 Hs Hp, begin rw ←sub_add_cancel z b, induction (z - b), { induction a with n ih, { rwa [of_nat_zero, zero_add] }, rw [of_nat_succ, add_assoc, add_comm 1 b, ←add_assoc], exact Hs _ (le_add_of_nonneg_left (of_nat_nonneg _)) ih }, { induction a with n ih, { rw [neg_succ_of_nat_eq, ←of_nat_eq_coe, of_nat_zero, zero_add, neg_add_eq_sub], exact Hp _ (le_refl _) H0 }, { rw [neg_succ_of_nat_coe', nat.succ_eq_add_one, ←neg_succ_of_nat_coe, sub_add_eq_add_sub], exact Hp _ (le_of_lt (add_lt_of_neg_of_le (neg_succ_lt_zero _) (le_refl _))) ih } } end /- nat abs -/ attribute [simp] nat_abs nat_abs_of_nat nat_abs_zero nat_abs_one theorem nat_abs_add_le (a b : ℤ) : nat_abs (a + b) ≤ nat_abs a + nat_abs b := begin have : ∀ (a b : ℕ), nat_abs (sub_nat_nat a (nat.succ b)) ≤ nat.succ (a + b), { refine (λ a b : ℕ, sub_nat_nat_elim a b.succ (λ m n i, n = b.succ → nat_abs i ≤ (m + b).succ) _ _ rfl); intros i n e, { subst e, rw [add_comm _ i, add_assoc], exact nat.le_add_right i (b.succ + b).succ }, { apply succ_le_succ, rw [← succ_inj e, ← add_assoc, add_comm], apply nat.le_add_right } }, cases a; cases b with b b; simp [nat_abs, nat.succ_add]; try {refl}; [skip, rw add_comm a b]; apply this end theorem nat_abs_neg_of_nat (n : ℕ) : nat_abs (neg_of_nat n) = n := by cases n; refl theorem nat_abs_mul (a b : ℤ) : nat_abs (a * b) = (nat_abs a) * (nat_abs b) := by cases a; cases b; simp only [(*), int.mul, nat_abs_neg_of_nat, eq_self_iff_true, int.nat_abs] @[simp] lemma nat_abs_mul_self' (a : ℤ) : (nat_abs a * nat_abs a : ℤ) = a * a := by rw [← int.coe_nat_mul, nat_abs_mul_self] theorem neg_succ_of_nat_eq' (m : ℕ) : -[1+ m] = -m - 1 := by simp [neg_succ_of_nat_eq, sub_eq_neg_add] lemma nat_abs_ne_zero_of_ne_zero {z : ℤ} (hz : z ≠ 0) : z.nat_abs ≠ 0 := λ h, hz $ int.eq_zero_of_nat_abs_eq_zero h @[simp] lemma nat_abs_eq_zero {a : ℤ} : a.nat_abs = 0 ↔ a = 0 := ⟨int.eq_zero_of_nat_abs_eq_zero, λ h, h.symm ▸ rfl⟩ lemma nat_abs_lt_nat_abs_of_nonneg_of_lt {a b : ℤ} (w₁ : 0 ≤ a) (w₂ : a < b) : a.nat_abs < b.nat_abs := begin lift b to ℕ using le_trans w₁ (le_of_lt w₂), lift a to ℕ using w₁, simpa using w₂, end /- / -/ @[simp] theorem of_nat_div (m n : ℕ) : of_nat (m / n) = (of_nat m) / (of_nat n) := rfl @[simp, norm_cast] theorem coe_nat_div (m n : ℕ) : ((m / n : ℕ) : ℤ) = m / n := rfl theorem neg_succ_of_nat_div (m : ℕ) {b : ℤ} (H : 0 < b) : -[1+m] / b = -(m / b + 1) := match b, eq_succ_of_zero_lt H with ._, ⟨n, rfl⟩ := rfl end @[simp] protected theorem div_neg : ∀ (a b : ℤ), a / -b = -(a / b) | (m : ℕ) 0 := show of_nat (m / 0) = -(m / 0 : ℕ), by rw nat.div_zero; refl | (m : ℕ) (n+1:ℕ) := rfl | 0 -[1+ n] := rfl | (m+1:ℕ) -[1+ n] := (neg_neg _).symm | -[1+ m] 0 := rfl | -[1+ m] (n+1:ℕ) := rfl | -[1+ m] -[1+ n] := rfl theorem div_of_neg_of_pos {a b : ℤ} (Ha : a < 0) (Hb : 0 < b) : a / b = -((-a - 1) / b + 1) := match a, b, eq_neg_succ_of_lt_zero Ha, eq_succ_of_zero_lt Hb with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := by change (- -[1+ m] : ℤ) with (m+1 : ℤ); rw add_sub_cancel; refl end protected theorem div_nonneg {a b : ℤ} (Ha : 0 ≤ a) (Hb : 0 ≤ b) : 0 ≤ a / b := match a, b, eq_coe_of_zero_le Ha, eq_coe_of_zero_le Hb with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := coe_zero_le _ end protected theorem div_nonpos {a b : ℤ} (Ha : 0 ≤ a) (Hb : b ≤ 0) : a / b ≤ 0 := nonpos_of_neg_nonneg $ by rw [← int.div_neg]; exact int.div_nonneg Ha (neg_nonneg_of_nonpos Hb) theorem div_neg' {a b : ℤ} (Ha : a < 0) (Hb : 0 < b) : a / b < 0 := match a, b, eq_neg_succ_of_lt_zero Ha, eq_succ_of_zero_lt Hb with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := neg_succ_lt_zero _ end -- Will be generalized to Euclidean domains. protected theorem zero_div : ∀ (b : ℤ), 0 / b = 0 | 0 := rfl | (n+1:ℕ) := rfl | -[1+ n] := rfl local attribute [simp] -- Will be generalized to Euclidean domains. protected theorem div_zero : ∀ (a : ℤ), a / 0 = 0 | 0 := rfl | (n+1:ℕ) := rfl | -[1+ n] := rfl @[simp] protected theorem div_one : ∀ (a : ℤ), a / 1 = a | 0 := rfl | (n+1:ℕ) := congr_arg of_nat (nat.div_one _) | -[1+ n] := congr_arg neg_succ_of_nat (nat.div_one _) theorem div_eq_zero_of_lt {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a / b = 0 := match a, b, eq_coe_of_zero_le H1, eq_succ_of_zero_lt (lt_of_le_of_lt H1 H2), H2 with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩, H2 := congr_arg of_nat $ nat.div_eq_of_lt $ lt_of_coe_nat_lt_coe_nat H2 end theorem div_eq_zero_of_lt_abs {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < abs b) : a / b = 0 := match b, abs b, abs_eq_nat_abs b, H2 with | (n : ℕ), ._, rfl, H2 := div_eq_zero_of_lt H1 H2 | -[1+ n], ._, rfl, H2 := neg_inj $ by rw [← int.div_neg]; exact div_eq_zero_of_lt H1 H2 end protected theorem add_mul_div_right (a b : ℤ) {c : ℤ} (H : c ≠ 0) : (a + b * c) / c = a / c + b := have ∀ {k n : ℕ} {a : ℤ}, (a + n * k.succ) / k.succ = a / k.succ + n, from λ k n a, match a with | (m : ℕ) := congr_arg of_nat $ nat.add_mul_div_right _ _ k.succ_pos | -[1+ m] := show ((n * k.succ:ℕ) - m.succ : ℤ) / k.succ = n - (m / k.succ + 1 : ℕ), begin cases lt_or_ge m (n*k.succ) with h h, { rw [← int.coe_nat_sub h, ← int.coe_nat_sub ((nat.div_lt_iff_lt_mul _ _ k.succ_pos).2 h)], apply congr_arg of_nat, rw [mul_comm, nat.mul_sub_div], rwa mul_comm }, { change (↑(n * nat.succ k) - (m + 1) : ℤ) / ↑(nat.succ k) = ↑n - ((m / nat.succ k : ℕ) + 1), rw [← sub_sub, ← sub_sub, ← neg_sub (m:ℤ), ← neg_sub _ (n:ℤ), ← int.coe_nat_sub h, ← int.coe_nat_sub ((nat.le_div_iff_mul_le _ _ k.succ_pos).2 h), ← neg_succ_of_nat_coe', ← neg_succ_of_nat_coe'], { apply congr_arg neg_succ_of_nat, rw [mul_comm, nat.sub_mul_div], rwa mul_comm } } end end, have ∀ {a b c : ℤ}, 0 < c → (a + b * c) / c = a / c + b, from λ a b c H, match c, eq_succ_of_zero_lt H, b with | ._, ⟨k, rfl⟩, (n : ℕ) := this | ._, ⟨k, rfl⟩, -[1+ n] := show (a - n.succ * k.succ) / k.succ = (a / k.succ) - n.succ, from eq_sub_of_add_eq $ by rw [← this, sub_add_cancel] end, match lt_trichotomy c 0 with | or.inl hlt := neg_inj $ by rw [← int.div_neg, neg_add, ← int.div_neg, ← neg_mul_neg]; apply this (neg_pos_of_neg hlt) | or.inr (or.inl heq) := absurd heq H | or.inr (or.inr hgt) := this hgt end protected theorem add_mul_div_left (a : ℤ) {b : ℤ} (c : ℤ) (H : b ≠ 0) : (a + b * c) / b = a / b + c := by rw [mul_comm, int.add_mul_div_right _ _ H] @[simp] protected theorem mul_div_cancel (a : ℤ) {b : ℤ} (H : b ≠ 0) : a * b / b = a := by have := int.add_mul_div_right 0 a H; rwa [zero_add, int.zero_div, zero_add] at this @[simp] protected theorem mul_div_cancel_left {a : ℤ} (b : ℤ) (H : a ≠ 0) : a * b / a = b := by rw [mul_comm, int.mul_div_cancel _ H] @[simp] protected theorem div_self {a : ℤ} (H : a ≠ 0) : a / a = 1 := by have := int.mul_div_cancel 1 H; rwa one_mul at this /- mod -/ theorem of_nat_mod (m n : nat) : (m % n : ℤ) = of_nat (m % n) := rfl @[simp] theorem coe_nat_mod (m n : ℕ) : (↑(m % n) : ℤ) = ↑m % ↑n := rfl theorem neg_succ_of_nat_mod (m : ℕ) {b : ℤ} (bpos : 0 < b) : -[1+m] % b = b - 1 - m % b := by rw [sub_sub, add_comm]; exact match b, eq_succ_of_zero_lt bpos with ._, ⟨n, rfl⟩ := rfl end @[simp] theorem mod_neg : ∀ (a b : ℤ), a % -b = a % b | (m : ℕ) n := @congr_arg ℕ ℤ _ _ (λ i, ↑(m % i)) (nat_abs_neg _) | -[1+ m] n := @congr_arg ℕ ℤ _ _ (λ i, sub_nat_nat i (nat.succ (m % i))) (nat_abs_neg _) @[simp] theorem mod_abs (a b : ℤ) : a % (abs b) = a % b := abs_by_cases (λ i, a % i = a % b) rfl (mod_neg _ _) local attribute [simp] -- Will be generalized to Euclidean domains. theorem zero_mod (b : ℤ) : 0 % b = 0 := congr_arg of_nat $ nat.zero_mod _ local attribute [simp] -- Will be generalized to Euclidean domains. theorem mod_zero : ∀ (a : ℤ), a % 0 = a | (m : ℕ) := congr_arg of_nat $ nat.mod_zero _ | -[1+ m] := congr_arg neg_succ_of_nat $ nat.mod_zero _ local attribute [simp] -- Will be generalized to Euclidean domains. theorem mod_one : ∀ (a : ℤ), a % 1 = 0 | (m : ℕ) := congr_arg of_nat $ nat.mod_one _ | -[1+ m] := show (1 - (m % 1).succ : ℤ) = 0, by rw nat.mod_one; refl theorem mod_eq_of_lt {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a % b = a := match a, b, eq_coe_of_zero_le H1, eq_coe_of_zero_le (le_trans H1 (le_of_lt H2)), H2 with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩, H2 := congr_arg of_nat $ nat.mod_eq_of_lt (lt_of_coe_nat_lt_coe_nat H2) end theorem mod_nonneg : ∀ (a : ℤ) {b : ℤ}, b ≠ 0 → 0 ≤ a % b | (m : ℕ) n H := coe_zero_le _ | -[1+ m] n H := sub_nonneg_of_le $ coe_nat_le_coe_nat_of_le $ nat.mod_lt _ (nat_abs_pos_of_ne_zero H) theorem mod_lt_of_pos (a : ℤ) {b : ℤ} (H : 0 < b) : a % b < b := match a, b, eq_succ_of_zero_lt H with | (m : ℕ), ._, ⟨n, rfl⟩ := coe_nat_lt_coe_nat_of_lt (nat.mod_lt _ (nat.succ_pos _)) | -[1+ m], ._, ⟨n, rfl⟩ := sub_lt_self _ (coe_nat_lt_coe_nat_of_lt $ nat.succ_pos _) end theorem mod_lt (a : ℤ) {b : ℤ} (H : b ≠ 0) : a % b < abs b := by rw [← mod_abs]; exact mod_lt_of_pos _ (abs_pos_of_ne_zero H) theorem mod_add_div_aux (m n : ℕ) : (n - (m % n + 1) - (n * (m / n) + n) : ℤ) = -[1+ m] := begin rw [← sub_sub, neg_succ_of_nat_coe, sub_sub (n:ℤ)], apply eq_neg_of_eq_neg, rw [neg_sub, sub_sub_self, add_right_comm], exact @congr_arg ℕ ℤ _ _ (λi, (i + 1 : ℤ)) (nat.mod_add_div _ _).symm end theorem mod_add_div : ∀ (a b : ℤ), a % b + b * (a / b) = a | (m : ℕ) 0 := congr_arg of_nat (nat.mod_add_div _ _) | (m : ℕ) (n+1:ℕ) := congr_arg of_nat (nat.mod_add_div _ _) | 0 -[1+ n] := rfl | (m+1:ℕ) -[1+ n] := show (_ + -(n+1) * -((m + 1) / (n + 1) : ℕ) : ℤ) = _, by rw [neg_mul_neg]; exact congr_arg of_nat (nat.mod_add_div _ _) | -[1+ m] 0 := by rw [mod_zero, int.div_zero]; refl | -[1+ m] (n+1:ℕ) := mod_add_div_aux m n.succ | -[1+ m] -[1+ n] := mod_add_div_aux m n.succ theorem mod_def (a b : ℤ) : a % b = a - b * (a / b) := eq_sub_of_add_eq (mod_add_div _ _) @[simp] theorem add_mul_mod_self {a b c : ℤ} : (a + b * c) % c = a % c := if cz : c = 0 then by rw [cz, mul_zero, add_zero] else by rw [mod_def, mod_def, int.add_mul_div_right _ _ cz, mul_add, mul_comm, add_sub_add_right_eq_sub] @[simp] theorem add_mul_mod_self_left (a b c : ℤ) : (a + b * c) % b = a % b := by rw [mul_comm, add_mul_mod_self] @[simp] theorem add_mod_self {a b : ℤ} : (a + b) % b = a % b := by have := add_mul_mod_self_left a b 1; rwa mul_one at this @[simp] theorem add_mod_self_left {a b : ℤ} : (a + b) % a = b % a := by rw [add_comm, add_mod_self] @[simp] theorem mod_add_mod (m n k : ℤ) : (m % n + k) % n = (m + k) % n := by have := (add_mul_mod_self_left (m % n + k) n (m / n)).symm; rwa [add_right_comm, mod_add_div] at this @[simp] theorem add_mod_mod (m n k : ℤ) : (m + n % k) % k = (m + n) % k := by rw [add_comm, mod_add_mod, add_comm] lemma add_mod (a b n : ℤ) : (a + b) % n = ((a % n) + (b % n)) % n := by rw [add_mod_mod, mod_add_mod] theorem add_mod_eq_add_mod_right {m n k : ℤ} (i : ℤ) (H : m % n = k % n) : (m + i) % n = (k + i) % n := by rw [← mod_add_mod, ← mod_add_mod k, H] theorem add_mod_eq_add_mod_left {m n k : ℤ} (i : ℤ) (H : m % n = k % n) : (i + m) % n = (i + k) % n := by rw [add_comm, add_mod_eq_add_mod_right _ H, add_comm] theorem mod_add_cancel_right {m n k : ℤ} (i) : (m + i) % n = (k + i) % n ↔ m % n = k % n := ⟨λ H, by have := add_mod_eq_add_mod_right (-i) H; rwa [add_neg_cancel_right, add_neg_cancel_right] at this, add_mod_eq_add_mod_right _⟩ theorem mod_add_cancel_left {m n k i : ℤ} : (i + m) % n = (i + k) % n ↔ m % n = k % n := by rw [add_comm, add_comm i, mod_add_cancel_right] theorem mod_sub_cancel_right {m n k : ℤ} (i) : (m - i) % n = (k - i) % n ↔ m % n = k % n := mod_add_cancel_right _ theorem mod_eq_mod_iff_mod_sub_eq_zero {m n k : ℤ} : m % n = k % n ↔ (m - k) % n = 0 := (mod_sub_cancel_right k).symm.trans $ by simp @[simp] theorem mul_mod_left (a b : ℤ) : (a * b) % b = 0 := by rw [← zero_add (a * b), add_mul_mod_self, zero_mod] @[simp] theorem mul_mod_right (a b : ℤ) : (a * b) % a = 0 := by rw [mul_comm, mul_mod_left] lemma mul_mod (a b n : ℤ) : (a * b) % n = ((a % n) * (b % n)) % n := begin conv_lhs { rw [←mod_add_div a n, ←mod_add_div b n, right_distrib, left_distrib, left_distrib, mul_assoc, mul_assoc, ←left_distrib n _ _, add_mul_mod_self_left, mul_comm _ (n * (b / n)), mul_assoc, add_mul_mod_self_left] } end local attribute [simp] -- Will be generalized to Euclidean domains. theorem mod_self {a : ℤ} : a % a = 0 := by have := mul_mod_left 1 a; rwa one_mul at this @[simp] theorem mod_mod_of_dvd (n : int) {m k : int} (h : m ∣ k) : n % k % m = n % m := begin conv { to_rhs, rw ←mod_add_div n k }, rcases h with ⟨t, rfl⟩, rw [mul_assoc, add_mul_mod_self_left] end @[simp] theorem mod_mod (a b : ℤ) : a % b % b = a % b := by conv {to_rhs, rw [← mod_add_div a b, add_mul_mod_self_left]} /- properties of / and % -/ @[simp] theorem mul_div_mul_of_pos {a : ℤ} (b c : ℤ) (H : 0 < a) : a * b / (a * c) = b / c := suffices ∀ (m k : ℕ) (b : ℤ), (m.succ * b / (m.succ * k) : ℤ) = b / k, from match a, eq_succ_of_zero_lt H, c, eq_coe_or_neg c with | ._, ⟨m, rfl⟩, ._, ⟨k, or.inl rfl⟩ := this _ _ _ | ._, ⟨m, rfl⟩, ._, ⟨k, or.inr rfl⟩ := by rw [← neg_mul_eq_mul_neg, int.div_neg, int.div_neg]; apply congr_arg has_neg.neg; apply this end, λ m k b, match b, k with | (n : ℕ), k := congr_arg of_nat (nat.mul_div_mul _ _ m.succ_pos) | -[1+ n], 0 := by rw [int.coe_nat_zero, mul_zero, int.div_zero, int.div_zero] | -[1+ n], k+1 := congr_arg neg_succ_of_nat $ show (m.succ * n + m) / (m.succ * k.succ) = n / k.succ, begin apply nat.div_eq_of_lt_le, { refine le_trans _ (nat.le_add_right _ _), rw [← nat.mul_div_mul _ _ m.succ_pos], apply nat.div_mul_le_self }, { change m.succ * n.succ ≤ _, rw [mul_left_comm], apply nat.mul_le_mul_left, apply (nat.div_lt_iff_lt_mul _ _ k.succ_pos).1, apply nat.lt_succ_self } end end @[simp] theorem mul_div_mul_of_pos_left (a : ℤ) {b : ℤ} (c : ℤ) (H : 0 < b) : a * b / (c * b) = a / c := by rw [mul_comm, mul_comm c, mul_div_mul_of_pos _ _ H] @[simp] theorem mul_mod_mul_of_pos {a : ℤ} (b c : ℤ) (H : 0 < a) : a * b % (a * c) = a * (b % c) := by rw [mod_def, mod_def, mul_div_mul_of_pos _ _ H, mul_sub_left_distrib, mul_assoc] theorem lt_div_add_one_mul_self (a : ℤ) {b : ℤ} (H : 0 < b) : a < (a / b + 1) * b := by rw [add_mul, one_mul, mul_comm]; apply lt_add_of_sub_left_lt; rw [← mod_def]; apply mod_lt_of_pos _ H theorem abs_div_le_abs : ∀ (a b : ℤ), abs (a / b) ≤ abs a := suffices ∀ (a : ℤ) (n : ℕ), abs (a / n) ≤ abs a, from λ a b, match b, eq_coe_or_neg b with | ._, ⟨n, or.inl rfl⟩ := this _ _ | ._, ⟨n, or.inr rfl⟩ := by rw [int.div_neg, abs_neg]; apply this end, λ a n, by rw [abs_eq_nat_abs, abs_eq_nat_abs]; exact coe_nat_le_coe_nat_of_le (match a, n with | (m : ℕ), n := nat.div_le_self _ _ | -[1+ m], 0 := nat.zero_le _ | -[1+ m], n+1 := nat.succ_le_succ (nat.div_le_self _ _) end) theorem div_le_self {a : ℤ} (b : ℤ) (Ha : 0 ≤ a) : a / b ≤ a := by have := le_trans (le_abs_self _) (abs_div_le_abs a b); rwa [abs_of_nonneg Ha] at this theorem mul_div_cancel_of_mod_eq_zero {a b : ℤ} (H : a % b = 0) : b * (a / b) = a := by have := mod_add_div a b; rwa [H, zero_add] at this theorem div_mul_cancel_of_mod_eq_zero {a b : ℤ} (H : a % b = 0) : a / b * b = a := by rw [mul_comm, mul_div_cancel_of_mod_eq_zero H] lemma mod_two_eq_zero_or_one (n : ℤ) : n % 2 = 0 ∨ n % 2 = 1 := have h : n % 2 < 2 := abs_of_nonneg (show 0 ≤ (2 : ℤ), from dec_trivial) ▸ int.mod_lt _ dec_trivial, have h₁ : 0 ≤ n % 2 := int.mod_nonneg _ dec_trivial, match (n % 2), h, h₁ with | (0 : ℕ) := λ _ _, or.inl rfl | (1 : ℕ) := λ _ _, or.inr rfl | (k + 2 : ℕ) := λ h _, absurd h dec_trivial | -[1+ a] := λ _ h₁, absurd h₁ dec_trivial end /- dvd -/ @[norm_cast] theorem coe_nat_dvd {m n : ℕ} : (↑m : ℤ) ∣ ↑n ↔ m ∣ n := ⟨λ ⟨a, ae⟩, m.eq_zero_or_pos.elim (λm0, by simp [m0] at ae; simp [ae, m0]) (λm0l, by { cases eq_coe_of_zero_le (@nonneg_of_mul_nonneg_left ℤ _ m a (by simp [ae.symm]) (by simpa using m0l)) with k e, subst a, exact ⟨k, int.coe_nat_inj ae⟩ }), λ ⟨k, e⟩, dvd.intro k $ by rw [e, int.coe_nat_mul]⟩ theorem coe_nat_dvd_left {n : ℕ} {z : ℤ} : (↑n : ℤ) ∣ z ↔ n ∣ z.nat_abs := by rcases nat_abs_eq z with eq | eq; rw eq; simp [coe_nat_dvd] theorem coe_nat_dvd_right {n : ℕ} {z : ℤ} : z ∣ (↑n : ℤ) ↔ z.nat_abs ∣ n := by rcases nat_abs_eq z with eq | eq; rw eq; simp [coe_nat_dvd] theorem dvd_antisymm {a b : ℤ} (H1 : 0 ≤ a) (H2 : 0 ≤ b) : a ∣ b → b ∣ a → a = b := begin rw [← abs_of_nonneg H1, ← abs_of_nonneg H2, abs_eq_nat_abs, abs_eq_nat_abs], rw [coe_nat_dvd, coe_nat_dvd, coe_nat_inj'], apply nat.dvd_antisymm end theorem dvd_of_mod_eq_zero {a b : ℤ} (H : b % a = 0) : a ∣ b := ⟨b / a, (mul_div_cancel_of_mod_eq_zero H).symm⟩ theorem mod_eq_zero_of_dvd : ∀ {a b : ℤ}, a ∣ b → b % a = 0 | a ._ ⟨c, rfl⟩ := mul_mod_right _ _ theorem dvd_iff_mod_eq_zero (a b : ℤ) : a ∣ b ↔ b % a = 0 := ⟨mod_eq_zero_of_dvd, dvd_of_mod_eq_zero⟩ /-- If `a % b = c` then `b` divides `a - c`. -/ lemma dvd_sub_of_mod_eq {a b c : ℤ} (h : a % b = c) : b ∣ a - c := begin have hx : a % b % b = c % b, { rw h }, rw [mod_mod, ←mod_sub_cancel_right c, sub_self, zero_mod] at hx, exact dvd_of_mod_eq_zero hx end theorem nat_abs_dvd {a b : ℤ} : (a.nat_abs : ℤ) ∣ b ↔ a ∣ b := (nat_abs_eq a).elim (λ e, by rw ← e) (λ e, by rw [← neg_dvd_iff_dvd, ← e]) theorem dvd_nat_abs {a b : ℤ} : a ∣ b.nat_abs ↔ a ∣ b := (nat_abs_eq b).elim (λ e, by rw ← e) (λ e, by rw [← dvd_neg_iff_dvd, ← e]) instance decidable_dvd : @decidable_rel ℤ (∣) := assume a n, decidable_of_decidable_of_iff (by apply_instance) (dvd_iff_mod_eq_zero _ _).symm protected theorem div_mul_cancel {a b : ℤ} (H : b ∣ a) : a / b * b = a := div_mul_cancel_of_mod_eq_zero (mod_eq_zero_of_dvd H) protected theorem mul_div_cancel' {a b : ℤ} (H : a ∣ b) : a * (b / a) = b := by rw [mul_comm, int.div_mul_cancel H] protected theorem mul_div_assoc (a : ℤ) : ∀ {b c : ℤ}, c ∣ b → (a * b) / c = a * (b / c) | ._ c ⟨d, rfl⟩ := if cz : c = 0 then by simp [cz] else by rw [mul_left_comm, int.mul_div_cancel_left _ cz, int.mul_div_cancel_left _ cz] theorem div_dvd_div : ∀ {a b c : ℤ} (H1 : a ∣ b) (H2 : b ∣ c), b / a ∣ c / a | a ._ ._ ⟨b, rfl⟩ ⟨c, rfl⟩ := if az : a = 0 then by simp [az] else by rw [int.mul_div_cancel_left _ az, mul_assoc, int.mul_div_cancel_left _ az]; apply dvd_mul_right protected theorem eq_mul_of_div_eq_right {a b c : ℤ} (H1 : b ∣ a) (H2 : a / b = c) : a = b * c := by rw [← H2, int.mul_div_cancel' H1] protected theorem div_eq_of_eq_mul_right {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = b * c) : a / b = c := by rw [H2, int.mul_div_cancel_left _ H1] protected theorem div_eq_iff_eq_mul_right {a b c : ℤ} (H : b ≠ 0) (H' : b ∣ a) : a / b = c ↔ a = b * c := ⟨int.eq_mul_of_div_eq_right H', int.div_eq_of_eq_mul_right H⟩ protected theorem div_eq_iff_eq_mul_left {a b c : ℤ} (H : b ≠ 0) (H' : b ∣ a) : a / b = c ↔ a = c * b := by rw mul_comm; exact int.div_eq_iff_eq_mul_right H H' protected theorem eq_mul_of_div_eq_left {a b c : ℤ} (H1 : b ∣ a) (H2 : a / b = c) : a = c * b := by rw [mul_comm, int.eq_mul_of_div_eq_right H1 H2] protected theorem div_eq_of_eq_mul_left {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = c * b) : a / b = c := int.div_eq_of_eq_mul_right H1 (by rw [mul_comm, H2]) theorem neg_div_of_dvd : ∀ {a b : ℤ} (H : b ∣ a), -a / b = -(a / b) | ._ b ⟨c, rfl⟩ := if bz : b = 0 then by simp [bz] else by rw [neg_mul_eq_mul_neg, int.mul_div_cancel_left _ bz, int.mul_div_cancel_left _ bz] lemma add_div_of_dvd {a b c : ℤ} : c ∣ a → c ∣ b → (a + b) / c = a / c + b / c := begin intros h1 h2, by_cases h3 : c = 0, { rw [h3, zero_dvd_iff] at *, rw [h1, h2, h3], refl }, { apply eq_of_mul_eq_mul_right h3, rw add_mul, repeat {rw [int.div_mul_cancel]}; try {apply dvd_add}; assumption } end theorem div_sign : ∀ a b, a / sign b = a * sign b | a (n+1:ℕ) := by unfold sign; simp | a 0 := by simp [sign] | a -[1+ n] := by simp [sign] @[simp] theorem sign_mul : ∀ a b, sign (a * b) = sign a * sign b | a 0 := by simp | 0 b := by simp | (m+1:ℕ) (n+1:ℕ) := rfl | (m+1:ℕ) -[1+ n] := rfl | -[1+ m] (n+1:ℕ) := rfl | -[1+ m] -[1+ n] := rfl protected theorem sign_eq_div_abs (a : ℤ) : sign a = a / (abs a) := if az : a = 0 then by simp [az] else (int.div_eq_of_eq_mul_left (mt eq_zero_of_abs_eq_zero az) (sign_mul_abs _).symm).symm theorem mul_sign : ∀ (i : ℤ), i * sign i = nat_abs i | (n+1:ℕ) := mul_one _ | 0 := mul_zero _ | -[1+ n] := mul_neg_one _ theorem le_of_dvd {a b : ℤ} (bpos : 0 < b) (H : a ∣ b) : a ≤ b := match a, b, eq_succ_of_zero_lt bpos, H with | (m : ℕ), ._, ⟨n, rfl⟩, H := coe_nat_le_coe_nat_of_le $ nat.le_of_dvd n.succ_pos $ coe_nat_dvd.1 H | -[1+ m], ._, ⟨n, rfl⟩, _ := le_trans (le_of_lt $ neg_succ_lt_zero _) (coe_zero_le _) end theorem eq_one_of_dvd_one {a : ℤ} (H : 0 ≤ a) (H' : a ∣ 1) : a = 1 := match a, eq_coe_of_zero_le H, H' with | ._, ⟨n, rfl⟩, H' := congr_arg coe $ nat.eq_one_of_dvd_one $ coe_nat_dvd.1 H' end theorem eq_one_of_mul_eq_one_right {a b : ℤ} (H : 0 ≤ a) (H' : a * b = 1) : a = 1 := eq_one_of_dvd_one H ⟨b, H'.symm⟩ theorem eq_one_of_mul_eq_one_left {a b : ℤ} (H : 0 ≤ b) (H' : a * b = 1) : b = 1 := eq_one_of_mul_eq_one_right H (by rw [mul_comm, H']) lemma of_nat_dvd_of_dvd_nat_abs {a : ℕ} : ∀ {z : ℤ} (haz : a ∣ z.nat_abs), ↑a ∣ z | (int.of_nat _) haz := int.coe_nat_dvd.2 haz | -[1+k] haz := begin change ↑a ∣ -(k+1 : ℤ), apply dvd_neg_of_dvd, apply int.coe_nat_dvd.2, exact haz end lemma dvd_nat_abs_of_of_nat_dvd {a : ℕ} : ∀ {z : ℤ} (haz : ↑a ∣ z), a ∣ z.nat_abs | (int.of_nat _) haz := int.coe_nat_dvd.1 (int.dvd_nat_abs.2 haz) | -[1+k] haz := have haz' : (↑a:ℤ) ∣ (↑(k+1):ℤ), from dvd_of_dvd_neg haz, int.coe_nat_dvd.1 haz' lemma pow_dvd_of_le_of_pow_dvd {p m n : ℕ} {k : ℤ} (hmn : m ≤ n) (hdiv : ↑(p ^ n) ∣ k) : ↑(p ^ m) ∣ k := begin induction k, { apply int.coe_nat_dvd.2, apply pow_dvd_of_le_of_pow_dvd hmn, apply int.coe_nat_dvd.1 hdiv }, { change -[1+k] with -(↑(k+1) : ℤ), apply dvd_neg_of_dvd, apply int.coe_nat_dvd.2, apply pow_dvd_of_le_of_pow_dvd hmn, apply int.coe_nat_dvd.1, apply dvd_of_dvd_neg, exact hdiv } end lemma dvd_of_pow_dvd {p k : ℕ} {m : ℤ} (hk : 1 ≤ k) (hpk : ↑(p^k) ∣ m) : ↑p ∣ m := by rw ←nat.pow_one p; exact pow_dvd_of_le_of_pow_dvd hk hpk /- / and ordering -/ protected theorem div_mul_le (a : ℤ) {b : ℤ} (H : b ≠ 0) : a / b * b ≤ a := le_of_sub_nonneg $ by rw [mul_comm, ← mod_def]; apply mod_nonneg _ H protected theorem div_le_of_le_mul {a b c : ℤ} (H : 0 < c) (H' : a ≤ b * c) : a / c ≤ b := le_of_mul_le_mul_right (le_trans (int.div_mul_le _ (ne_of_gt H)) H') H protected theorem mul_lt_of_lt_div {a b c : ℤ} (H : 0 < c) (H3 : a < b / c) : a * c < b := lt_of_not_ge $ mt (int.div_le_of_le_mul H) (not_le_of_gt H3) protected theorem mul_le_of_le_div {a b c : ℤ} (H1 : 0 < c) (H2 : a ≤ b / c) : a * c ≤ b := le_trans (mul_le_mul_of_nonneg_right H2 (le_of_lt H1)) (int.div_mul_le _ (ne_of_gt H1)) protected theorem le_div_of_mul_le {a b c : ℤ} (H1 : 0 < c) (H2 : a * c ≤ b) : a ≤ b / c := le_of_lt_add_one $ lt_of_mul_lt_mul_right (lt_of_le_of_lt H2 (lt_div_add_one_mul_self _ H1)) (le_of_lt H1) protected theorem le_div_iff_mul_le {a b c : ℤ} (H : 0 < c) : a ≤ b / c ↔ a * c ≤ b := ⟨int.mul_le_of_le_div H, int.le_div_of_mul_le H⟩ protected theorem div_le_div {a b c : ℤ} (H : 0 < c) (H' : a ≤ b) : a / c ≤ b / c := int.le_div_of_mul_le H (le_trans (int.div_mul_le _ (ne_of_gt H)) H') protected theorem div_lt_of_lt_mul {a b c : ℤ} (H : 0 < c) (H' : a < b * c) : a / c < b := lt_of_not_ge $ mt (int.mul_le_of_le_div H) (not_le_of_gt H') protected theorem lt_mul_of_div_lt {a b c : ℤ} (H1 : 0 < c) (H2 : a / c < b) : a < b * c := lt_of_not_ge $ mt (int.le_div_of_mul_le H1) (not_le_of_gt H2) protected theorem div_lt_iff_lt_mul {a b c : ℤ} (H : 0 < c) : a / c < b ↔ a < b * c := ⟨int.lt_mul_of_div_lt H, int.div_lt_of_lt_mul H⟩ protected theorem le_mul_of_div_le {a b c : ℤ} (H1 : 0 ≤ b) (H2 : b ∣ a) (H3 : a / b ≤ c) : a ≤ c * b := by rw [← int.div_mul_cancel H2]; exact mul_le_mul_of_nonneg_right H3 H1 protected theorem lt_div_of_mul_lt {a b c : ℤ} (H1 : 0 ≤ b) (H2 : b ∣ c) (H3 : a * b < c) : a < c / b := lt_of_not_ge $ mt (int.le_mul_of_div_le H1 H2) (not_le_of_gt H3) protected theorem lt_div_iff_mul_lt {a b : ℤ} (c : ℤ) (H : 0 < c) (H' : c ∣ b) : a < b / c ↔ a * c < b := ⟨int.mul_lt_of_lt_div H, int.lt_div_of_mul_lt (le_of_lt H) H'⟩ theorem div_pos_of_pos_of_dvd {a b : ℤ} (H1 : 0 < a) (H2 : 0 ≤ b) (H3 : b ∣ a) : 0 < a / b := int.lt_div_of_mul_lt H2 H3 (by rwa zero_mul) theorem div_eq_div_of_mul_eq_mul {a b c d : ℤ} (H2 : d ∣ c) (H3 : b ≠ 0) (H4 : d ≠ 0) (H5 : a * d = b * c) : a / b = c / d := int.div_eq_of_eq_mul_right H3 $ by rw [← int.mul_div_assoc _ H2]; exact (int.div_eq_of_eq_mul_left H4 H5.symm).symm theorem eq_mul_div_of_mul_eq_mul_of_dvd_left {a b c d : ℤ} (hb : b ≠ 0) (hbc : b ∣ c) (h : b * a = c * d) : a = c / b * d := begin cases hbc with k hk, subst hk, rw int.mul_div_cancel_left, rw mul_assoc at h, apply _root_.eq_of_mul_eq_mul_left _ h, repeat {assumption} end /-- If an integer with larger absolute value divides an integer, it is zero. -/ lemma eq_zero_of_dvd_of_nat_abs_lt_nat_abs {a b : ℤ} (w : a ∣ b) (h : nat_abs b < nat_abs a) : b = 0 := begin rw [←nat_abs_dvd, ←dvd_nat_abs, coe_nat_dvd] at w, rw ←nat_abs_eq_zero, exact eq_zero_of_dvd_of_lt w h end lemma eq_zero_of_dvd_of_nonneg_of_lt {a b : ℤ} (w₁ : 0 ≤ a) (w₂ : a < b) (h : b ∣ a) : a = 0 := eq_zero_of_dvd_of_nat_abs_lt_nat_abs h (nat_abs_lt_nat_abs_of_nonneg_of_lt w₁ w₂) /-- If two integers are congruent to a sufficiently large modulus, they are equal. -/ lemma eq_of_mod_eq_of_nat_abs_sub_lt_nat_abs {a b c : ℤ} (h1 : a % b = c) (h2 : nat_abs (a - c) < nat_abs b) : a = c := eq_of_sub_eq_zero (eq_zero_of_dvd_of_nat_abs_lt_nat_abs (dvd_sub_of_mod_eq h1) h2) theorem of_nat_add_neg_succ_of_nat_of_lt {m n : ℕ} (h : m < n.succ) : of_nat m + -[1+n] = -[1+ n - m] := begin change sub_nat_nat _ _ = _, have h' : n.succ - m = (n - m).succ, apply succ_sub, apply le_of_lt_succ h, simp [*, sub_nat_nat] end theorem of_nat_add_neg_succ_of_nat_of_ge {m n : ℕ} (h : n.succ ≤ m) : of_nat m + -[1+n] = of_nat (m - n.succ) := begin change sub_nat_nat _ _ = _, have h' : n.succ - m = 0, apply sub_eq_zero_of_le h, simp [*, sub_nat_nat] end @[simp] theorem neg_add_neg (m n : ℕ) : -[1+m] + -[1+n] = -[1+nat.succ(m+n)] := rfl /- to_nat -/ theorem to_nat_eq_max : ∀ (a : ℤ), (to_nat a : ℤ) = max a 0 | (n : ℕ) := (max_eq_left (coe_zero_le n)).symm | -[1+ n] := (max_eq_right (le_of_lt (neg_succ_lt_zero n))).symm @[simp] theorem to_nat_of_nonneg {a : ℤ} (h : 0 ≤ a) : (to_nat a : ℤ) = a := by rw [to_nat_eq_max, max_eq_left h] @[simp] lemma to_nat_sub_of_le (a b : ℤ) (h : b ≤ a) : (to_nat (a + -b) : ℤ) = a + - b := int.to_nat_of_nonneg (sub_nonneg_of_le h) @[simp] theorem to_nat_coe_nat (n : ℕ) : to_nat ↑n = n := rfl theorem le_to_nat (a : ℤ) : a ≤ to_nat a := by rw [to_nat_eq_max]; apply le_max_left @[simp] theorem to_nat_le {a : ℤ} {n : ℕ} : to_nat a ≤ n ↔ a ≤ n := by rw [(coe_nat_le_coe_nat_iff _ _).symm, to_nat_eq_max, max_le_iff]; exact and_iff_left (coe_zero_le _) @[simp] theorem lt_to_nat {n : ℕ} {a : ℤ} : n < to_nat a ↔ (n : ℤ) < a := le_iff_le_iff_lt_iff_lt.1 to_nat_le theorem to_nat_le_to_nat {a b : ℤ} (h : a ≤ b) : to_nat a ≤ to_nat b := by rw to_nat_le; exact le_trans h (le_to_nat b) theorem to_nat_lt_to_nat {a b : ℤ} (hb : 0 < b) : to_nat a < to_nat b ↔ a < b := ⟨λ h, begin cases a, exact lt_to_nat.1 h, exact lt_trans (neg_succ_of_nat_lt_zero a) hb, end, λ h, begin rw lt_to_nat, cases a, exact h, exact hb end⟩ theorem lt_of_to_nat_lt {a b : ℤ} (h : to_nat a < to_nat b) : a < b := (to_nat_lt_to_nat $ lt_to_nat.1 $ lt_of_le_of_lt (nat.zero_le _) h).1 h def to_nat' : ℤ → option ℕ | (n : ℕ) := some n | -[1+ n] := none theorem mem_to_nat' : ∀ (a : ℤ) (n : ℕ), n ∈ to_nat' a ↔ a = n | (m : ℕ) n := option.some_inj.trans coe_nat_inj'.symm | -[1+ m] n := by split; intro h; cases h /- units -/ @[simp] theorem units_nat_abs (u : units ℤ) : nat_abs u = 1 := units.ext_iff.1 $ nat.units_eq_one ⟨nat_abs u, nat_abs ↑u⁻¹, by rw [← nat_abs_mul, units.mul_inv]; refl, by rw [← nat_abs_mul, units.inv_mul]; refl⟩ theorem units_eq_one_or (u : units ℤ) : u = 1 ∨ u = -1 := by simpa [units.ext_iff, units_nat_abs] using nat_abs_eq u lemma units_inv_eq_self (u : units ℤ) : u⁻¹ = u := (units_eq_one_or u).elim (λ h, h.symm ▸ rfl) (λ h, h.symm ▸ rfl) /- bitwise ops -/ @[simp] lemma bodd_zero : bodd 0 = ff := rfl @[simp] lemma bodd_one : bodd 1 = tt := rfl @[simp] lemma bodd_two : bodd 2 = ff := rfl @[simp, norm_cast] lemma bodd_coe (n : ℕ) : int.bodd n = nat.bodd n := rfl @[simp] lemma bodd_sub_nat_nat (m n : ℕ) : bodd (sub_nat_nat m n) = bxor m.bodd n.bodd := by apply sub_nat_nat_elim m n (λ m n i, bodd i = bxor m.bodd n.bodd); intros; simp; cases i.bodd; simp @[simp] lemma bodd_neg_of_nat (n : ℕ) : bodd (neg_of_nat n) = n.bodd := by cases n; simp; refl @[simp] lemma bodd_neg (n : ℤ) : bodd (-n) = bodd n := by cases n; simp [has_neg.neg, int.coe_nat_eq, int.neg, bodd, -of_nat_eq_coe] @[simp] lemma bodd_add (m n : ℤ) : bodd (m + n) = bxor (bodd m) (bodd n) := by cases m with m m; cases n with n n; unfold has_add.add; simp [int.add, -of_nat_eq_coe, bool.bxor_comm] @[simp] lemma bodd_mul (m n : ℤ) : bodd (m * n) = bodd m && bodd n := by cases m with m m; cases n with n n; unfold has_mul.mul; simp [int.mul, -of_nat_eq_coe, bool.bxor_comm] theorem bodd_add_div2 : ∀ n, cond (bodd n) 1 0 + 2 * div2 n = n | (n : ℕ) := by rw [show (cond (bodd n) 1 0 : ℤ) = (cond (bodd n) 1 0 : ℕ), by cases bodd n; refl]; exact congr_arg of_nat n.bodd_add_div2 | -[1+ n] := begin refine eq.trans _ (congr_arg neg_succ_of_nat n.bodd_add_div2), dsimp [bodd], cases nat.bodd n; dsimp [cond, bnot, div2, int.mul], { change -[1+ 2 * nat.div2 n] = _, rw zero_add }, { rw [zero_add, add_comm], refl } end theorem div2_val : ∀ n, div2 n = n / 2 | (n : ℕ) := congr_arg of_nat n.div2_val | -[1+ n] := congr_arg neg_succ_of_nat n.div2_val lemma bit0_val (n : ℤ) : bit0 n = 2 * n := (two_mul _).symm lemma bit1_val (n : ℤ) : bit1 n = 2 * n + 1 := congr_arg (+(1:ℤ)) (bit0_val _) lemma bit_val (b n) : bit b n = 2 * n + cond b 1 0 := by { cases b, apply (bit0_val n).trans (add_zero _).symm, apply bit1_val } lemma bit_decomp (n : ℤ) : bit (bodd n) (div2 n) = n := (bit_val _ _).trans $ (add_comm _ _).trans $ bodd_add_div2 _ def {u} bit_cases_on {C : ℤ → Sort u} (n) (h : ∀ b n, C (bit b n)) : C n := by rw [← bit_decomp n]; apply h @[simp] lemma bit_zero : bit ff 0 = 0 := rfl @[simp] lemma bit_coe_nat (b) (n : ℕ) : bit b n = nat.bit b n := by rw [bit_val, nat.bit_val]; cases b; refl @[simp] lemma bit_neg_succ (b) (n : ℕ) : bit b -[1+ n] = -[1+ nat.bit (bnot b) n] := by rw [bit_val, nat.bit_val]; cases b; refl @[simp] lemma bodd_bit (b n) : bodd (bit b n) = b := by rw bit_val; simp; cases b; cases bodd n; refl @[simp] lemma div2_bit (b n) : div2 (bit b n) = n := begin rw [bit_val, div2_val, add_comm, int.add_mul_div_left, (_ : (_/2:ℤ) = 0), zero_add], cases b, all_goals {exact dec_trivial} end @[simp] lemma test_bit_zero (b) : ∀ n, test_bit (bit b n) 0 = b | (n : ℕ) := by rw [bit_coe_nat]; apply nat.test_bit_zero | -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_zero]; clear test_bit_zero; cases b; refl @[simp] lemma test_bit_succ (m b) : ∀ n, test_bit (bit b n) (nat.succ m) = test_bit n m | (n : ℕ) := by rw [bit_coe_nat]; apply nat.test_bit_succ | -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_succ] private meta def bitwise_tac : tactic unit := `[ funext m, funext n, cases m with m m; cases n with n n; try {refl}, all_goals { apply congr_arg of_nat <|> apply congr_arg neg_succ_of_nat, try {dsimp [nat.land, nat.ldiff, nat.lor]}, try {rw [ show nat.bitwise (λ a b, a && bnot b) n m = nat.bitwise (λ a b, b && bnot a) m n, from congr_fun (congr_fun (@nat.bitwise_swap (λ a b, b && bnot a) rfl) n) m]}, apply congr_arg (λ f, nat.bitwise f m n), funext a, funext b, cases a; cases b; refl }, all_goals {unfold nat.land nat.ldiff nat.lor} ] theorem bitwise_or : bitwise bor = lor := by bitwise_tac theorem bitwise_and : bitwise band = land := by bitwise_tac theorem bitwise_diff : bitwise (λ a b, a && bnot b) = ldiff := by bitwise_tac theorem bitwise_xor : bitwise bxor = lxor := by bitwise_tac @[simp] lemma bitwise_bit (f : bool → bool → bool) (a m b n) : bitwise f (bit a m) (bit b n) = bit (f a b) (bitwise f m n) := begin cases m with m m; cases n with n n; repeat { rw [← int.coe_nat_eq] <|> rw bit_coe_nat <|> rw bit_neg_succ }; unfold bitwise nat_bitwise bnot; [ induction h : f ff ff, induction h : f ff tt, induction h : f tt ff, induction h : f tt tt ], all_goals { unfold cond, rw nat.bitwise_bit, repeat { rw bit_coe_nat <|> rw bit_neg_succ <|> rw bnot_bnot } }, all_goals { unfold bnot {fail_if_unchanged := ff}; rw h; refl } end @[simp] lemma lor_bit (a m b n) : lor (bit a m) (bit b n) = bit (a || b) (lor m n) := by rw [← bitwise_or, bitwise_bit] @[simp] lemma land_bit (a m b n) : land (bit a m) (bit b n) = bit (a && b) (land m n) := by rw [← bitwise_and, bitwise_bit] @[simp] lemma ldiff_bit (a m b n) : ldiff (bit a m) (bit b n) = bit (a && bnot b) (ldiff m n) := by rw [← bitwise_diff, bitwise_bit] @[simp] lemma lxor_bit (a m b n) : lxor (bit a m) (bit b n) = bit (bxor a b) (lxor m n) := by rw [← bitwise_xor, bitwise_bit] @[simp] lemma lnot_bit (b) : ∀ n, lnot (bit b n) = bit (bnot b) (lnot n) | (n : ℕ) := by simp [lnot] | -[1+ n] := by simp [lnot] @[simp] lemma test_bit_bitwise (f : bool → bool → bool) (m n k) : test_bit (bitwise f m n) k = f (test_bit m k) (test_bit n k) := begin induction k with k IH generalizing m n; apply bit_cases_on m; intros a m'; apply bit_cases_on n; intros b n'; rw bitwise_bit, { simp [test_bit_zero] }, { simp [test_bit_succ, IH] } end @[simp] lemma test_bit_lor (m n k) : test_bit (lor m n) k = test_bit m k || test_bit n k := by rw [← bitwise_or, test_bit_bitwise] @[simp] lemma test_bit_land (m n k) : test_bit (land m n) k = test_bit m k && test_bit n k := by rw [← bitwise_and, test_bit_bitwise] @[simp] lemma test_bit_ldiff (m n k) : test_bit (ldiff m n) k = test_bit m k && bnot (test_bit n k) := by rw [← bitwise_diff, test_bit_bitwise] @[simp] lemma test_bit_lxor (m n k) : test_bit (lxor m n) k = bxor (test_bit m k) (test_bit n k) := by rw [← bitwise_xor, test_bit_bitwise] @[simp] lemma test_bit_lnot : ∀ n k, test_bit (lnot n) k = bnot (test_bit n k) | (n : ℕ) k := by simp [lnot, test_bit] | -[1+ n] k := by simp [lnot, test_bit] lemma shiftl_add : ∀ (m : ℤ) (n : ℕ) (k : ℤ), shiftl m (n + k) = shiftl (shiftl m n) k | (m : ℕ) n (k:ℕ) := congr_arg of_nat (nat.shiftl_add _ _ _) | -[1+ m] n (k:ℕ) := congr_arg neg_succ_of_nat (nat.shiftl'_add _ _ _ _) | (m : ℕ) n -[1+k] := sub_nat_nat_elim n k.succ (λ n k i, shiftl ↑m i = nat.shiftr (nat.shiftl m n) k) (λ i n, congr_arg coe $ by rw [← nat.shiftl_sub, nat.add_sub_cancel_left]; apply nat.le_add_right) (λ i n, congr_arg coe $ by rw [add_assoc, nat.shiftr_add, ← nat.shiftl_sub, nat.sub_self]; refl) | -[1+ m] n -[1+k] := sub_nat_nat_elim n k.succ (λ n k i, shiftl -[1+ m] i = -[1+ nat.shiftr (nat.shiftl' tt m n) k]) (λ i n, congr_arg neg_succ_of_nat $ by rw [← nat.shiftl'_sub, nat.add_sub_cancel_left]; apply nat.le_add_right) (λ i n, congr_arg neg_succ_of_nat $ by rw [add_assoc, nat.shiftr_add, ← nat.shiftl'_sub, nat.sub_self]; refl) lemma shiftl_sub (m : ℤ) (n : ℕ) (k : ℤ) : shiftl m (n - k) = shiftr (shiftl m n) k := shiftl_add _ _ _ @[simp] lemma shiftl_neg (m n : ℤ) : shiftl m (-n) = shiftr m n := rfl @[simp] lemma shiftr_neg (m n : ℤ) : shiftr m (-n) = shiftl m n := by rw [← shiftl_neg, neg_neg] @[simp] lemma shiftl_coe_nat (m n : ℕ) : shiftl m n = nat.shiftl m n := rfl @[simp] lemma shiftr_coe_nat (m n : ℕ) : shiftr m n = nat.shiftr m n := by cases n; refl @[simp] lemma shiftl_neg_succ (m n : ℕ) : shiftl -[1+ m] n = -[1+ nat.shiftl' tt m n] := rfl @[simp] lemma shiftr_neg_succ (m n : ℕ) : shiftr -[1+ m] n = -[1+ nat.shiftr m n] := by cases n; refl lemma shiftr_add : ∀ (m : ℤ) (n k : ℕ), shiftr m (n + k) = shiftr (shiftr m n) k | (m : ℕ) n k := by rw [shiftr_coe_nat, shiftr_coe_nat, ← int.coe_nat_add, shiftr_coe_nat, nat.shiftr_add] | -[1+ m] n k := by rw [shiftr_neg_succ, shiftr_neg_succ, ← int.coe_nat_add, shiftr_neg_succ, nat.shiftr_add] lemma shiftl_eq_mul_pow : ∀ (m : ℤ) (n : ℕ), shiftl m n = m * ↑(2 ^ n) | (m : ℕ) n := congr_arg coe (nat.shiftl_eq_mul_pow _ _) | -[1+ m] n := @congr_arg ℕ ℤ _ _ (λi, -i) (nat.shiftl'_tt_eq_mul_pow _ _) lemma shiftr_eq_div_pow : ∀ (m : ℤ) (n : ℕ), shiftr m n = m / ↑(2 ^ n) | (m : ℕ) n := by rw shiftr_coe_nat; exact congr_arg coe (nat.shiftr_eq_div_pow _ _) | -[1+ m] n := begin rw [shiftr_neg_succ, neg_succ_of_nat_div, nat.shiftr_eq_div_pow], refl, exact coe_nat_lt_coe_nat_of_lt (nat.pos_pow_of_pos _ dec_trivial) end lemma one_shiftl (n : ℕ) : shiftl 1 n = (2 ^ n : ℕ) := congr_arg coe (nat.one_shiftl _) @[simp] lemma zero_shiftl : ∀ n : ℤ, shiftl 0 n = 0 | (n : ℕ) := congr_arg coe (nat.zero_shiftl _) | -[1+ n] := congr_arg coe (nat.zero_shiftr _) @[simp] lemma zero_shiftr (n) : shiftr 0 n = 0 := zero_shiftl _ /- Least upper bound property for integers -/ section classical open_locale classical theorem exists_least_of_bdd {P : ℤ → Prop} (Hbdd : ∃ b : ℤ, ∀ z : ℤ, P z → b ≤ z) (Hinh : ∃ z : ℤ, P z) : ∃ lb : ℤ, P lb ∧ (∀ z : ℤ, P z → lb ≤ z) := let ⟨b, Hb⟩ := Hbdd in have EX : ∃ n : ℕ, P (b + n), from let ⟨elt, Helt⟩ := Hinh in match elt, le.dest (Hb _ Helt), Helt with | ._, ⟨n, rfl⟩, Hn := ⟨n, Hn⟩ end, ⟨b + (nat.find EX : ℤ), nat.find_spec EX, λ z h, match z, le.dest (Hb _ h), h with | ._, ⟨n, rfl⟩, h := add_le_add_left (int.coe_nat_le.2 $ nat.find_min' _ h) _ end⟩ theorem exists_greatest_of_bdd {P : ℤ → Prop} (Hbdd : ∃ b : ℤ, ∀ z : ℤ, P z → z ≤ b) (Hinh : ∃ z : ℤ, P z) : ∃ ub : ℤ, P ub ∧ (∀ z : ℤ, P z → z ≤ ub) := have Hbdd' : ∃ (b : ℤ), ∀ (z : ℤ), P (-z) → b ≤ z, from let ⟨b, Hb⟩ := Hbdd in ⟨-b, λ z h, neg_le.1 (Hb _ h)⟩, have Hinh' : ∃ z : ℤ, P (-z), from let ⟨elt, Helt⟩ := Hinh in ⟨-elt, by rw [neg_neg]; exact Helt⟩, let ⟨lb, Plb, al⟩ := exists_least_of_bdd Hbdd' Hinh' in ⟨-lb, Plb, λ z h, le_neg.1 $ al _ $ by rwa neg_neg⟩ end classical /- cast (injection into groups with one) -/ @[simp] theorem nat_cast_eq_coe_nat : ∀ n, @coe ℕ ℤ (@coe_to_lift _ _ nat.cast_coe) n = @coe ℕ ℤ (@coe_to_lift _ _ (@coe_base _ _ int.has_coe)) n | 0 := rfl | (n+1) := congr_arg (+(1:ℤ)) (nat_cast_eq_coe_nat n) /-- Coercion `ℕ → ℤ` as a `ring_hom`. -/ def of_nat_hom : ℕ →+* ℤ := ⟨coe, rfl, int.of_nat_mul, rfl, int.of_nat_add⟩ section cast variables {α : Type*} section variables [has_zero α] [has_one α] [has_add α] [has_neg α] /-- Canonical homomorphism from the integers to any ring(-like) structure `α` -/ protected def cast : ℤ → α | (n : ℕ) := n | -[1+ n] := -(n+1) -- see Note [coercion into rings] @[priority 900] instance cast_coe : has_coe_t ℤ α := ⟨int.cast⟩ @[simp, norm_cast] theorem cast_zero : ((0 : ℤ) : α) = 0 := rfl theorem cast_of_nat (n : ℕ) : (of_nat n : α) = n := rfl @[simp, norm_cast] theorem cast_coe_nat (n : ℕ) : ((n : ℤ) : α) = n := rfl theorem cast_coe_nat' (n : ℕ) : (@coe ℕ ℤ (@coe_to_lift _ _ nat.cast_coe) n : α) = n := by simp @[simp, norm_cast] theorem cast_neg_succ_of_nat (n : ℕ) : (-[1+ n] : α) = -(n + 1) := rfl end @[simp, norm_cast] theorem cast_one [add_monoid α] [has_one α] [has_neg α] : ((1 : ℤ) : α) = 1 := nat.cast_one @[simp, norm_cast] theorem cast_sub_nat_nat [add_group α] [has_one α] (m n) : ((int.sub_nat_nat m n : ℤ) : α) = m - n := begin unfold sub_nat_nat, cases e : n - m, { simp [sub_nat_nat, e, nat.le_of_sub_eq_zero e] }, { rw [sub_nat_nat, cast_neg_succ_of_nat, ← nat.cast_succ, ← e, nat.cast_sub $ _root_.le_of_lt $ nat.lt_of_sub_eq_succ e, neg_sub] }, end @[simp, norm_cast] theorem cast_neg_of_nat [add_group α] [has_one α] : ∀ n, ((neg_of_nat n : ℤ) : α) = -n | 0 := neg_zero.symm | (n+1) := rfl @[simp, norm_cast] theorem cast_add [add_group α] [has_one α] : ∀ m n, ((m + n : ℤ) : α) = m + n | (m : ℕ) (n : ℕ) := nat.cast_add _ _ | (m : ℕ) -[1+ n] := cast_sub_nat_nat _ _ | -[1+ m] (n : ℕ) := (cast_sub_nat_nat _ _).trans $ sub_eq_of_eq_add $ show (n:α) = -(m+1) + n + (m+1), by rw [add_assoc, ← cast_succ, ← nat.cast_add, add_comm, nat.cast_add, cast_succ, neg_add_cancel_left] | -[1+ m] -[1+ n] := show -((m + n + 1 + 1 : ℕ) : α) = -(m + 1) + -(n + 1), begin rw [← neg_add_rev, ← nat.cast_add_one, ← nat.cast_add_one, ← nat.cast_add], apply congr_arg (λ x:ℕ, -(x:α)), ac_refl end @[simp, norm_cast] theorem cast_neg [add_group α] [has_one α] : ∀ n, ((-n : ℤ) : α) = -n | (n : ℕ) := cast_neg_of_nat _ | -[1+ n] := (neg_neg _).symm @[simp, norm_cast] theorem cast_sub [add_group α] [has_one α] (m n) : ((m - n : ℤ) : α) = m - n := by simp [sub_eq_add_neg] @[simp] theorem cast_eq_zero [add_group α] [has_one α] [char_zero α] {n : ℤ} : (n : α) = 0 ↔ n = 0 := ⟨λ h, begin cases n, { exact congr_arg coe (nat.cast_eq_zero.1 h) }, { rw [cast_neg_succ_of_nat, neg_eq_zero, ← cast_succ, nat.cast_eq_zero] at h, contradiction } end, λ h, by rw [h, cast_zero]⟩ @[simp, norm_cast] theorem cast_inj [add_group α] [has_one α] [char_zero α] {m n : ℤ} : (m : α) = n ↔ m = n := by rw [← sub_eq_zero, ← cast_sub, cast_eq_zero, sub_eq_zero] theorem cast_injective [add_group α] [has_one α] [char_zero α] : function.injective (coe : ℤ → α) | m n := cast_inj.1 theorem cast_ne_zero [add_group α] [has_one α] [char_zero α] {n : ℤ} : (n : α) ≠ 0 ↔ n ≠ 0 := not_congr cast_eq_zero @[simp, norm_cast] theorem cast_mul [ring α] : ∀ m n, ((m * n : ℤ) : α) = m * n | (m : ℕ) (n : ℕ) := nat.cast_mul _ _ | (m : ℕ) -[1+ n] := (cast_neg_of_nat _).trans $ show (-(m * (n + 1) : ℕ) : α) = m * -(n + 1), by rw [nat.cast_mul, nat.cast_add_one, neg_mul_eq_mul_neg] | -[1+ m] (n : ℕ) := (cast_neg_of_nat _).trans $ show (-((m + 1) * n : ℕ) : α) = -(m + 1) * n, by rw [nat.cast_mul, nat.cast_add_one, neg_mul_eq_neg_mul] | -[1+ m] -[1+ n] := show (((m + 1) * (n + 1) : ℕ) : α) = -(m + 1) * -(n + 1), by rw [nat.cast_mul, nat.cast_add_one, nat.cast_add_one, neg_mul_neg] /-- `coe : ℤ → α` as a `ring_hom`. -/ def cast_ring_hom (α : Type*) [ring α] : ℤ →+* α := ⟨coe, cast_one, cast_mul, cast_zero, cast_add⟩ @[simp] lemma coe_cast_ring_hom [ring α] : ⇑(cast_ring_hom α) = coe := rfl theorem mul_cast_comm [ring α] (a : α) (n : ℤ) : a * n = n * a := by cases n; simp [nat.mul_cast_comm, left_distrib, right_distrib, *] @[simp, norm_cast] theorem coe_nat_bit0 (n : ℕ) : (↑(bit0 n) : ℤ) = bit0 ↑n := by {unfold bit0, simp} @[simp, norm_cast] theorem coe_nat_bit1 (n : ℕ) : (↑(bit1 n) : ℤ) = bit1 ↑n := by {unfold bit1, unfold bit0, simp} @[simp, norm_cast] theorem cast_bit0 [ring α] (n : ℤ) : ((bit0 n : ℤ) : α) = bit0 n := cast_add _ _ @[simp, norm_cast] theorem cast_bit1 [ring α] (n : ℤ) : ((bit1 n : ℤ) : α) = bit1 n := by rw [bit1, cast_add, cast_one, cast_bit0]; refl lemma cast_two [ring α] : ((2 : ℤ) : α) = 2 := by simp theorem cast_nonneg [linear_ordered_ring α] : ∀ {n : ℤ}, (0 : α) ≤ n ↔ 0 ≤ n | (n : ℕ) := by simp | -[1+ n] := by simpa [not_le_of_gt (neg_succ_lt_zero n)] using show -(n:α) < 1, from lt_of_le_of_lt (by simp) zero_lt_one @[simp, norm_cast] theorem cast_le [linear_ordered_ring α] {m n : ℤ} : (m : α) ≤ n ↔ m ≤ n := by rw [← sub_nonneg, ← cast_sub, cast_nonneg, sub_nonneg] @[simp, norm_cast] theorem cast_lt [linear_ordered_ring α] {m n : ℤ} : (m : α) < n ↔ m < n := by simpa [-cast_le] using not_congr (@cast_le α _ n m) @[simp] theorem cast_nonpos [linear_ordered_ring α] {n : ℤ} : (n : α) ≤ 0 ↔ n ≤ 0 := by rw [← cast_zero, cast_le] @[simp] theorem cast_pos [linear_ordered_ring α] {n : ℤ} : (0 : α) < n ↔ 0 < n := by rw [← cast_zero, cast_lt] @[simp] theorem cast_lt_zero [linear_ordered_ring α] {n : ℤ} : (n : α) < 0 ↔ n < 0 := by rw [← cast_zero, cast_lt] @[simp, norm_cast] theorem cast_min [decidable_linear_ordered_comm_ring α] {a b : ℤ} : (↑(min a b) : α) = min a b := by by_cases a ≤ b; simp [h, min] @[simp, norm_cast] theorem cast_max [decidable_linear_ordered_comm_ring α] {a b : ℤ} : (↑(max a b) : α) = max a b := by by_cases a ≤ b; simp [h, max] @[simp, norm_cast] theorem cast_abs [decidable_linear_ordered_comm_ring α] {q : ℤ} : ((abs q : ℤ) : α) = abs q := by simp [abs] end cast section decidable /-- List enumerating `[m, n)`. -/ def range (m n : ℤ) : list ℤ := (list.range (to_nat (n-m))).map $ λ r, m+r theorem mem_range_iff {m n r : ℤ} : r ∈ range m n ↔ m ≤ r ∧ r < n := ⟨λ H, let ⟨s, h1, h2⟩ := list.mem_map.1 H in h2 ▸ ⟨le_add_of_nonneg_right trivial, add_lt_of_lt_sub_left $ match n-m, h1 with | (k:ℕ), h1 := by rwa [list.mem_range, to_nat_coe_nat, ← coe_nat_lt] at h1 end⟩, λ ⟨h1, h2⟩, list.mem_map.2 ⟨to_nat (r-m), list.mem_range.2 $ by rw [← coe_nat_lt, to_nat_of_nonneg (sub_nonneg_of_le h1), to_nat_of_nonneg (sub_nonneg_of_le (le_of_lt (lt_of_le_of_lt h1 h2)))]; exact sub_lt_sub_right h2 _, show m + _ = _, by rw [to_nat_of_nonneg (sub_nonneg_of_le h1), add_sub_cancel'_right]⟩⟩ instance decidable_le_lt (P : int → Prop) [decidable_pred P] (m n : ℤ) : decidable (∀ r, m ≤ r → r < n → P r) := decidable_of_iff (∀ r ∈ range m n, P r) $ by simp only [mem_range_iff, and_imp] instance decidable_le_le (P : int → Prop) [decidable_pred P] (m n : ℤ) : decidable (∀ r, m ≤ r → r ≤ n → P r) := decidable_of_iff (∀ r ∈ range m (n+1), P r) $ by simp only [mem_range_iff, and_imp, lt_add_one_iff] instance decidable_lt_lt (P : int → Prop) [decidable_pred P] (m n : ℤ) : decidable (∀ r, m < r → r < n → P r) := int.decidable_le_lt P _ _ instance decidable_lt_le (P : int → Prop) [decidable_pred P] (m n : ℤ) : decidable (∀ r, m < r → r ≤ n → P r) := int.decidable_le_le P _ _ end decidable end int open int theorem add_monoid_hom.eq_int_cast {A} [add_group A] [has_one A] (f : ℤ →+ A) (h1 : f 1 = 1) (n : ℤ) : f n = n := begin have : ∀ n : ℕ, f n = n, from λ n, (f.comp of_nat_hom.to_add_monoid_hom).eq_nat_cast h1 n, cases n, { exact this n }, rw [cast_neg_succ_of_nat, neg_succ_of_nat_eq, f.map_neg, f.map_add, h1, this] end namespace ring_hom variables {α : Type*} {β : Type*} [ring α] [ring β] @[simp] lemma eq_int_cast (f : ℤ →+* α) (n : ℤ) : f n = n := f.to_add_monoid_hom.eq_int_cast f.map_one n lemma eq_int_cast' (f : ℤ →+* α) : f = int.cast_ring_hom α := ring_hom.ext f.eq_int_cast @[simp] lemma map_int_cast (f : α →+* β) (n : ℤ) : f n = n := (f.comp (int.cast_ring_hom α)).eq_int_cast n end ring_hom @[simp, norm_cast] theorem int.cast_id (n : ℤ) : ↑n = n := ((ring_hom.id ℤ).eq_int_cast n).symm
73f3c2bd4933eb2f67aaa452f5bbe2b57995439d
6582544781b11aaa14da20f1d34bead608be4a10
/lean/love01_definitions_and_statements_demo.lean
16525f7e07332845bf6f68401a6f6aa8a592c300
[]
no_license
jpablo/logical_verification_2020
f34e4945f788d5097d80364a49b518ce92b18194
55d9ecde1d7c8ff127f3c13da346e0bc04a3cef5
refs/heads/master
1,672,293,528,924
1,602,693,572,000
1,602,693,572,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,703
lean
import .lovelib /- # LoVe Demo 1: Definitions and Statements We introduce the basics of Lean and proof assistants, without trying to carry out actual proofs yet. We focus on specifying objects and statements of their intended properties. -/ set_option pp.beta true set_option pp.generalized_field_notation false set_option pp.generalized_field_notation false namespace LoVe /- ## Proof Assistants Proof assistants (also called interactive theorem provers) * check and help develop formal proofs; * can be used to prove big theorems, not only logic puzzles; * can be tedious to use; * are highly addictive (think video games). A selection of proof assistants, classified by logical foundations: * set theory: Isabelle/ZF, Metamath, Mizar; * simple type theory: HOL4, HOL Light, Isabelle/HOL; * **dependent type theory**: Agda, Coq, **Lean**, Matita, PVS. ## Success Stories Mathematics: * the four-color theorem (in Coq); * the odd-order theorem (in Coq); * the Kepler conjecture (in HOL Light and Isabelle/HOL). Computer science: * hardware * operating systems * programming language theory * compilers * security ## Lean Lean is a fairly new proof assistant developed primarily by Leonardo de Moura (Microsoft Research) since 2012. Its mathematical library, `mathlib`, is developed under the leadership of Jeremy Avigad (Carnegie Mellon University). We use community version 3.5.1. We use its basic libraries, `mathlib`, and LoVelib`. Lean is a research project, with some rough edges. Strengths: * highly expressive logic based on a dependent type theory called the **calculus of inductive constructions**; * extended with classical axioms and quotient types; * metaprogramming framework; * modern user interface; * documentation; * open source; * endless source of puns (Lean Forward, Lean Together, Boolean, …). ## This Course ### Web Site https://lean-forward.github.io/logical-verification/2020/index.html ### Installation Instructions https://github.com/blanchette/logical_verification_2020/blob/master/README.md#logical-verification-2020---installation-instructions ### Repository (Demos, Exercises, Homework) https://github.com/blanchette/logical_verification_2020 The file you are currently looking at is a demo. There are * 13 demo files; * 13 exercise sheets; * 11 homework sheets (10 points each); * 1 project (20 points). You may submit at most 10 homework, or at most 8 homework and the project. Homework, including the project, must be done individually. The homework builds on the exercises, which build on the demos. ### The Hitchhiker's Guide to Logical Verification https://github.com/blanchette/logical_verification_2020/blob/master/hitchhikers_guide.pdf The lecture notes consist of a preface and 13 chapters. They cover the same material as the corresponding lectures but with more details. Sometimes there will not be enough time to cover everything in class, so reading the lecture notes will be necessary. ### Final Exam The course aims at teaching concepts, not syntax. Therefore, the final exam is on paper. ## Our Goal We want you to * master fundamental theory and techniques in interactive theorem proving; * familiarize yourselves with some application areas; * develop some practical skills you can apply on a larger project (as a hobby, for an MSc or PhD, or in industry); * feel ready to move to another proof assistant and apply what you have learned; * understand the domain well enough to start reading scientific papers. This course is neither a pure metatheory course nor a Lean tutorial. Lean is our vehicle, not an end in itself. ## A View of Lean In a first approximation: Lean = functional programming + logic In today's lecture, we cover inductive types, recursive functions, and lemma statements. If you are not familiar with typed functional programming (e.g., Haskell, ML, OCaml, Scala), we recommend that you study a tutorial, such as the first chapters of the online tutorial __Learn You a Haskell for Great Good!__: http://learnyouahaskell.com/chapters Make sure to at least reach the section titled "Lambdas". ## Types and Terms Similar to simply typed λ-calculus or typed functional programming languages (ML, OCaml, Haskell). Types `σ`, `τ`, `υ`: * type variables `α`; * basic types `T`; * complex types `T σ1 … σN`. Some type constructors `T` are written infix, e.g., `→` (function type). The function arrow is right-associative: `σ₁ → σ₂ → σ₃ → τ` = `σ₁ → (σ₂ → (σ₃ → τ))`. In Lean, type variables must be bound using `∀`, e.g., `∀α, α → α`. Terms `t`, `u`: * constants `c`; * variables `x`; * applications `t u`; * λ-expressions `λx, t`. __Currying__: functions can be * fully applied (e.g., `f x y z` if `f` is ternary); * partially applied (e.g., `f x y`, `f x`); * left unapplied (e.g., `f`). Application is left-associative: `f x y z` = `((f x) y) z`. -/ #check ℕ #check ℤ #check empty #check unit #check bool #check ℕ → ℤ #check ℤ → ℕ #check bool → ℕ → ℤ #check (bool → ℕ) → ℤ #check ℕ → (bool → ℕ) → ℤ #check λx : ℕ, x #check λf : ℕ → ℕ, λg : ℕ → ℕ, λh : ℕ → ℕ, λx : ℕ, h (g (f x)) #check λ(f g h : ℕ → ℕ) (x : ℕ), h (g (f x)) constants a b : ℤ constant f : ℤ → ℤ constant g : ℤ → ℤ → ℤ #check λx : ℤ, g (f (g a x)) (g x b) #check λx, g (f (g a x)) (g x b) #check λx, x constant trool : Type constants trool.true trool.false trool.maybe : trool /- ### Type Checking and Type Inference Type checking and type inference are decidable problems, but this property is quickly lost if features such as overloading or subtyping are added. Type judgment: `C ⊢ t : σ`, meaning `t` has type `σ` in local context `C`. Typing rules: —————————— Cst if c is declared with type σ C ⊢ c : σ —————————— Var if x : σ occurs in C C ⊢ x : σ C ⊢ t : σ → τ C ⊢ u : σ ——————————————————————————— App C ⊢ t u : τ C, x : σ ⊢ t : τ ———————————————————————— Lam C ⊢ (λx : σ, t) : σ → τ ### Type Inhabitation Given a type `σ`, the __type inhabitation__ problem consists of finding a term of that type. Recursive procedure: 1. If `σ` is of the form `τ → υ`, a candidate inhabitant is an anonymous function of the form `λx, _`. 2. Alternatively, you can use any constant or variable `x : τ₁ → ⋯ → τN → σ` to build the term `x _ … _`. -/ constants α β γ : Type def some_fun_of_type : (α → β → γ) → ((β → α) → β) → α → γ := λf g a, f a (g (λb, a)) /- ## Type Definitions An __inductive type__ (also called __inductive datatype__, __algebraic datatype__, or just __datatype__) is a type that consists all the values that can be built using a finite number of applications of its __constructors__, and only those. ### Natural Numbers -/ namespace my_nat /- Definition of type `nat` (= `ℕ`) of natural numbers, using Peano-style unary notation: -/ inductive nat : Type | zero : nat | succ : nat → nat #check nat #check nat.zero #check nat.succ end my_nat #print nat #print ℕ /- ### Arithmetic Expressions -/ inductive aexp : Type | num : ℤ → aexp | var : string → aexp | add : aexp → aexp → aexp | sub : aexp → aexp → aexp | mul : aexp → aexp → aexp | div : aexp → aexp → aexp /- ### Lists -/ namespace my_list inductive list (α : Type) : Type | nil : list | cons : α → list → list #check list.nil #check list.cons end my_list #print list /- ## Function Definitions The syntax for defining a function operating on an inductive type is very compact: We define a single function and use __pattern matching__ to extract the arguments to the constructors. -/ def add : ℕ → ℕ → ℕ | m nat.zero := m | m (nat.succ n) := nat.succ (add m n) #eval add 2 7 #reduce add 2 7 def mul : ℕ → ℕ → ℕ | _ nat.zero := nat.zero | m (nat.succ n) := add m (mul m n) #eval mul 2 7 #print mul #print mul._main def power : ℕ → ℕ → ℕ | _ nat.zero := 1 | m (nat.succ n) := m * power m n #eval power 2 5 def power₂ (m : ℕ) : ℕ → ℕ | nat.zero := 1 | (nat.succ n) := m * power₂ n #eval power₂ 2 5 def iter (α : Type) (z : α) (f : α → α) : ℕ → α | nat.zero := z | (nat.succ n) := f (iter n) #check iter def power₃ (m n : ℕ) : ℕ := iter ℕ 1 (λl, m * l) n #eval power₃ 2 5 def append (α : Type) : list α → list α → list α | list.nil ys := ys | (list.cons x xs) ys := list.cons x (append xs ys) #check append #eval append _ [3, 1] [4, 1, 5] /- Aliases: `[]` := `nil` `x :: xs` := `cons x xs` `[x₁, …, xN]` := `x₁ :: … :: xN` -/ def append₂ {α : Type} : list α → list α → list α | list.nil ys := ys | (list.cons x xs) ys := list.cons x (append₂ xs ys) #check append₂ #eval append₂ [3, 1] [4, 1, 5] #check @append₂ #eval @append₂ _ [3, 1] [4, 1, 5] def append₃ {α : Type} : list α → list α → list α | [] ys := ys | (x :: xs) ys := x :: append₃ xs ys def reverse {α : Type} : list α → list α | [] := [] | (x :: xs) := reverse xs ++ [x] def eval (env : string → ℤ) : aexp → ℤ | (aexp.num i) := i | (aexp.var x) := env x | (aexp.add e₁ e₂) := eval e₁ + eval e₂ | (aexp.sub e₁ e₂) := eval e₁ - eval e₂ | (aexp.mul e₁ e₂) := eval e₁ * eval e₂ | (aexp.div e₁ e₂) := eval e₁ / eval e₂ /- Lean only accepts the function definitions for which it can prove termination. In particular, it accepts __structurally recursive__ functions, which peel off exactly one constructor at a time. ## Lemma Statements Notice the similarity with `def` commands. -/ namespace sorry_lemmas lemma add_comm (m n : ℕ) : add m n = add n m := sorry lemma add_assoc (l m n : ℕ) : add (add l m) n = add l (add m n) := sorry lemma mul_comm (m n : ℕ) : mul m n = mul n m := sorry lemma mul_assoc (l m n : ℕ) : mul (mul l m) n = mul l (mul m n) := sorry lemma mul_add (l m n : ℕ) : mul l (add m n) = add (mul l m) (mul l n) := sorry lemma reverse_reverse {α : Type} (xs : list α) : reverse (reverse xs) = xs := sorry /- Axioms are like lemmas but without proofs (`:= …`). Constant declarations are like definitions but without bodies (`:= …`). -/ constants a b : ℤ axiom a_less_b : a < b end sorry_lemmas end LoVe
b3ce7de6b95c92d9b9085127be0629a713d6d2d9
4f9ca1935adf84f1bae9c5740ec1f2ad406716fa
/src/analysis/normed_space/operator_norm.lean
0fbda4d9160937f5e3fc7f46456771d0a88a19e8
[ "Apache-2.0" ]
permissive
matthew-hilty/mathlib
36fd7db866365e9ee4a0ba1d6f8ad34d068cec6c
585e107f9811719832c6656f49e1263a8eef5380
refs/heads/master
1,607,100,509,178
1,578,151,707,000
1,578,151,707,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
22,164
lean
/- Copyright (c) 2019 Jan-David Salchow. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jan-David Salchow, Sébastien Gouëzel, Jean Lo Operator norm on the space of continuous linear maps Define the operator norm on the space of continuous linear maps between normed spaces, and prove its basic properties. In particular, show that this space is itself a normed space. -/ import topology.metric_space.lipschitz analysis.normed_space.riesz_lemma import analysis.asymptotics noncomputable theory open_locale classical set_option class.instance_max_depth 70 variables {𝕜 : Type*} {E : Type*} {F : Type*} {G : Type*} [normed_group E] [normed_group F] [normed_group G] open metric continuous_linear_map lemma exists_pos_bound_of_bound {f : E → F} (M : ℝ) (h : ∀x, ∥f x∥ ≤ M * ∥x∥) : ∃ N, 0 < N ∧ ∀x, ∥f x∥ ≤ N * ∥x∥ := ⟨max M 1, lt_of_lt_of_le zero_lt_one (le_max_right _ _), λx, calc ∥f x∥ ≤ M * ∥x∥ : h x ... ≤ max M 1 * ∥x∥ : mul_le_mul_of_nonneg_right (le_max_left _ _) (norm_nonneg _) ⟩ section normed_field /- Most statements in this file require the field to be non-discrete, as this is necessary to deduce an inequality ∥f x∥ ≤ C ∥x∥ from the continuity of f. However, the other direction always holds. In this section, we just assume that 𝕜 is a normed field. In the remainder of the file, it will be non-discrete. -/ variables [normed_field 𝕜] [normed_space 𝕜 E] [normed_space 𝕜 F] (f : E →ₗ[𝕜] F) lemma linear_map.lipschitz_of_bound (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : lipschitz_with (nnreal.of_real C) f := lipschitz_with.of_dist_le $ λ x y, by simpa [dist_eq_norm] using h (x - y) lemma linear_map.uniform_continuous_of_bound (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : uniform_continuous f := (f.lipschitz_of_bound C h).to_uniform_continuous lemma linear_map.continuous_of_bound (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : continuous f := (f.lipschitz_of_bound C h).to_continuous /-- Construct a continuous linear map from a linear map and a bound on this linear map. -/ def linear_map.with_bound (h : ∃C : ℝ, ∀x, ∥f x∥ ≤ C * ∥x∥) : E →L[𝕜] F := ⟨f, let ⟨C, hC⟩ := h in linear_map.continuous_of_bound f C hC⟩ @[simp, elim_cast] lemma linear_map_with_bound_coe (h : ∃C : ℝ, ∀x, ∥f x∥ ≤ C * ∥x∥) : ((f.with_bound h) : E →ₗ[𝕜] F) = f := rfl @[simp] lemma linear_map_with_bound_apply (h : ∃C : ℝ, ∀x, ∥f x∥ ≤ C * ∥x∥) (x : E) : f.with_bound h x = f x := rfl lemma linear_map.continuous_iff_is_closed_ker {f : E →ₗ[𝕜] 𝕜} : continuous f ↔ is_closed (f.ker : set E) := begin -- the continuity of f obviously implies that its kernel is closed refine ⟨λh, (continuous_iff_is_closed.1 h) {0} (t1_space.t1 0), λh, _⟩, -- for the other direction, we assume that the kernel is closed by_cases hf : ∀x, x ∈ f.ker, { -- if f = 0, its continuity is obvious have : (f : E → 𝕜) = (λx, 0), by { ext x, simpa using hf x }, rw this, exact continuous_const }, { /- if f is not zero, we use an element x₀ ∉ ker f such that ∥x₀∥ ≤ 2 ∥x₀ - y∥ for all y ∈ ker f, given by Riesz's lemma, and prove that 2 ∥f x₀∥ / ∥x₀∥ gives a bound on the operator norm of f. For this, start from an arbitrary x and note that y = x₀ - (f x₀ / f x) x belongs to the kernel of f. Applying the above inequality to x₀ and y readily gives the conclusion. -/ push_neg at hf, let r : ℝ := (2 : ℝ)⁻¹, have : 0 ≤ r, by norm_num [r], have : r < 1, by norm_num [r], obtain ⟨x₀, x₀ker, h₀⟩ : ∃ (x₀ : E), x₀ ∉ f.ker ∧ ∀ y ∈ linear_map.ker f, r * ∥x₀∥ ≤ ∥x₀ - y∥, from riesz_lemma h hf this, have : x₀ ≠ 0, { assume h, have : x₀ ∈ f.ker, by { rw h, exact (linear_map.ker f).zero }, exact x₀ker this }, have rx₀_ne_zero : r * ∥x₀∥ ≠ 0, by { simp [norm_eq_zero, this], norm_num }, have : ∀x, ∥f x∥ ≤ (((r * ∥x₀∥)⁻¹) * ∥f x₀∥) * ∥x∥, { assume x, by_cases hx : f x = 0, { rw [hx, norm_zero], apply_rules [mul_nonneg', norm_nonneg, inv_nonneg.2, norm_nonneg] }, { let y := x₀ - (f x₀ * (f x)⁻¹ ) • x, have fy_zero : f y = 0, by calc f y = f x₀ - (f x₀ * (f x)⁻¹ ) * f x : by { dsimp [y], rw [f.map_add, f.map_neg, f.map_smul], refl } ... = 0 : by { rw [mul_assoc, inv_mul_cancel hx, mul_one, sub_eq_zero_of_eq], refl }, have A : r * ∥x₀∥ ≤ ∥f x₀∥ * ∥f x∥⁻¹ * ∥x∥, from calc r * ∥x₀∥ ≤ ∥x₀ - y∥ : h₀ _ (linear_map.mem_ker.2 fy_zero) ... = ∥(f x₀ * (f x)⁻¹ ) • x∥ : by { dsimp [y], congr, abel } ... = ∥f x₀∥ * ∥f x∥⁻¹ * ∥x∥ : by rw [norm_smul, normed_field.norm_mul, normed_field.norm_inv], calc ∥f x∥ = (r * ∥x₀∥)⁻¹ * (r * ∥x₀∥) * ∥f x∥ : by rwa [inv_mul_cancel, one_mul] ... ≤ (r * ∥x₀∥)⁻¹ * (∥f x₀∥ * ∥f x∥⁻¹ * ∥x∥) * ∥f x∥ : begin apply mul_le_mul_of_nonneg_right (mul_le_mul_of_nonneg_left A _) (norm_nonneg _), exact inv_nonneg.2 (mul_nonneg' (by norm_num) (norm_nonneg _)) end ... = (∥f x∥ ⁻¹ * ∥f x∥) * (((r * ∥x₀∥)⁻¹) * ∥f x₀∥) * ∥x∥ : by ring ... = (((r * ∥x₀∥)⁻¹) * ∥f x₀∥) * ∥x∥ : by { rw [inv_mul_cancel, one_mul], simp [norm_eq_zero, hx] } } }, exact linear_map.continuous_of_bound f _ this } end end normed_field variables [nondiscrete_normed_field 𝕜] [normed_space 𝕜 E] [normed_space 𝕜 F] [normed_space 𝕜 G] (c : 𝕜) (f g : E →L[𝕜] F) (h : F →L[𝕜] G) (x y z : E) include 𝕜 /-- A continuous linear map between normed spaces is bounded when the field is nondiscrete. The continuity ensures boundedness on a ball of some radius δ. The nondiscreteness is then used to rescale any element into an element of norm in [δ/C, δ], whose image has a controlled norm. The norm control for the original element follows by rescaling. -/ lemma linear_map.bound_of_continuous (f : E →ₗ[𝕜] F) (hf : continuous f) : ∃ C, 0 < C ∧ (∀ x : E, ∥f x∥ ≤ C * ∥x∥) := begin have : continuous_at f 0 := continuous_iff_continuous_at.1 hf _, rcases metric.tendsto_nhds_nhds.1 this 1 zero_lt_one with ⟨ε, ε_pos, hε⟩, let δ := ε/2, have δ_pos : δ > 0 := half_pos ε_pos, have H : ∀{a}, ∥a∥ ≤ δ → ∥f a∥ ≤ 1, { assume a ha, have : dist (f a) (f 0) ≤ 1, { apply le_of_lt (hε _), rw [dist_eq_norm, sub_zero], exact lt_of_le_of_lt ha (half_lt_self ε_pos) }, simpa using this }, rcases normed_field.exists_one_lt_norm 𝕜 with ⟨c, hc⟩, refine ⟨δ⁻¹ * ∥c∥, mul_pos (inv_pos δ_pos) (lt_trans zero_lt_one hc), (λx, _)⟩, by_cases h : x = 0, { simp only [h, norm_zero, mul_zero, linear_map.map_zero] }, { rcases rescale_to_shell hc δ_pos h with ⟨d, hd, dxle, ledx, dinv⟩, calc ∥f x∥ = ∥f ((d⁻¹ * d) • x)∥ : by rwa [inv_mul_cancel, one_smul] ... = ∥d∥⁻¹ * ∥f (d • x)∥ : by rw [mul_smul, linear_map.map_smul, norm_smul, normed_field.norm_inv] ... ≤ ∥d∥⁻¹ * 1 : mul_le_mul_of_nonneg_left (H dxle) (by { rw ← normed_field.norm_inv, exact norm_nonneg _ }) ... ≤ δ⁻¹ * ∥c∥ * ∥x∥ : by { rw mul_one, exact dinv } } end namespace continuous_linear_map theorem bound : ∃ C, 0 < C ∧ (∀ x : E, ∥f x∥ ≤ C * ∥x∥) := f.to_linear_map.bound_of_continuous f.2 section open asymptotics filter theorem is_O_id (l : filter E) : is_O f (λ x, x) l := let ⟨M, hMp, hM⟩ := f.bound in ⟨M, hMp, mem_sets_of_superset univ_mem_sets (λ x _, hM x)⟩ theorem is_O_comp {E : Type*} (g : F →L[𝕜] G) (f : E → F) (l : filter E) : is_O (λ x', g (f x')) f l := ((g.is_O_id ⊤).comp _).mono (map_le_iff_le_comap.mp lattice.le_top) theorem is_O_sub (f : E →L[𝕜] F) (l : filter E) (x : E) : is_O (λ x', f (x' - x)) (λ x', x' - x) l := is_O_comp f _ l end section op_norm open set real set_option class.instance_max_depth 100 /-- The operator norm of a continuous linear map is the inf of all its bounds. -/ def op_norm := Inf { c | c ≥ 0 ∧ ∀ x, ∥f x∥ ≤ c * ∥x∥ } instance has_op_norm : has_norm (E →L[𝕜] F) := ⟨op_norm⟩ -- So that invocations of real.Inf_le ma𝕜e sense: we show that the set of -- bounds is nonempty and bounded below. lemma bounds_nonempty {f : E →L[𝕜] F} : ∃ c, c ∈ { c | 0 ≤ c ∧ ∀ x, ∥f x∥ ≤ c * ∥x∥ } := let ⟨M, hMp, hMb⟩ := f.bound in ⟨M, le_of_lt hMp, hMb⟩ lemma bounds_bdd_below {f : E →L[𝕜] F} : bdd_below { c | 0 ≤ c ∧ ∀ x, ∥f x∥ ≤ c * ∥x∥ } := ⟨0, λ _ ⟨hn, _⟩, hn⟩ lemma op_norm_nonneg : 0 ≤ ∥f∥ := lb_le_Inf _ bounds_nonempty (λ _ ⟨hx, _⟩, hx) /-- The fundamental property of the operator norm: ∥f x∥ ≤ ∥f∥ * ∥x∥. -/ theorem le_op_norm : ∥f x∥ ≤ ∥f∥ * ∥x∥ := classical.by_cases (λ heq : x = 0, by { rw heq, simp }) (λ hne, have hlt : 0 < ∥x∥, from (norm_pos_iff _).2 hne, le_mul_of_div_le hlt ((le_Inf _ bounds_nonempty bounds_bdd_below).2 (λ c ⟨_, hc⟩, div_le_of_le_mul hlt (by { rw mul_comm, apply hc })))) lemma ratio_le_op_norm : ∥f x∥ / ∥x∥ ≤ ∥f∥ := (or.elim (lt_or_eq_of_le (norm_nonneg _)) (λ hlt, div_le_of_le_mul hlt (by { rw mul_comm, apply le_op_norm })) (λ heq, by { rw [←heq, div_zero], apply op_norm_nonneg })) /-- The image of the unit ball under a continuous linear map is bounded. -/ lemma unit_le_op_norm : ∥x∥ ≤ 1 → ∥f x∥ ≤ ∥f∥ := λ hx, begin rw [←(mul_one ∥f∥)], calc _ ≤ ∥f∥ * ∥x∥ : le_op_norm _ _ ... ≤ _ : mul_le_mul_of_nonneg_left hx (op_norm_nonneg _) end /-- If one controls the norm of every A x, then one controls the norm of A. -/ lemma op_norm_le_bound {M : ℝ} (hMp: 0 ≤ M) (hM : ∀ x, ∥f x∥ ≤ M * ∥x∥) : ∥f∥ ≤ M := Inf_le _ bounds_bdd_below ⟨hMp, hM⟩ /-- The operator norm satisfies the triangle inequality. -/ theorem op_norm_add_le : ∥f + g∥ ≤ ∥f∥ + ∥g∥ := Inf_le _ bounds_bdd_below ⟨add_nonneg (op_norm_nonneg _) (op_norm_nonneg _), λ x, by { rw add_mul, exact norm_add_le_of_le (le_op_norm _ _) (le_op_norm _ _) }⟩ /-- An operator is zero iff its norm vanishes. -/ theorem op_norm_zero_iff : ∥f∥ = 0 ↔ f = 0 := iff.intro (λ hn, continuous_linear_map.ext (λ x, (norm_le_zero_iff _).1 (calc _ ≤ ∥f∥ * ∥x∥ : le_op_norm _ _ ... = _ : by rw [hn, zero_mul]))) (λ hf, le_antisymm (Inf_le _ bounds_bdd_below ⟨ge_of_eq rfl, λ _, le_of_eq (by { rw [zero_mul, hf], exact norm_zero })⟩) (op_norm_nonneg _)) @[simp] lemma norm_zero : ∥(0 : E →L[𝕜] F)∥ = 0 := by rw op_norm_zero_iff /-- The norm of the identity is at most 1. It is in fact 1, except when the space is trivial where it is 0. It means that one can not do better than an inequality in general. -/ lemma norm_id : ∥(id : E →L[𝕜] E)∥ ≤ 1 := op_norm_le_bound _ zero_le_one (λx, by simp) /-- The operator norm is homogeneous. -/ lemma op_norm_smul : ∥c • f∥ = ∥c∥ * ∥f∥ := le_antisymm (Inf_le _ bounds_bdd_below ⟨mul_nonneg (norm_nonneg _) (op_norm_nonneg _), λ _, begin erw [norm_smul, mul_assoc], exact mul_le_mul_of_nonneg_left (le_op_norm _ _) (norm_nonneg _) end⟩) (lb_le_Inf _ bounds_nonempty (λ _ ⟨hn, hc⟩, (or.elim (lt_or_eq_of_le (norm_nonneg c)) (λ hlt, begin rw mul_comm, exact mul_le_of_le_div hlt (Inf_le _ bounds_bdd_below ⟨div_nonneg hn hlt, λ _, (by { rw div_mul_eq_mul_div, exact le_div_of_mul_le hlt (by { rw [ mul_comm, ←norm_smul ], exact hc _ }) })⟩) end) (λ heq, by { rw [←heq, zero_mul], exact hn })))) lemma op_norm_neg : ∥-f∥ = ∥f∥ := calc ∥-f∥ = ∥(-1:𝕜) • f∥ : by rw neg_one_smul ... = ∥(-1:𝕜)∥ * ∥f∥ : by rw op_norm_smul ... = ∥f∥ : by simp /-- Continuous linear maps themselves form a normed space with respect to the operator norm. -/ instance to_normed_group : normed_group (E →L[𝕜] F) := normed_group.of_core _ ⟨op_norm_zero_iff, op_norm_add_le, op_norm_neg⟩ instance to_normed_space : normed_space 𝕜 (E →L[𝕜] F) := ⟨op_norm_smul⟩ /-- The operator norm is submultiplicative. -/ lemma op_norm_comp_le : ∥comp h f∥ ≤ ∥h∥ * ∥f∥ := (Inf_le _ bounds_bdd_below ⟨mul_nonneg (op_norm_nonneg _) (op_norm_nonneg _), λ x, begin rw mul_assoc, calc _ ≤ ∥h∥ * ∥f x∥: le_op_norm _ _ ... ≤ _ : mul_le_mul_of_nonneg_left (le_op_norm _ _) (op_norm_nonneg _) end⟩) /-- continuous linear maps are Lipschitz continuous. -/ theorem lipschitz : lipschitz_with ⟨∥f∥, op_norm_nonneg f⟩ f := λ x y, by { rw [dist_eq_norm, dist_eq_norm, ←map_sub], apply le_op_norm } /-- A continuous linear map is automatically uniformly continuous. -/ protected theorem uniform_continuous : uniform_continuous f := f.lipschitz.to_uniform_continuous variable {f} /-- A continuous linear map is an isometry if and only if it preserves the norm. -/ lemma isometry_iff_norm_image_eq_norm : isometry f ↔ ∀x, ∥f x∥ = ∥x∥ := begin rw isometry_emetric_iff_metric, split, { assume H x, have := H x 0, rwa [dist_eq_norm, dist_eq_norm, f.map_zero, sub_zero, sub_zero] at this }, { assume H x y, rw [dist_eq_norm, dist_eq_norm, ← f.map_sub, H] } end variable (f) /-- A continuous linear map is a uniform embedding if it expands the norm by a constant factor. -/ theorem uniform_embedding_of_bound (C : ℝ) (hC : ∀x, ∥x∥ ≤ C * ∥f x∥) : uniform_embedding f := begin have Cpos : 0 < max C 1 := lt_of_lt_of_le zero_lt_one (le_max_right _ _), refine uniform_embedding_iff'.2 ⟨metric.uniform_continuous_iff.1 f.uniform_continuous, λδ δpos, ⟨δ / (max C 1), div_pos δpos Cpos, λx y hxy, _⟩⟩, calc dist x y = ∥x - y∥ : by rw dist_eq_norm ... ≤ C * ∥f (x - y)∥ : hC _ ... = C * dist (f x) (f y) : by rw [f.map_sub, dist_eq_norm] ... ≤ max C 1 * dist (f x) (f y) : mul_le_mul_of_nonneg_right (le_max_left _ _) dist_nonneg ... < max C 1 * (δ / max C 1) : mul_lt_mul_of_pos_left hxy Cpos ... = δ : by { rw mul_comm, exact div_mul_cancel _ (ne_of_lt Cpos).symm } end /-- If a continuous linear map is a uniform embedding, then it expands the norm by a positive factor.-/ theorem bound_of_uniform_embedding (hf : uniform_embedding f) : ∃ C : ℝ, 0 < C ∧ ∀x, ∥x∥ ≤ C * ∥f x∥ := begin obtain ⟨ε, εpos, hε⟩ : ∃ (ε : ℝ) (H : ε > 0), ∀ {x y : E}, dist (f x) (f y) < ε → dist x y < 1, from (uniform_embedding_iff.1 hf).2.2 1 zero_lt_one, let δ := ε/2, have δ_pos : δ > 0 := half_pos εpos, have H : ∀{x}, ∥f x∥ ≤ δ → ∥x∥ ≤ 1, { assume x hx, have : dist x 0 ≤ 1, { apply le_of_lt, apply hε, simp [dist_eq_norm], exact lt_of_le_of_lt hx (half_lt_self εpos) }, simpa using this }, rcases normed_field.exists_one_lt_norm 𝕜 with ⟨c, hc⟩, refine ⟨δ⁻¹ * ∥c∥, (mul_pos (inv_pos δ_pos) ((lt_trans zero_lt_one hc))), (λx, _)⟩, by_cases hx : f x = 0, { have : f x = f 0, by { simp [hx] }, have : x = 0 := (uniform_embedding_iff.1 hf).1 this, simp [this] }, { rcases rescale_to_shell hc δ_pos hx with ⟨d, hd, dxle, ledx, dinv⟩, have : ∥f (d • x)∥ ≤ δ, by simpa, have : ∥d • x∥ ≤ 1 := H this, calc ∥x∥ = ∥d∥⁻¹ * ∥d • x∥ : by rwa [← normed_field.norm_inv, ← norm_smul, ← mul_smul, inv_mul_cancel, one_smul] ... ≤ ∥d∥⁻¹ * 1 : mul_le_mul_of_nonneg_left this (inv_nonneg.2 (norm_nonneg _)) ... ≤ δ⁻¹ * ∥c∥ * ∥f x∥ : by rwa [mul_one] } end section uniformly_extend variables [complete_space F] (e : E →L[𝕜] G) (h_dense : dense_range e) section variables (h_e : uniform_inducing e) /-- Extension of a continuous linear map `f : E →L[𝕜] F`, with `E` a normed space and `F` a complete normed space, along a uniform and dense embedding `e : E →L[𝕜] G`. -/ def extend : G →L[𝕜] F := /- extension of `f` is continuous -/ have cont : _ := (uniform_continuous_uniformly_extend h_e h_dense f.uniform_continuous).continuous, /- extension of `f` agrees with `f` on the domain of the embedding `e` -/ have eq : _ := uniformly_extend_of_ind h_e h_dense f.uniform_continuous, { to_fun := (h_e.dense_inducing h_dense).extend f, add := begin refine is_closed_property2 h_dense (is_closed_eq _ _) _, { exact cont.comp (continuous_fst.add continuous_snd) }, { exact (cont.comp continuous_fst).add (cont.comp continuous_snd) }, { assume x y, rw ← e.map_add, simp only [eq], exact f.map_add _ _ }, end, smul := λk, begin refine is_closed_property h_dense (is_closed_eq _ _) _, { exact cont.comp (continuous_const.smul continuous_id) }, { exact (continuous_const.smul continuous_id).comp cont }, { assume x, rw ← map_smul, simp only [eq], exact map_smul _ _ _ }, end, cont := cont } @[simp] lemma extend_zero : extend (0 : E →L[𝕜] F) e h_dense h_e = 0 := begin apply ext, refine is_closed_property h_dense (is_closed_eq _ _) _, { exact (uniform_continuous_uniformly_extend h_e h_dense uniform_continuous_const).continuous }, { simp only [zero_apply], exact continuous_const }, { assume x, exact uniformly_extend_of_ind h_e h_dense uniform_continuous_const x } end end section variables {N : ℝ} (h_e : ∀x, ∥x∥ ≤ N * ∥e x∥) local notation `ψ` := f.extend e h_dense (uniform_embedding_of_bound _ _ h_e).to_uniform_inducing /-- If a dense embedding `e : E →L[𝕜] G` expands the norm by a constant factor `N⁻¹`, then the norm of the extension of `f` along `e` is bounded by `N * ∥f∥`. -/ lemma op_norm_extend_le : ∥ψ∥ ≤ N * ∥f∥ := begin have uni : uniform_inducing e := (uniform_embedding_of_bound _ _ h_e).to_uniform_inducing, have eq : ∀x, ψ (e x) = f x := uniformly_extend_of_ind uni h_dense f.uniform_continuous, by_cases N0 : 0 ≤ N, { refine op_norm_le_bound ψ _ (is_closed_property h_dense (is_closed_le _ _) _), { exact mul_nonneg N0 (norm_nonneg _) }, { exact continuous_norm.comp (cont ψ) }, { exact continuous_const.mul continuous_norm }, { assume x, rw eq, calc ∥f x∥ ≤ ∥f∥ * ∥x∥ : le_op_norm _ _ ... ≤ ∥f∥ * (N * ∥e x∥) : mul_le_mul_of_nonneg_left (h_e x) (norm_nonneg _) ... ≤ N * ∥f∥ * ∥e x∥ : by rw [mul_comm N ∥f∥, mul_assoc] } }, { have he : ∀ x : E, x = 0, { assume x, have N0 : N ≤ 0 := le_of_lt (lt_of_not_ge N0), rw ← norm_le_zero_iff, exact le_trans (h_e x) (mul_nonpos_of_nonpos_of_nonneg N0 (norm_nonneg _)) }, have hf : f = 0, { ext, simp only [he x, zero_apply, map_zero] }, have hψ : ψ = 0, { rw hf, apply extend_zero }, rw [hψ, hf, norm_zero, norm_zero, mul_zero] } end end end uniformly_extend end op_norm /-- The norm of the tensor product of a scalar linear map and of an element of a normed space is the product of the norms. -/ @[simp] lemma smul_right_norm {c : E →L[𝕜] 𝕜} {f : F} : ∥smul_right c f∥ = ∥c∥ * ∥f∥ := begin refine le_antisymm _ _, { apply op_norm_le_bound _ (mul_nonneg (norm_nonneg _) (norm_nonneg _)) (λx, _), calc ∥(c x) • f∥ = ∥c x∥ * ∥f∥ : norm_smul _ _ ... ≤ (∥c∥ * ∥x∥) * ∥f∥ : mul_le_mul_of_nonneg_right (le_op_norm _ _) (norm_nonneg _) ... = ∥c∥ * ∥f∥ * ∥x∥ : by ring }, { by_cases h : ∥f∥ = 0, { rw h, simp [norm_nonneg] }, { have : 0 < ∥f∥ := lt_of_le_of_ne (norm_nonneg _) (ne.symm h), rw ← le_div_iff this, apply op_norm_le_bound _ (div_nonneg (norm_nonneg _) this) (λx, _), rw [div_mul_eq_mul_div, le_div_iff this], calc ∥c x∥ * ∥f∥ = ∥c x • f∥ : (norm_smul _ _).symm ... = ∥((smul_right c f) : E → F) x∥ : rfl ... ≤ ∥smul_right c f∥ * ∥x∥ : le_op_norm _ _ } }, end section restrict_scalars variable (𝕜) variables {𝕜' : Type*} [normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] {E' : Type*} [normed_group E'] [normed_space 𝕜' E'] {F' : Type*} [normed_group F'] [normed_space 𝕜' F'] local attribute [instance, priority 500] normed_space.restrict_scalars /-- `𝕜`-linear continuous function induced by a `𝕜'`-linear continuous function when `𝕜'` is a normed algebra over `𝕜`. -/ def restrict_scalars (f : E' →L[𝕜'] F') : E' →L[𝕜] F' := { cont := f.cont, ..linear_map.restrict_scalars 𝕜 (f.to_linear_map) } @[simp, move_cast] lemma restrict_scalars_coe_eq_coe (f : E' →L[𝕜'] F') : (f.restrict_scalars 𝕜 : E' →ₗ[𝕜] F') = (f : E' →ₗ[𝕜'] F').restrict_scalars 𝕜 := rfl @[simp, squash_cast] lemma restrict_scalars_coe_eq_coe' (f : E' →L[𝕜'] F') : (f.restrict_scalars 𝕜 : E' → F') = f := rfl end restrict_scalars end continuous_linear_map /-- If both directions in a linear equiv `e` are continuous, then `e` is a uniform embedding. -/ lemma linear_equiv.uniform_embedding (e : E ≃ₗ[𝕜] F) (h₁ : continuous e) (h₂ : continuous e.symm) : uniform_embedding e := begin rcases linear_map.bound_of_continuous e.symm.to_linear_map h₂ with ⟨C, Cpos, hC⟩, let f : E →L[𝕜] F := { cont := h₁, ..e }, apply f.uniform_embedding_of_bound C (λx, _), have : e.symm (e x) = x := linear_equiv.symm_apply_apply _ _, conv_lhs { rw ← this }, exact hC _ end
837e83e6fb4ed9a50905d2bffc85f7a7b3deb4e0
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/specific_limits/basic.lean
b69227c9b8cf94df1e8c766386ed23578f0c704a
[ "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
24,647
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel, Johannes Hölzl, Yury G. Kudryashov, Patrick Massot -/ import algebra.geom_sum import order.filter.archimedean import order.iterate import topology.instances.ennreal /-! # A collection of specific limit computations This file, by design, is independent of `normed_space` in the import hierarchy. It contains important specific limit computations in metric spaces, in ordered rings/fields, and in specific instances of these such as `ℝ`, `ℝ≥0` and `ℝ≥0∞`. -/ noncomputable theory open classical set function filter finset metric open_locale classical topological_space nat big_operators uniformity nnreal ennreal variables {α : Type*} {β : Type*} {ι : Type*} lemma tendsto_inverse_at_top_nhds_0_nat : tendsto (λ n : ℕ, (n : ℝ)⁻¹) at_top (𝓝 0) := tendsto_inv_at_top_zero.comp tendsto_coe_nat_at_top_at_top lemma tendsto_const_div_at_top_nhds_0_nat (C : ℝ) : tendsto (λ n : ℕ, C / n) at_top (𝓝 0) := by simpa only [mul_zero] using tendsto_const_nhds.mul tendsto_inverse_at_top_nhds_0_nat lemma nnreal.tendsto_inverse_at_top_nhds_0_nat : tendsto (λ n : ℕ, (n : ℝ≥0)⁻¹) at_top (𝓝 0) := by { rw ← nnreal.tendsto_coe, convert tendsto_inverse_at_top_nhds_0_nat, simp } lemma nnreal.tendsto_const_div_at_top_nhds_0_nat (C : ℝ≥0) : tendsto (λ n : ℕ, C / n) at_top (𝓝 0) := by simpa using tendsto_const_nhds.mul nnreal.tendsto_inverse_at_top_nhds_0_nat lemma tendsto_one_div_add_at_top_nhds_0_nat : tendsto (λ n : ℕ, 1 / ((n : ℝ) + 1)) at_top (𝓝 0) := suffices tendsto (λ n : ℕ, 1 / (↑(n + 1) : ℝ)) at_top (𝓝 0), by simpa, (tendsto_add_at_top_iff_nat 1).2 (tendsto_const_div_at_top_nhds_0_nat 1) /-! ### Powers -/ lemma tendsto_add_one_pow_at_top_at_top_of_pos [linear_ordered_semiring α] [archimedean α] {r : α} (h : 0 < r) : tendsto (λ n:ℕ, (r + 1)^n) at_top at_top := tendsto_at_top_at_top_of_monotone' (λ n m, pow_le_pow (le_add_of_nonneg_left (le_of_lt h))) $ not_bdd_above_iff.2 $ λ x, set.exists_range_iff.2 $ add_one_pow_unbounded_of_pos _ h lemma tendsto_pow_at_top_at_top_of_one_lt [linear_ordered_ring α] [archimedean α] {r : α} (h : 1 < r) : tendsto (λn:ℕ, r ^ n) at_top at_top := sub_add_cancel r 1 ▸ tendsto_add_one_pow_at_top_at_top_of_pos (sub_pos.2 h) lemma nat.tendsto_pow_at_top_at_top_of_one_lt {m : ℕ} (h : 1 < m) : tendsto (λn:ℕ, m ^ n) at_top at_top := tsub_add_cancel_of_le (le_of_lt h) ▸ tendsto_add_one_pow_at_top_at_top_of_pos (tsub_pos_of_lt h) lemma tendsto_pow_at_top_nhds_0_of_lt_1 {𝕜 : Type*} [linear_ordered_field 𝕜] [archimedean 𝕜] [topological_space 𝕜] [order_topology 𝕜] {r : 𝕜} (h₁ : 0 ≤ r) (h₂ : r < 1) : tendsto (λn:ℕ, r^n) at_top (𝓝 0) := h₁.eq_or_lt.elim (assume : 0 = r, (tendsto_add_at_top_iff_nat 1).mp $ by simp [pow_succ, ← this, tendsto_const_nhds]) (assume : 0 < r, have tendsto (λn, (r⁻¹ ^ n)⁻¹) at_top (𝓝 0), from tendsto_inv_at_top_zero.comp (tendsto_pow_at_top_at_top_of_one_lt $ one_lt_inv this h₂), this.congr (λ n, by simp)) lemma tendsto_pow_at_top_nhds_within_0_of_lt_1 {𝕜 : Type*} [linear_ordered_field 𝕜] [archimedean 𝕜] [topological_space 𝕜] [order_topology 𝕜] {r : 𝕜} (h₁ : 0 < r) (h₂ : r < 1) : tendsto (λn:ℕ, r^n) at_top (𝓝[>] 0) := tendsto_inf.2 ⟨tendsto_pow_at_top_nhds_0_of_lt_1 h₁.le h₂, tendsto_principal.2 $ eventually_of_forall $ λ n, pow_pos h₁ _⟩ lemma uniformity_basis_dist_pow_of_lt_1 {α : Type*} [pseudo_metric_space α] {r : ℝ} (h₀ : 0 < r) (h₁ : r < 1) : (𝓤 α).has_basis (λ k : ℕ, true) (λ k, {p : α × α | dist p.1 p.2 < r ^ k}) := metric.mk_uniformity_basis (λ i _, pow_pos h₀ _) $ λ ε ε0, (exists_pow_lt_of_lt_one ε0 h₁).imp $ λ k hk, ⟨trivial, hk.le⟩ lemma geom_lt {u : ℕ → ℝ} {c : ℝ} (hc : 0 ≤ c) {n : ℕ} (hn : 0 < n) (h : ∀ k < n, c * u k < u (k + 1)) : c ^ n * u 0 < u n := begin refine (monotone_mul_left_of_nonneg hc).seq_pos_lt_seq_of_le_of_lt hn _ _ h, { simp }, { simp [pow_succ, mul_assoc, le_refl] } end lemma geom_le {u : ℕ → ℝ} {c : ℝ} (hc : 0 ≤ c) (n : ℕ) (h : ∀ k < n, c * u k ≤ u (k + 1)) : c ^ n * u 0 ≤ u n := by refine (monotone_mul_left_of_nonneg hc).seq_le_seq n _ _ h; simp [pow_succ, mul_assoc, le_refl] lemma lt_geom {u : ℕ → ℝ} {c : ℝ} (hc : 0 ≤ c) {n : ℕ} (hn : 0 < n) (h : ∀ k < n, u (k + 1) < c * u k) : u n < c ^ n * u 0 := begin refine (monotone_mul_left_of_nonneg hc).seq_pos_lt_seq_of_lt_of_le hn _ h _, { simp }, { simp [pow_succ, mul_assoc, le_refl] } end lemma le_geom {u : ℕ → ℝ} {c : ℝ} (hc : 0 ≤ c) (n : ℕ) (h : ∀ k < n, u (k + 1) ≤ c * u k) : u n ≤ (c ^ n) * u 0 := by refine (monotone_mul_left_of_nonneg hc).seq_le_seq n _ h _; simp [pow_succ, mul_assoc, le_refl] /-- If a sequence `v` of real numbers satisfies `k * v n ≤ v (n+1)` with `1 < k`, then it goes to +∞. -/ lemma tendsto_at_top_of_geom_le {v : ℕ → ℝ} {c : ℝ} (h₀ : 0 < v 0) (hc : 1 < c) (hu : ∀ n, c * v n ≤ v (n + 1)) : tendsto v at_top at_top := tendsto_at_top_mono (λ n, geom_le (zero_le_one.trans hc.le) n (λ k hk, hu k)) $ (tendsto_pow_at_top_at_top_of_one_lt hc).at_top_mul_const h₀ lemma nnreal.tendsto_pow_at_top_nhds_0_of_lt_1 {r : ℝ≥0} (hr : r < 1) : tendsto (λ n:ℕ, r^n) at_top (𝓝 0) := nnreal.tendsto_coe.1 $ by simp only [nnreal.coe_pow, nnreal.coe_zero, tendsto_pow_at_top_nhds_0_of_lt_1 r.coe_nonneg hr] lemma ennreal.tendsto_pow_at_top_nhds_0_of_lt_1 {r : ℝ≥0∞} (hr : r < 1) : tendsto (λ n:ℕ, r^n) at_top (𝓝 0) := begin rcases ennreal.lt_iff_exists_coe.1 hr with ⟨r, rfl, hr'⟩, rw [← ennreal.coe_zero], norm_cast at *, apply nnreal.tendsto_pow_at_top_nhds_0_of_lt_1 hr end /-! ### Geometric series-/ section geometric lemma has_sum_geometric_of_lt_1 {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : has_sum (λn:ℕ, r ^ n) (1 - r)⁻¹ := have r ≠ 1, from ne_of_lt h₂, have tendsto (λn, (r ^ n - 1) * (r - 1)⁻¹) at_top (𝓝 ((0 - 1) * (r - 1)⁻¹)), from ((tendsto_pow_at_top_nhds_0_of_lt_1 h₁ h₂).sub tendsto_const_nhds).mul tendsto_const_nhds, have (λ n, (∑ i in range n, r ^ i)) = (λ n, geom_sum r n) := rfl, (has_sum_iff_tendsto_nat_of_nonneg (pow_nonneg h₁) _).mpr $ by simp [neg_inv, geom_sum_eq, div_eq_mul_inv, *] at * lemma summable_geometric_of_lt_1 {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : summable (λn:ℕ, r ^ n) := ⟨_, has_sum_geometric_of_lt_1 h₁ h₂⟩ lemma tsum_geometric_of_lt_1 {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : ∑'n:ℕ, r ^ n = (1 - r)⁻¹ := (has_sum_geometric_of_lt_1 h₁ h₂).tsum_eq lemma has_sum_geometric_two : has_sum (λn:ℕ, ((1:ℝ)/2) ^ n) 2 := by convert has_sum_geometric_of_lt_1 _ _; norm_num lemma summable_geometric_two : summable (λn:ℕ, ((1:ℝ)/2) ^ n) := ⟨_, has_sum_geometric_two⟩ lemma summable_geometric_two_encode {ι : Type*} [encodable ι] : summable (λ (i : ι), (1/2 : ℝ)^(encodable.encode i)) := summable_geometric_two.comp_injective encodable.encode_injective lemma tsum_geometric_two : ∑'n:ℕ, ((1:ℝ)/2) ^ n = 2 := has_sum_geometric_two.tsum_eq lemma sum_geometric_two_le (n : ℕ) : ∑ (i : ℕ) in range n, (1 / (2 : ℝ)) ^ i ≤ 2 := begin have : ∀ i, 0 ≤ (1 / (2 : ℝ)) ^ i, { intro i, apply pow_nonneg, norm_num }, convert sum_le_tsum (range n) (λ i _, this i) summable_geometric_two, exact tsum_geometric_two.symm end lemma tsum_geometric_inv_two : ∑' n : ℕ, (2 : ℝ)⁻¹ ^ n = 2 := (inv_eq_one_div (2 : ℝ)).symm ▸ tsum_geometric_two /-- The sum of `2⁻¹ ^ i` for `n ≤ i` equals `2 * 2⁻¹ ^ n`. -/ lemma tsum_geometric_inv_two_ge (n : ℕ) : ∑' i, ite (n ≤ i) ((2 : ℝ)⁻¹ ^ i) 0 = 2 * 2⁻¹ ^ n := begin have A : summable (λ (i : ℕ), ite (n ≤ i) ((2⁻¹ : ℝ) ^ i) 0), { apply summable_of_nonneg_of_le _ _ summable_geometric_two; { intro i, by_cases hi : n ≤ i; simp [hi] } }, have B : (finset.range n).sum (λ (i : ℕ), ite (n ≤ i) ((2⁻¹ : ℝ)^i) 0) = 0 := finset.sum_eq_zero (λ i hi, ite_eq_right_iff.2 $ λ h, (lt_irrefl _ ((finset.mem_range.1 hi).trans_le h)).elim), simp only [← sum_add_tsum_nat_add n A, B, if_true, zero_add, zero_le', le_add_iff_nonneg_left, pow_add, tsum_mul_right, tsum_geometric_inv_two], end lemma has_sum_geometric_two' (a : ℝ) : has_sum (λn:ℕ, (a / 2) / 2 ^ n) a := begin convert has_sum.mul_left (a / 2) (has_sum_geometric_of_lt_1 (le_of_lt one_half_pos) one_half_lt_one), { funext n, simp, refl, }, { norm_num } end lemma summable_geometric_two' (a : ℝ) : summable (λ n:ℕ, (a / 2) / 2 ^ n) := ⟨a, has_sum_geometric_two' a⟩ lemma tsum_geometric_two' (a : ℝ) : ∑' n:ℕ, (a / 2) / 2^n = a := (has_sum_geometric_two' a).tsum_eq /-- **Sum of a Geometric Series** -/ lemma nnreal.has_sum_geometric {r : ℝ≥0} (hr : r < 1) : has_sum (λ n : ℕ, r ^ n) (1 - r)⁻¹ := begin apply nnreal.has_sum_coe.1, push_cast, rw [nnreal.coe_sub (le_of_lt hr)], exact has_sum_geometric_of_lt_1 r.coe_nonneg hr end lemma nnreal.summable_geometric {r : ℝ≥0} (hr : r < 1) : summable (λn:ℕ, r ^ n) := ⟨_, nnreal.has_sum_geometric hr⟩ lemma tsum_geometric_nnreal {r : ℝ≥0} (hr : r < 1) : ∑'n:ℕ, r ^ n = (1 - r)⁻¹ := (nnreal.has_sum_geometric hr).tsum_eq /-- The series `pow r` converges to `(1-r)⁻¹`. For `r < 1` the RHS is a finite number, and for `1 ≤ r` the RHS equals `∞`. -/ @[simp] lemma ennreal.tsum_geometric (r : ℝ≥0∞) : ∑'n:ℕ, r ^ n = (1 - r)⁻¹ := begin cases lt_or_le r 1 with hr hr, { rcases ennreal.lt_iff_exists_coe.1 hr with ⟨r, rfl, hr'⟩, norm_cast at *, convert ennreal.tsum_coe_eq (nnreal.has_sum_geometric hr), rw [ennreal.coe_inv $ ne_of_gt $ tsub_pos_iff_lt.2 hr] }, { rw [tsub_eq_zero_iff_le.mpr hr, ennreal.inv_zero, ennreal.tsum_eq_supr_nat, supr_eq_top], refine λ a ha, (ennreal.exists_nat_gt (lt_top_iff_ne_top.1 ha)).imp (λ n hn, lt_of_lt_of_le hn _), calc (n:ℝ≥0∞) = ∑ i in range n, 1 : by rw [sum_const, nsmul_one, card_range] ... ≤ ∑ i in range n, r ^ i : sum_le_sum (λ k _, one_le_pow_of_one_le' hr k) } end end geometric /-! ### Sequences with geometrically decaying distance in metric spaces In this paragraph, we discuss sequences in metric spaces or emetric spaces for which the distance between two consecutive terms decays geometrically. We show that such sequences are Cauchy sequences, and bound their distances to the limit. We also discuss series with geometrically decaying terms. -/ section edist_le_geometric variables [pseudo_emetric_space α] (r C : ℝ≥0∞) (hr : r < 1) (hC : C ≠ ⊤) {f : ℕ → α} (hu : ∀n, edist (f n) (f (n+1)) ≤ C * r^n) include hr hC hu /-- If `edist (f n) (f (n+1))` is bounded by `C * r^n`, `C ≠ ∞`, `r < 1`, then `f` is a Cauchy sequence.-/ lemma cauchy_seq_of_edist_le_geometric : cauchy_seq f := begin refine cauchy_seq_of_edist_le_of_tsum_ne_top _ hu _, rw [ennreal.tsum_mul_left, ennreal.tsum_geometric], refine ennreal.mul_ne_top hC (ennreal.inv_ne_top.2 _), exact (tsub_pos_iff_lt.2 hr).ne' end omit hr hC /-- If `edist (f n) (f (n+1))` is bounded by `C * r^n`, then the distance from `f n` to the limit of `f` is bounded above by `C * r^n / (1 - r)`. -/ lemma edist_le_of_edist_le_geometric_of_tendsto {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) : edist (f n) a ≤ (C * r^n) / (1 - r) := begin convert edist_le_tsum_of_edist_le_of_tendsto _ hu ha _, simp only [pow_add, ennreal.tsum_mul_left, ennreal.tsum_geometric, div_eq_mul_inv, mul_assoc] end /-- If `edist (f n) (f (n+1))` is bounded by `C * r^n`, then the distance from `f 0` to the limit of `f` is bounded above by `C / (1 - r)`. -/ lemma edist_le_of_edist_le_geometric_of_tendsto₀ {a : α} (ha : tendsto f at_top (𝓝 a)) : edist (f 0) a ≤ C / (1 - r) := by simpa only [pow_zero, mul_one] using edist_le_of_edist_le_geometric_of_tendsto r C hu ha 0 end edist_le_geometric section edist_le_geometric_two variables [pseudo_emetric_space α] (C : ℝ≥0∞) (hC : C ≠ ⊤) {f : ℕ → α} (hu : ∀n, edist (f n) (f (n+1)) ≤ C / 2^n) {a : α} (ha : tendsto f at_top (𝓝 a)) include hC hu /-- If `edist (f n) (f (n+1))` is bounded by `C * 2^-n`, then `f` is a Cauchy sequence.-/ lemma cauchy_seq_of_edist_le_geometric_two : cauchy_seq f := begin simp only [div_eq_mul_inv, ennreal.inv_pow] at hu, refine cauchy_seq_of_edist_le_geometric 2⁻¹ C _ hC hu, simp [ennreal.one_lt_two] end omit hC include ha /-- If `edist (f n) (f (n+1))` is bounded by `C * 2^-n`, then the distance from `f n` to the limit of `f` is bounded above by `2 * C * 2^-n`. -/ lemma edist_le_of_edist_le_geometric_two_of_tendsto (n : ℕ) : edist (f n) a ≤ 2 * C / 2^n := begin simp only [div_eq_mul_inv, ennreal.inv_pow] at *, rw [mul_assoc, mul_comm], convert edist_le_of_edist_le_geometric_of_tendsto 2⁻¹ C hu ha n, rw [ennreal.one_sub_inv_two, inv_inv] end /-- If `edist (f n) (f (n+1))` is bounded by `C * 2^-n`, then the distance from `f 0` to the limit of `f` is bounded above by `2 * C`. -/ lemma edist_le_of_edist_le_geometric_two_of_tendsto₀: edist (f 0) a ≤ 2 * C := by simpa only [pow_zero, div_eq_mul_inv, ennreal.inv_one, mul_one] using edist_le_of_edist_le_geometric_two_of_tendsto C hu ha 0 end edist_le_geometric_two section le_geometric variables [pseudo_metric_space α] {r C : ℝ} (hr : r < 1) {f : ℕ → α} (hu : ∀n, dist (f n) (f (n+1)) ≤ C * r^n) include hr hu lemma aux_has_sum_of_le_geometric : has_sum (λ n : ℕ, C * r^n) (C / (1 - r)) := begin rcases sign_cases_of_C_mul_pow_nonneg (λ n, dist_nonneg.trans (hu n)) with rfl | ⟨C₀, r₀⟩, { simp [has_sum_zero] }, { refine has_sum.mul_left C _, simpa using has_sum_geometric_of_lt_1 r₀ hr } end variables (r C) /-- If `dist (f n) (f (n+1))` is bounded by `C * r^n`, `r < 1`, then `f` is a Cauchy sequence. Note that this lemma does not assume `0 ≤ C` or `0 ≤ r`. -/ lemma cauchy_seq_of_le_geometric : cauchy_seq f := cauchy_seq_of_dist_le_of_summable _ hu ⟨_, aux_has_sum_of_le_geometric hr hu⟩ /-- If `dist (f n) (f (n+1))` is bounded by `C * r^n`, `r < 1`, then the distance from `f n` to the limit of `f` is bounded above by `C * r^n / (1 - r)`. -/ lemma dist_le_of_le_geometric_of_tendsto₀ {a : α} (ha : tendsto f at_top (𝓝 a)) : dist (f 0) a ≤ C / (1 - r) := (aux_has_sum_of_le_geometric hr hu).tsum_eq ▸ dist_le_tsum_of_dist_le_of_tendsto₀ _ hu ⟨_, aux_has_sum_of_le_geometric hr hu⟩ ha /-- If `dist (f n) (f (n+1))` is bounded by `C * r^n`, `r < 1`, then the distance from `f 0` to the limit of `f` is bounded above by `C / (1 - r)`. -/ lemma dist_le_of_le_geometric_of_tendsto {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) : dist (f n) a ≤ (C * r^n) / (1 - r) := begin have := aux_has_sum_of_le_geometric hr hu, convert dist_le_tsum_of_dist_le_of_tendsto _ hu ⟨_, this⟩ ha n, simp only [pow_add, mul_left_comm C, mul_div_right_comm], rw [mul_comm], exact (this.mul_left _).tsum_eq.symm end omit hr hu variable (hu₂ : ∀ n, dist (f n) (f (n+1)) ≤ (C / 2) / 2^n) /-- If `dist (f n) (f (n+1))` is bounded by `(C / 2) / 2^n`, then `f` is a Cauchy sequence. -/ lemma cauchy_seq_of_le_geometric_two : cauchy_seq f := cauchy_seq_of_dist_le_of_summable _ hu₂ $ ⟨_, has_sum_geometric_two' C⟩ /-- If `dist (f n) (f (n+1))` is bounded by `(C / 2) / 2^n`, then the distance from `f 0` to the limit of `f` is bounded above by `C`. -/ lemma dist_le_of_le_geometric_two_of_tendsto₀ {a : α} (ha : tendsto f at_top (𝓝 a)) : dist (f 0) a ≤ C := (tsum_geometric_two' C) ▸ dist_le_tsum_of_dist_le_of_tendsto₀ _ hu₂ (summable_geometric_two' C) ha include hu₂ /-- If `dist (f n) (f (n+1))` is bounded by `(C / 2) / 2^n`, then the distance from `f n` to the limit of `f` is bounded above by `C / 2^n`. -/ lemma dist_le_of_le_geometric_two_of_tendsto {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) : dist (f n) a ≤ C / 2^n := begin convert dist_le_tsum_of_dist_le_of_tendsto _ hu₂ (summable_geometric_two' C) ha n, simp only [add_comm n, pow_add, ← div_div], symmetry, exact ((has_sum_geometric_two' C).div_const _).tsum_eq end end le_geometric /-! ### Summability tests based on comparison with geometric series -/ /-- A series whose terms are bounded by the terms of a converging geometric series converges. -/ lemma summable_one_div_pow_of_le {m : ℝ} {f : ℕ → ℕ} (hm : 1 < m) (fi : ∀ i, i ≤ f i) : summable (λ i, 1 / m ^ f i) := begin refine summable_of_nonneg_of_le (λ a, one_div_nonneg.mpr (pow_nonneg (zero_le_one.trans hm.le) _)) (λ a, _) (summable_geometric_of_lt_1 (one_div_nonneg.mpr (zero_le_one.trans hm.le)) ((one_div_lt (zero_lt_one.trans hm) zero_lt_one).mpr (one_div_one.le.trans_lt hm))), rw [div_pow, one_pow], refine (one_div_le_one_div _ _).mpr (pow_le_pow hm.le (fi a)); exact pow_pos (zero_lt_one.trans hm) _ end /-! ### Positive sequences with small sums on encodable types -/ /-- For any positive `ε`, define on an encodable type a positive sequence with sum less than `ε` -/ def pos_sum_of_encodable {ε : ℝ} (hε : 0 < ε) (ι) [encodable ι] : {ε' : ι → ℝ // (∀ i, 0 < ε' i) ∧ ∃ c, has_sum ε' c ∧ c ≤ ε} := begin let f := λ n, (ε / 2) / 2 ^ n, have hf : has_sum f ε := has_sum_geometric_two' _, have f0 : ∀ n, 0 < f n := λ n, div_pos (half_pos hε) (pow_pos zero_lt_two _), refine ⟨f ∘ encodable.encode, λ i, f0 _, _⟩, rcases hf.summable.comp_injective (@encodable.encode_injective ι _) with ⟨c, hg⟩, refine ⟨c, hg, has_sum_le_inj _ (@encodable.encode_injective ι _) _ _ hg hf⟩, { assume i _, exact le_of_lt (f0 _) }, { assume n, exact le_rfl } end lemma set.countable.exists_pos_has_sum_le {ι : Type*} {s : set ι} (hs : s.countable) {ε : ℝ} (hε : 0 < ε) : ∃ ε' : ι → ℝ, (∀ i, 0 < ε' i) ∧ ∃ c, has_sum (λ i : s, ε' i) c ∧ c ≤ ε := begin haveI := hs.to_encodable, rcases pos_sum_of_encodable hε s with ⟨f, hf0, ⟨c, hfc, hcε⟩⟩, refine ⟨λ i, if h : i ∈ s then f ⟨i, h⟩ else 1, λ i, _, ⟨c, _, hcε⟩⟩, { split_ifs, exacts [hf0 _, zero_lt_one] }, { simpa only [subtype.coe_prop, dif_pos, subtype.coe_eta] } end lemma set.countable.exists_pos_forall_sum_le {ι : Type*} {s : set ι} (hs : s.countable) {ε : ℝ} (hε : 0 < ε) : ∃ ε' : ι → ℝ, (∀ i, 0 < ε' i) ∧ ∀ t : finset ι, ↑t ⊆ s → ∑ i in t, ε' i ≤ ε := begin rcases hs.exists_pos_has_sum_le hε with ⟨ε', hpos, c, hε'c, hcε⟩, refine ⟨ε', hpos, λ t ht, _⟩, rw [← sum_subtype_of_mem _ ht], refine (sum_le_has_sum _ _ hε'c).trans hcε, exact λ _ _, (hpos _).le end namespace nnreal theorem exists_pos_sum_of_encodable {ε : ℝ≥0} (hε : ε ≠ 0) (ι) [encodable ι] : ∃ ε' : ι → ℝ≥0, (∀ i, 0 < ε' i) ∧ ∃c, has_sum ε' c ∧ c < ε := let ⟨a, a0, aε⟩ := exists_between (pos_iff_ne_zero.2 hε) in let ⟨ε', hε', c, hc, hcε⟩ := pos_sum_of_encodable a0 ι in ⟨ λi, ⟨ε' i, le_of_lt $ hε' i⟩, assume i, nnreal.coe_lt_coe.1 $ hε' i, ⟨c, has_sum_le (assume i, le_of_lt $ hε' i) has_sum_zero hc ⟩, nnreal.has_sum_coe.1 hc, lt_of_le_of_lt (nnreal.coe_le_coe.1 hcε) aε ⟩ end nnreal namespace ennreal theorem exists_pos_sum_of_encodable {ε : ℝ≥0∞} (hε : ε ≠ 0) (ι) [encodable ι] : ∃ ε' : ι → ℝ≥0, (∀ i, 0 < ε' i) ∧ ∑' i, (ε' i : ℝ≥0∞) < ε := begin rcases exists_between (pos_iff_ne_zero.2 hε) with ⟨r, h0r, hrε⟩, rcases lt_iff_exists_coe.1 hrε with ⟨x, rfl, hx⟩, rcases nnreal.exists_pos_sum_of_encodable (coe_pos.1 h0r).ne' ι with ⟨ε', hp, c, hc, hcr⟩, exact ⟨ε', hp, (ennreal.tsum_coe_eq hc).symm ▸ lt_trans (coe_lt_coe.2 hcr) hrε⟩ end theorem exists_pos_sum_of_encodable' {ε : ℝ≥0∞} (hε : ε ≠ 0) (ι) [encodable ι] : ∃ ε' : ι → ℝ≥0∞, (∀ i, 0 < ε' i) ∧ (∑' i, ε' i) < ε := let ⟨δ, δpos, hδ⟩ := exists_pos_sum_of_encodable hε ι in ⟨λ i, δ i, λ i, ennreal.coe_pos.2 (δpos i), hδ⟩ theorem exists_pos_tsum_mul_lt_of_encodable {ε : ℝ≥0∞} (hε : ε ≠ 0) {ι} [encodable ι] (w : ι → ℝ≥0∞) (hw : ∀ i, w i ≠ ∞) : ∃ δ : ι → ℝ≥0, (∀ i, 0 < δ i) ∧ ∑' i, (w i * δ i : ℝ≥0∞) < ε := begin lift w to ι → ℝ≥0 using hw, rcases exists_pos_sum_of_encodable hε ι with ⟨δ', Hpos, Hsum⟩, have : ∀ i, 0 < max 1 (w i), from λ i, zero_lt_one.trans_le (le_max_left _ _), refine ⟨λ i, δ' i / max 1 (w i), λ i, nnreal.div_pos (Hpos _) (this i), _⟩, refine lt_of_le_of_lt (ennreal.tsum_le_tsum $ λ i, _) Hsum, rw [coe_div (this i).ne'], refine mul_le_of_le_div' (ennreal.mul_le_mul le_rfl $ ennreal.inv_le_inv.2 _), exact coe_le_coe.2 (le_max_right _ _) end end ennreal /-! ### Factorial -/ lemma factorial_tendsto_at_top : tendsto nat.factorial at_top at_top := tendsto_at_top_at_top_of_monotone nat.monotone_factorial (λ n, ⟨n, n.self_le_factorial⟩) lemma tendsto_factorial_div_pow_self_at_top : tendsto (λ n, n! / n^n : ℕ → ℝ) at_top (𝓝 0) := tendsto_of_tendsto_of_tendsto_of_le_of_le' tendsto_const_nhds (tendsto_const_div_at_top_nhds_0_nat 1) (eventually_of_forall $ λ n, div_nonneg (by exact_mod_cast n.factorial_pos.le) (pow_nonneg (by exact_mod_cast n.zero_le) _)) begin refine (eventually_gt_at_top 0).mono (λ n hn, _), rcases nat.exists_eq_succ_of_ne_zero hn.ne.symm with ⟨k, rfl⟩, rw [← prod_range_add_one_eq_factorial, pow_eq_prod_const, div_eq_mul_inv, ← inv_eq_one_div, prod_nat_cast, nat.cast_succ, ← prod_inv_distrib', ← prod_mul_distrib, finset.prod_range_succ'], simp only [prod_range_succ', one_mul, nat.cast_add, zero_add, nat.cast_one], refine mul_le_of_le_one_left (inv_nonneg.mpr $ by exact_mod_cast hn.le) (prod_le_one _ _); intros x hx; rw finset.mem_range at hx, { refine mul_nonneg _ (inv_nonneg.mpr _); norm_cast; linarith }, { refine (div_le_one $ by exact_mod_cast hn).mpr _, norm_cast, linarith } end /-! ### Ceil and floor -/ section lemma tendsto_nat_floor_at_top {α : Type*} [linear_ordered_semiring α] [floor_semiring α] : tendsto (λ (x : α), ⌊x⌋₊) at_top at_top := nat.floor_mono.tendsto_at_top_at_top (λ x, ⟨max 0 (x + 1), by simp [nat.le_floor_iff]⟩) variables {R : Type*} [topological_space R] [linear_ordered_field R] [order_topology R] [floor_ring R] lemma tendsto_nat_floor_mul_div_at_top {a : R} (ha : 0 ≤ a) : tendsto (λ x, (⌊a * x⌋₊ : R) / x) at_top (𝓝 a) := begin have A : tendsto (λ (x : R), a - x⁻¹) at_top (𝓝 (a - 0)) := tendsto_const_nhds.sub tendsto_inv_at_top_zero, rw sub_zero at A, apply tendsto_of_tendsto_of_tendsto_of_le_of_le' A tendsto_const_nhds, { refine eventually_at_top.2 ⟨1, λ x hx, _⟩, simp only [le_div_iff (zero_lt_one.trans_le hx), sub_mul, inv_mul_cancel (zero_lt_one.trans_le hx).ne'], have := nat.lt_floor_add_one (a * x), linarith }, { refine eventually_at_top.2 ⟨1, λ x hx, _⟩, rw div_le_iff (zero_lt_one.trans_le hx), simp [nat.floor_le (mul_nonneg ha (zero_le_one.trans hx))] } end lemma tendsto_nat_floor_div_at_top : tendsto (λ x, (⌊x⌋₊ : R) / x) at_top (𝓝 1) := by simpa using tendsto_nat_floor_mul_div_at_top (@zero_le_one R _) lemma tendsto_nat_ceil_mul_div_at_top {a : R} (ha : 0 ≤ a) : tendsto (λ x, (⌈a * x⌉₊ : R) / x) at_top (𝓝 a) := begin have A : tendsto (λ (x : R), a + x⁻¹) at_top (𝓝 (a + 0)) := tendsto_const_nhds.add tendsto_inv_at_top_zero, rw add_zero at A, apply tendsto_of_tendsto_of_tendsto_of_le_of_le' tendsto_const_nhds A, { refine eventually_at_top.2 ⟨1, λ x hx, _⟩, rw le_div_iff (zero_lt_one.trans_le hx), exact nat.le_ceil _ }, { refine eventually_at_top.2 ⟨1, λ x hx, _⟩, simp [div_le_iff (zero_lt_one.trans_le hx), inv_mul_cancel (zero_lt_one.trans_le hx).ne', (nat.ceil_lt_add_one ((mul_nonneg ha (zero_le_one.trans hx)))).le, add_mul] } end lemma tendsto_nat_ceil_div_at_top : tendsto (λ x, (⌈x⌉₊ : R) / x) at_top (𝓝 1) := by simpa using tendsto_nat_ceil_mul_div_at_top (@zero_le_one R _) end
8207a558effabbaa0b24567ab7338c119e97d9d0
5d166a16ae129621cb54ca9dde86c275d7d2b483
/tests/lean/unfold1.lean
9845efef3232929a372fc23892f9a011af256575
[ "Apache-2.0" ]
permissive
jcarlson23/lean
b00098763291397e0ac76b37a2dd96bc013bd247
8de88701247f54d325edd46c0eed57aeacb64baf
refs/heads/master
1,611,571,813,719
1,497,020,963,000
1,497,021,515,000
93,882,536
1
0
null
1,497,029,896,000
1,497,029,896,000
null
UTF-8
Lean
false
false
404
lean
open tactic meta definition rewriteH (Hname : name) : tactic unit := do get_local Hname >>= rewrite_core reducible tt tt occurrences.all ff, try reflexivity example (l : list nat) : list.append l [] = l := by do get_local `l >>= λ H, induction H [`h, `t, `iH], -- dunfold [`list.append], trace_state, trace "------", reflexivity, dunfold [`list.append], trace_state, rewriteH `iH
82c83efccf927a4afdbee6d4d6394c024bfe74d9
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/calculus/deriv/add.lean
c199f455536e6e34fee143320c8cf5cfc0015aa7
[ "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
11,333
lean
/- Copyright (c) 2019 Gabriel Ebner All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner, Sébastien Gouëzel, Yury Kudryashov, Anatole Dedecker -/ import analysis.calculus.deriv.basic import analysis.calculus.fderiv.add /-! # One-dimensional derivatives of sums etc > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we prove formulas about derivatives of `f + g`, `-f`, `f - g`, and `∑ i, f i x` for functions from the base field to a normed space over this field. For a more detailed overview of one-dimensional derivatives in mathlib, see the module docstring of `analysis/calculus/deriv/basic`. ## Keywords derivative -/ universes u v w open_locale classical topology big_operators filter ennreal open filter asymptotics set variables {𝕜 : Type u} [nontrivially_normed_field 𝕜] variables {F : Type v} [normed_add_comm_group F] [normed_space 𝕜 F] variables {E : Type w} [normed_add_comm_group E] [normed_space 𝕜 E] variables {f f₀ f₁ g : 𝕜 → F} variables {f' f₀' f₁' g' : F} variables {x : 𝕜} variables {s t : set 𝕜} variables {L : filter 𝕜} section add /-! ### Derivative of the sum of two functions -/ theorem has_deriv_at_filter.add (hf : has_deriv_at_filter f f' x L) (hg : has_deriv_at_filter g g' x L) : has_deriv_at_filter (λ y, f y + g y) (f' + g') x L := by simpa using (hf.add hg).has_deriv_at_filter theorem has_strict_deriv_at.add (hf : has_strict_deriv_at f f' x) (hg : has_strict_deriv_at g g' x) : has_strict_deriv_at (λ y, f y + g y) (f' + g') x := by simpa using (hf.add hg).has_strict_deriv_at theorem has_deriv_within_at.add (hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) : has_deriv_within_at (λ y, f y + g y) (f' + g') s x := hf.add hg theorem has_deriv_at.add (hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) : has_deriv_at (λ x, f x + g x) (f' + g') x := hf.add hg lemma deriv_within_add (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : deriv_within (λy, f y + g y) s x = deriv_within f s x + deriv_within g s x := (hf.has_deriv_within_at.add hg.has_deriv_within_at).deriv_within hxs @[simp] lemma deriv_add (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : deriv (λy, f y + g y) x = deriv f x + deriv g x := (hf.has_deriv_at.add hg.has_deriv_at).deriv theorem has_deriv_at_filter.add_const (hf : has_deriv_at_filter f f' x L) (c : F) : has_deriv_at_filter (λ y, f y + c) f' x L := add_zero f' ▸ hf.add (has_deriv_at_filter_const x L c) theorem has_deriv_within_at.add_const (hf : has_deriv_within_at f f' s x) (c : F) : has_deriv_within_at (λ y, f y + c) f' s x := hf.add_const c theorem has_deriv_at.add_const (hf : has_deriv_at f f' x) (c : F) : has_deriv_at (λ x, f x + c) f' x := hf.add_const c lemma deriv_within_add_const (hxs : unique_diff_within_at 𝕜 s x) (c : F) : deriv_within (λy, f y + c) s x = deriv_within f s x := by simp only [deriv_within, fderiv_within_add_const hxs] lemma deriv_add_const (c : F) : deriv (λy, f y + c) x = deriv f x := by simp only [deriv, fderiv_add_const] @[simp] lemma deriv_add_const' (c : F) : deriv (λ y, f y + c) = deriv f := funext $ λ x, deriv_add_const c theorem has_deriv_at_filter.const_add (c : F) (hf : has_deriv_at_filter f f' x L) : has_deriv_at_filter (λ y, c + f y) f' x L := zero_add f' ▸ (has_deriv_at_filter_const x L c).add hf theorem has_deriv_within_at.const_add (c : F) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ y, c + f y) f' s x := hf.const_add c theorem has_deriv_at.const_add (c : F) (hf : has_deriv_at f f' x) : has_deriv_at (λ x, c + f x) f' x := hf.const_add c lemma deriv_within_const_add (hxs : unique_diff_within_at 𝕜 s x) (c : F) : deriv_within (λy, c + f y) s x = deriv_within f s x := by simp only [deriv_within, fderiv_within_const_add hxs] lemma deriv_const_add (c : F) : deriv (λy, c + f y) x = deriv f x := by simp only [deriv, fderiv_const_add] @[simp] lemma deriv_const_add' (c : F) : deriv (λ y, c + f y) = deriv f := funext $ λ x, deriv_const_add c end add section sum /-! ### Derivative of a finite sum of functions -/ open_locale big_operators variables {ι : Type*} {u : finset ι} {A : ι → (𝕜 → F)} {A' : ι → F} theorem has_deriv_at_filter.sum (h : ∀ i ∈ u, has_deriv_at_filter (A i) (A' i) x L) : has_deriv_at_filter (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x L := by simpa [continuous_linear_map.sum_apply] using (has_fderiv_at_filter.sum h).has_deriv_at_filter theorem has_strict_deriv_at.sum (h : ∀ i ∈ u, has_strict_deriv_at (A i) (A' i) x) : has_strict_deriv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x := by simpa [continuous_linear_map.sum_apply] using (has_strict_fderiv_at.sum h).has_strict_deriv_at theorem has_deriv_within_at.sum (h : ∀ i ∈ u, has_deriv_within_at (A i) (A' i) s x) : has_deriv_within_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) s x := has_deriv_at_filter.sum h theorem has_deriv_at.sum (h : ∀ i ∈ u, has_deriv_at (A i) (A' i) x) : has_deriv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x := has_deriv_at_filter.sum h lemma deriv_within_sum (hxs : unique_diff_within_at 𝕜 s x) (h : ∀ i ∈ u, differentiable_within_at 𝕜 (A i) s x) : deriv_within (λ y, ∑ i in u, A i y) s x = ∑ i in u, deriv_within (A i) s x := (has_deriv_within_at.sum (λ i hi, (h i hi).has_deriv_within_at)).deriv_within hxs @[simp] lemma deriv_sum (h : ∀ i ∈ u, differentiable_at 𝕜 (A i) x) : deriv (λ y, ∑ i in u, A i y) x = ∑ i in u, deriv (A i) x := (has_deriv_at.sum (λ i hi, (h i hi).has_deriv_at)).deriv end sum section neg /-! ### Derivative of the negative of a function -/ theorem has_deriv_at_filter.neg (h : has_deriv_at_filter f f' x L) : has_deriv_at_filter (λ x, -f x) (-f') x L := by simpa using h.neg.has_deriv_at_filter theorem has_deriv_within_at.neg (h : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, -f x) (-f') s x := h.neg theorem has_deriv_at.neg (h : has_deriv_at f f' x) : has_deriv_at (λ x, -f x) (-f') x := h.neg theorem has_strict_deriv_at.neg (h : has_strict_deriv_at f f' x) : has_strict_deriv_at (λ x, -f x) (-f') x := by simpa using h.neg.has_strict_deriv_at lemma deriv_within.neg (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λy, -f y) s x = - deriv_within f s x := by simp only [deriv_within, fderiv_within_neg hxs, continuous_linear_map.neg_apply] lemma deriv.neg : deriv (λy, -f y) x = - deriv f x := by simp only [deriv, fderiv_neg, continuous_linear_map.neg_apply] @[simp] lemma deriv.neg' : deriv (λy, -f y) = (λ x, - deriv f x) := funext $ λ x, deriv.neg end neg section neg2 /-! ### Derivative of the negation function (i.e `has_neg.neg`) -/ variables (s x L) theorem has_deriv_at_filter_neg : has_deriv_at_filter has_neg.neg (-1) x L := has_deriv_at_filter.neg $ has_deriv_at_filter_id _ _ theorem has_deriv_within_at_neg : has_deriv_within_at has_neg.neg (-1) s x := has_deriv_at_filter_neg _ _ theorem has_deriv_at_neg : has_deriv_at has_neg.neg (-1) x := has_deriv_at_filter_neg _ _ theorem has_deriv_at_neg' : has_deriv_at (λ x, -x) (-1) x := has_deriv_at_filter_neg _ _ theorem has_strict_deriv_at_neg : has_strict_deriv_at has_neg.neg (-1) x := has_strict_deriv_at.neg $ has_strict_deriv_at_id _ lemma deriv_neg : deriv has_neg.neg x = -1 := has_deriv_at.deriv (has_deriv_at_neg x) @[simp] lemma deriv_neg' : deriv (has_neg.neg : 𝕜 → 𝕜) = λ _, -1 := funext deriv_neg @[simp] lemma deriv_neg'' : deriv (λ x : 𝕜, -x) x = -1 := deriv_neg x lemma deriv_within_neg (hxs : unique_diff_within_at 𝕜 s x) : deriv_within has_neg.neg s x = -1 := (has_deriv_within_at_neg x s).deriv_within hxs lemma differentiable_neg : differentiable 𝕜 (has_neg.neg : 𝕜 → 𝕜) := differentiable.neg differentiable_id lemma differentiable_on_neg : differentiable_on 𝕜 (has_neg.neg : 𝕜 → 𝕜) s := differentiable_on.neg differentiable_on_id end neg2 section sub /-! ### Derivative of the difference of two functions -/ theorem has_deriv_at_filter.sub (hf : has_deriv_at_filter f f' x L) (hg : has_deriv_at_filter g g' x L) : has_deriv_at_filter (λ x, f x - g x) (f' - g') x L := by simpa only [sub_eq_add_neg] using hf.add hg.neg theorem has_deriv_within_at.sub (hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) : has_deriv_within_at (λ x, f x - g x) (f' - g') s x := hf.sub hg theorem has_deriv_at.sub (hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) : has_deriv_at (λ x, f x - g x) (f' - g') x := hf.sub hg theorem has_strict_deriv_at.sub (hf : has_strict_deriv_at f f' x) (hg : has_strict_deriv_at g g' x) : has_strict_deriv_at (λ x, f x - g x) (f' - g') x := by simpa only [sub_eq_add_neg] using hf.add hg.neg lemma deriv_within_sub (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : deriv_within (λy, f y - g y) s x = deriv_within f s x - deriv_within g s x := (hf.has_deriv_within_at.sub hg.has_deriv_within_at).deriv_within hxs @[simp] lemma deriv_sub (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : deriv (λ y, f y - g y) x = deriv f x - deriv g x := (hf.has_deriv_at.sub hg.has_deriv_at).deriv theorem has_deriv_at_filter.sub_const (hf : has_deriv_at_filter f f' x L) (c : F) : has_deriv_at_filter (λ x, f x - c) f' x L := by simpa only [sub_eq_add_neg] using hf.add_const (-c) theorem has_deriv_within_at.sub_const (hf : has_deriv_within_at f f' s x) (c : F) : has_deriv_within_at (λ x, f x - c) f' s x := hf.sub_const c theorem has_deriv_at.sub_const (hf : has_deriv_at f f' x) (c : F) : has_deriv_at (λ x, f x - c) f' x := hf.sub_const c lemma deriv_within_sub_const (hxs : unique_diff_within_at 𝕜 s x) (c : F) : deriv_within (λy, f y - c) s x = deriv_within f s x := by simp only [deriv_within, fderiv_within_sub_const hxs] lemma deriv_sub_const (c : F) : deriv (λ y, f y - c) x = deriv f x := by simp only [deriv, fderiv_sub_const] theorem has_deriv_at_filter.const_sub (c : F) (hf : has_deriv_at_filter f f' x L) : has_deriv_at_filter (λ x, c - f x) (-f') x L := by simpa only [sub_eq_add_neg] using hf.neg.const_add c theorem has_deriv_within_at.const_sub (c : F) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, c - f x) (-f') s x := hf.const_sub c theorem has_strict_deriv_at.const_sub (c : F) (hf : has_strict_deriv_at f f' x) : has_strict_deriv_at (λ x, c - f x) (-f') x := by simpa only [sub_eq_add_neg] using hf.neg.const_add c theorem has_deriv_at.const_sub (c : F) (hf : has_deriv_at f f' x) : has_deriv_at (λ x, c - f x) (-f') x := hf.const_sub c lemma deriv_within_const_sub (hxs : unique_diff_within_at 𝕜 s x) (c : F) : deriv_within (λy, c - f y) s x = -deriv_within f s x := by simp [deriv_within, fderiv_within_const_sub hxs] lemma deriv_const_sub (c : F) : deriv (λ y, c - f y) x = -deriv f x := by simp only [← deriv_within_univ, deriv_within_const_sub (unique_diff_within_at_univ : unique_diff_within_at 𝕜 _ _)] end sub
6d739a21a180baf991de601dd47c8782a62ef1e3
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/run/sigma_match.lean
31f85efb8c4fb416acc60f14839f268a9942b7e3
[ "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
758
lean
open sigma constant {l₁ l₂} hom {A : Type l₁} {B : Type l₂} (a : A) (b : B) : Type (max l₁ l₂) attribute [reducible] noncomputable definition arrow_ob (A B : Type) : Type := Σ (a : A) (b : B), hom a b noncomputable definition src1 {A B : Type} (x : arrow_ob A B) : A := match x with (sigma.mk a (sigma.mk b h)) := a end noncomputable definition src2 {A B : Type} : arrow_ob A B → A | (sigma.mk a (sigma.mk b c)) := a noncomputable definition src3 {A B : Type} (x : arrow_ob A B) : A := match x with (sigma.mk a (sigma.mk b c)) := a end example (A B : Type) (x : arrow_ob A B) : src1 x = src2 x := rfl example (A B : Type) (x : arrow_ob A B) : src1 x = src3 x := rfl example (A B : Type) (x : arrow_ob A B) : src2 x = src3 x := rfl
cad2e99a553d420cea31c421aa926ebd3ab5a1aa
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/funParen.lean
75397f4b2a1b15023c4caed3182cc5de7eb33505
[ "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
129
lean
#check fun (α) [Repr α] => repr (α := α) #check fun (x y) => x -- conservatively interpret as pattern #check fun (x id) => x
36b455ff03ccb7347abac4cf6d73fc369853feba
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/sec_notation.lean
8e037eaac327c94b45b0539204947160c84731a3
[ "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
197
lean
open nat section parameter (A : Type) definition f (a b : A) : A := a definition add2 (a : nat) : nat := a + 2 postfix `+.2`:100 := add2 #reduce 3 +.2 end example : 3 +.2 = 5 := rfl
153f0bcab9da13f89f71da067d05f4b811998110
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/library/data/encodable.lean
319fba650c8497b249d3b19aab4c0ba656207455
[ "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
13,698
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura Type class for encodable types. Note that every encodable type is countable. -/ import data.fintype data.list data.list.sort data.sum data.nat.div data.countable data.equiv import data.finset open option list nat function algebra structure encodable [class] (A : Type) := (encode : A → nat) (decode : nat → option A) (encodek : ∀ a, decode (encode a) = some a) open encodable definition countable_of_encodable {A : Type} : encodable A → countable A := assume e : encodable A, have injective encode, from λ (a₁ a₂ : A) (h : encode a₁ = encode a₂), assert decode A (encode a₁) = decode A (encode a₂), by rewrite h, by rewrite [*encodek at this]; injection this; assumption, exists.intro encode this definition encodable_fintype [instance] {A : Type} [h₁ : fintype A] [h₂ : decidable_eq A] : encodable A := encodable.mk (λ a, find a (elements_of A)) (λ n, nth (elements_of A) n) (λ a, find_nth (fintype.complete a)) definition encodable_nat [instance] : encodable nat := encodable.mk (λ a, a) (λ n, some n) (λ a, rfl) definition encodable_option [instance] {A : Type} [h : encodable A] : encodable (option A) := encodable.mk (λ o, match o with | some a := succ (encode a) | none := 0 end) (λ n, if n = 0 then some none else some (decode A (pred n))) (λ o, begin cases o with a, begin esimp end, begin esimp, rewrite [if_neg !succ_ne_zero, encodable.encodek] end end) section sum variables {A B : Type} variables [h₁ : encodable A] [h₂ : encodable B] include h₁ h₂ private definition encode_sum : sum A B → nat | (sum.inl a) := 2 * encode a | (sum.inr b) := 2 * encode b + 1 private definition decode_sum (n : nat) : option (sum A B) := if n % 2 = 0 then match decode A (n / 2) with | some a := some (sum.inl a) | none := none end else match decode B ((n - 1) / 2) with | some b := some (sum.inr b) | none := none end open decidable private theorem decode_encode_sum : ∀ s : sum A B, decode_sum (encode_sum s) = some s | (sum.inl a) := assert aux : 2 > (0:nat), from dec_trivial, begin esimp [encode_sum, decode_sum], rewrite [mul_mod_right, if_pos (eq.refl (0 : nat)), nat.mul_div_cancel_left _ aux, encodable.encodek] end | (sum.inr b) := assert aux₁ : 2 > (0:nat), from dec_trivial, assert aux₂ : 1 % 2 = (1:nat), by rewrite [nat.mod_def], assert aux₃ : 1 ≠ (0:nat), from dec_trivial, begin esimp [encode_sum, decode_sum], rewrite [add.comm, add_mul_mod_self_left, aux₂, if_neg aux₃, nat.add_sub_cancel_left, nat.mul_div_cancel_left _ aux₁, encodable.encodek] end definition encodable_sum [instance] : encodable (sum A B) := encodable.mk (λ s, encode_sum s) (λ n, decode_sum n) (λ s, decode_encode_sum s) end sum section prod variables {A B : Type} variables [h₁ : encodable A] [h₂ : encodable B] include h₁ h₂ private definition encode_prod : A × B → nat | (a, b) := mkpair (encode a) (encode b) private definition decode_prod (n : nat) : option (A × B) := match unpair n with | (n₁, n₂) := match decode A n₁ with | some a := match decode B n₂ with | some b := some (a, b) | none := none end | none := none end end private theorem decode_encode_prod : ∀ p : A × B, decode_prod (encode_prod p) = some p | (a, b) := begin esimp [encode_prod, decode_prod, prod.cases_on], rewrite [unpair_mkpair], esimp, rewrite [*encodable.encodek] end definition encodable_product [instance] : encodable (A × B) := encodable.mk encode_prod decode_prod decode_encode_prod end prod section list variables {A : Type} variables [h : encodable A] include h private definition encode_list_core : list A → nat | [] := 0 | (a::l) := mkpair (encode a) (encode_list_core l) private theorem encode_list_core_cons (a : A) (l : list A) : encode_list_core (a::l) = mkpair (encode a) (encode_list_core l) := rfl private definition encode_list (l : list A) : nat := mkpair (length l) (encode_list_core l) private definition decode_list_core : nat → nat → option (list A) | 0 v := some [] | (succ n) v := match unpair v with | (v₁, v₂) := match decode A v₁ with | some a := match decode_list_core n v₂ with | some l := some (a::l) | none := none end | none := none end end private theorem decode_list_core_succ (n v : nat) : decode_list_core (succ n) v = match unpair v with | (v₁, v₂) := match decode A v₁ with | some a := match decode_list_core n v₂ with | some l := some (a::l) | none := none end | none := none end end := rfl private definition decode_list (n : nat) : option (list A) := match unpair n with | (l, v) := decode_list_core l v end private theorem decode_encode_list_core : ∀ l : list A, decode_list_core (length l) (encode_list_core l) = some l | [] := rfl | (a::l) := begin rewrite [encode_list_core_cons, length_cons, add_one (length l), decode_list_core_succ], rewrite [unpair_mkpair], esimp [prod.cases_on], rewrite [decode_encode_list_core l], rewrite [encodable.encodek], end private theorem decode_encode_list (l : list A) : decode_list (encode_list l) = some l := begin esimp [encode_list, decode_list], rewrite [unpair_mkpair], esimp [prod.cases_on], apply decode_encode_list_core end definition encodable_list [instance] : encodable (list A) := encodable.mk encode_list decode_list decode_encode_list end list section finset variable {A : Type} variable [encA : encodable A] include encA private definition enle (a b : A) : Prop := encode a ≤ encode b private lemma enle.refl (a : A) : enle a a := !le.refl private lemma enle.trans (a b c : A) : enle a b → enle b c → enle a c := assume h₁ h₂, le.trans h₁ h₂ private lemma enle.total (a b : A) : enle a b ∨ enle b a := !le.total private lemma enle.antisymm (a b : A) : enle a b → enle b a → a = b := assume h₁ h₂, assert encode a = encode b, from le.antisymm h₁ h₂, assert decode A (encode a) = decode A (encode b), by rewrite this, assert some a = some b, by rewrite [*encodek at this]; exact this, option.no_confusion this (λ e, e) private definition decidable_enle [instance] (a b : A) : decidable (enle a b) := decidable_le (encode a) (encode b) variables [decA : decidable_eq A] include decA private definition ensort (l : list A) : list A := sort enle l open subtype perm private lemma sorted_eq_of_perm {l₁ l₂ : list A} (h : l₁ ~ l₂) : ensort l₁ = ensort l₂ := list.sort_eq_of_perm_core enle.total enle.trans enle.refl enle.antisymm h private definition encode_finset (s : finset A) : nat := quot.lift_on s (λ l, encode (ensort (elt_of l))) (λ l₁ l₂ p, have elt_of l₁ ~ elt_of l₂, from p, assert ensort (elt_of l₁) = ensort (elt_of l₂), from sorted_eq_of_perm this, by rewrite this) private definition decode_finset (n : nat) : option (finset A) := match decode (list A) n with | some l₁ := some (finset.to_finset l₁) | none := none end private theorem decode_encode_finset (s : finset A) : decode_finset (encode_finset s) = some s := quot.induction_on s (λ l, begin unfold encode_finset, unfold decode_finset, rewrite encodek, esimp, congruence, apply quot.sound, cases l with l nd, show erase_dup (ensort l) ~ l, from have nodup (ensort l), from nodup_of_perm_of_nodup (perm.symm !sort_perm) nd, calc erase_dup (ensort l) = ensort l : erase_dup_eq_of_nodup this ... ~ l : sort_perm end) definition encodable_finset [instance] : encodable (finset A) := encodable.mk encode_finset decode_finset decode_encode_finset end finset section subtype open subtype decidable variable {A : Type} variable {P : A → Prop} variable [encA : encodable A] variable [decP : decidable_pred P] include encA private definition encode_subtype : {a : A | P a} → nat | (tag v h) := encode v include decP private definition decode_subtype (v : nat) : option {a : A | P a} := match decode A v with | some a := if h : P a then some (tag a h) else none | none := none end private lemma decode_encode_subtype : ∀ s : {a : A | P a}, decode_subtype (encode_subtype s) = some s | (tag v h) := begin unfold [encode_subtype, decode_subtype], rewrite encodek, esimp, rewrite [dif_pos h] end definition encodable_subtype [instance] : encodable {a : A | P a} := encodable.mk encode_subtype decode_subtype decode_encode_subtype end subtype definition encodable_of_left_injection {A B : Type} [h₁ : encodable A] (f : B → A) (finv : A → option B) (linv : ∀ b, finv (f b) = some b) : encodable B := encodable.mk (λ b, encode (f b)) (λ n, match decode A n with | some a := finv a | none := none end) (λ b, begin esimp, rewrite [encodable.encodek], esimp [option.cases_on], rewrite [linv] end) section open equiv definition encodable_of_equiv {A B : Type} [h : encodable A] : A ≃ B → encodable B | (mk f g l r) := encodable_of_left_injection g (λ a, some (f a)) (λ b, by rewrite r; reflexivity) end /- Choice function for encodable types and decidable predicates. We provide the following API choose {A : Type} {p : A → Prop} [c : encodable A] [d : decidable_pred p] : (∃ x, p x) → A := choose_spec {A : Type} {p : A → Prop} [c : encodable A] [d : decidable_pred p] (ex : ∃ x, p x) : p (choose ex) := -/ section find_a parameters {A : Type} {p : A → Prop} [c : encodable A] [d : decidable_pred p] include c include d private definition pn (n : nat) : Prop := match decode A n with | some a := p a | none := false end private definition decidable_pn : decidable_pred pn := λ n, match decode A n with | some a := λ e : decode A n = some a, match d a with | decidable.inl t := begin unfold pn, rewrite e, esimp [option.cases_on], exact (decidable.inl t) end | decidable.inr f := begin unfold pn, rewrite e, esimp [option.cases_on], exact (decidable.inr f) end end | none := λ e : decode A n = none, begin unfold pn, rewrite e, esimp [option.cases_on], exact decidable_false end end (eq.refl (decode A n)) private definition ex_pn_of_ex : (∃ x, p x) → (∃ x, pn x) := assume ex, obtain (w : A) (pw : p w), from ex, exists.intro (encode w) begin unfold pn, rewrite [encodek], esimp, exact pw end private lemma decode_ne_none_of_pn {n : nat} : pn n → decode A n ≠ none := assume pnn e, begin rewrite [▸ (match decode A n with | some a := p a | none := false end) at pnn], rewrite [e at pnn], esimp [option.cases_on] at pnn, exact (false.elim pnn) end open subtype private definition of_nat (n : nat) : pn n → { a : A | p a } := match decode A n with | some a := λ (e : decode A n = some a), begin unfold pn, rewrite e, esimp [option.cases_on], intro pa, exact (tag a pa) end | none := λ (e : decode A n = none) h, absurd e (decode_ne_none_of_pn h) end (eq.refl (decode A n)) private definition find_a : (∃ x, p x) → {a : A | p a} := suppose ∃ x, p x, have ∃ x, pn x, from ex_pn_of_ex this, let r := @nat.find _ decidable_pn this in have pn r, from @nat.find_spec pn decidable_pn this, of_nat r this end find_a namespace encodable open subtype definition choose {A : Type} {p : A → Prop} [c : encodable A] [d : decidable_pred p] : (∃ x, p x) → A := assume ex, elt_of (find_a ex) theorem choose_spec {A : Type} {p : A → Prop} [c : encodable A] [d : decidable_pred p] (ex : ∃ x, p x) : p (choose ex) := has_property (find_a ex) theorem axiom_of_choice {A : Type} {B : A → Type} {R : Π x, B x → Prop} [c : Π a, encodable (B a)] [d : ∀ x y, decidable (R x y)] : (∀x, ∃y, R x y) → ∃f, ∀x, R x (f x) := assume H, have ∀x, R x (choose (H x)), from take x, choose_spec (H x), exists.intro _ this theorem skolem {A : Type} {B : A → Type} {P : Π x, B x → Prop} [c : Π a, encodable (B a)] [d : ∀ x y, decidable (P x y)] : (∀x, ∃y, P x y) ↔ ∃f, (∀x, P x (f x)) := iff.intro (suppose (∀ x, ∃y, P x y), axiom_of_choice this) (suppose (∃ f, (∀x, P x (f x))), take x, obtain (fw : ∀x, B x) (Hw : ∀x, P x (fw x)), from this, exists.intro (fw x) (Hw x)) end encodable namespace quot section open setoid encodable parameter {A : Type} parameter {s : setoid A} parameter [decR : ∀ a b : A, decidable (a ≈ b)] parameter [encA : encodable A] include decR include encA -- Choose equivalence class representative definition rep (q : quot s) : A := choose (exists_rep q) theorem rep_spec (q : quot s) : ⟦rep q⟧ = q := choose_spec (exists_rep q) private definition encode_quot (q : quot s) : nat := encode (rep q) private definition decode_quot (n : nat) : option (quot s) := match decode A n with | some a := some ⟦ a ⟧ | none := none end private lemma decode_encode_quot (q : quot s) : decode_quot (encode_quot q) = some q := quot.induction_on q (λ l, begin unfold [encode_quot, decode_quot], rewrite encodek, esimp, rewrite rep_spec end) definition encodable_quot : encodable (quot s) := encodable.mk encode_quot decode_quot decode_encode_quot end end quot attribute quot.encodable_quot [instance]
e121a5f3cb09b0960ee3404a23dca0492b1d28ab
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/ring/regular.lean
e34a13b1a68e8a67b81dcffbb5f38812854a9e00
[ "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
3,374
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Yury Kudryashov, Neil Strickland -/ import algebra.regular.basic import algebra.ring.defs /-! # Lemmas about regular elements in rings. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ variables {α : Type*} /-- Left `mul` by a `k : α` over `[ring α]` is injective, if `k` is not a zero divisor. The typeclass that restricts all terms of `α` to have this property is `no_zero_divisors`. -/ lemma is_left_regular_of_non_zero_divisor [non_unital_non_assoc_ring α] (k : α) (h : ∀ (x : α), k * x = 0 → x = 0) : is_left_regular k := begin refine λ x y (h' : k * x = k * y), sub_eq_zero.mp (h _ _), rw [mul_sub, sub_eq_zero, h'] end /-- Right `mul` by a `k : α` over `[ring α]` is injective, if `k` is not a zero divisor. The typeclass that restricts all terms of `α` to have this property is `no_zero_divisors`. -/ lemma is_right_regular_of_non_zero_divisor [non_unital_non_assoc_ring α] (k : α) (h : ∀ (x : α), x * k = 0 → x = 0) : is_right_regular k := begin refine λ x y (h' : x * k = y * k), sub_eq_zero.mp (h _ _), rw [sub_mul, sub_eq_zero, h'] end lemma is_regular_of_ne_zero' [non_unital_non_assoc_ring α] [no_zero_divisors α] {k : α} (hk : k ≠ 0) : is_regular k := ⟨is_left_regular_of_non_zero_divisor k (λ x h, (no_zero_divisors.eq_zero_or_eq_zero_of_mul_eq_zero h).resolve_left hk), is_right_regular_of_non_zero_divisor k (λ x h, (no_zero_divisors.eq_zero_or_eq_zero_of_mul_eq_zero h).resolve_right hk)⟩ lemma is_regular_iff_ne_zero' [nontrivial α] [non_unital_non_assoc_ring α] [no_zero_divisors α] {k : α} : is_regular k ↔ k ≠ 0 := ⟨λ h, by { rintro rfl, exact not_not.mpr h.left not_is_left_regular_zero }, is_regular_of_ne_zero'⟩ /-- A ring with no zero divisors is a `cancel_monoid_with_zero`. Note this is not an instance as it forms a typeclass loop. -/ @[reducible] def no_zero_divisors.to_cancel_monoid_with_zero [ring α] [no_zero_divisors α] : cancel_monoid_with_zero α := { mul_left_cancel_of_ne_zero := λ a b c ha, @is_regular.left _ _ _ (is_regular_of_ne_zero' ha) _ _, mul_right_cancel_of_ne_zero := λ a b c hb, @is_regular.right _ _ _ (is_regular_of_ne_zero' hb) _ _, .. (by apply_instance : monoid_with_zero α) } /-- A commutative ring with no zero divisors is a `cancel_comm_monoid_with_zero`. Note this is not an instance as it forms a typeclass loop. -/ @[reducible] def no_zero_divisors.to_cancel_comm_monoid_with_zero [comm_ring α] [no_zero_divisors α] : cancel_comm_monoid_with_zero α := { .. no_zero_divisors.to_cancel_monoid_with_zero, .. (by apply_instance : comm_monoid_with_zero α) } section is_domain @[priority 100] -- see Note [lower instance priority] instance is_domain.to_cancel_monoid_with_zero [semiring α] [is_domain α] : cancel_monoid_with_zero α := { .. semiring.to_monoid_with_zero α, .. ‹is_domain α› } variables [comm_semiring α] [is_domain α] @[priority 100] -- see Note [lower instance priority] instance is_domain.to_cancel_comm_monoid_with_zero : cancel_comm_monoid_with_zero α := { .. ‹comm_semiring α›, .. ‹is_domain α› } end is_domain
eeba95a62e05654188d0e8825bdbb0276ffd1258
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/algebraic_geometry/structure_sheaf.lean
90d345beb739957435a1d926dd2ecb86cc0dae5d
[ "Apache-2.0" ]
permissive
JLimperg/aesop3
306cc6570c556568897ed2e508c8869667252e8a
a4a116f650cc7403428e72bd2e2c4cda300fe03f
refs/heads/master
1,682,884,916,368
1,620,320,033,000
1,620,320,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
21,292
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Scott Morrison -/ import algebraic_geometry.prime_spectrum import algebra.category.CommRing.colimits import algebra.category.CommRing.limits import topology.sheaves.local_predicate import topology.sheaves.forget import ring_theory.localization import ring_theory.subring /-! # The structure sheaf on `prime_spectrum R`. We define the structure sheaf on `Top.of (prime_spectrum R)`, for a commutative ring `R`. We define this as a subsheaf of the sheaf of dependent functions into the localizations, cut out by the condition that the function must be locally equal to a ratio of elements of `R`. Because the condition "is equal to a fraction" passes to smaller open subsets, the subset of functions satisfying this condition is automatically a subpresheaf. Because the condition "is locally equal to a fraction" is local, it is also a subsheaf. (It may be helpful to refer back to `topology.sheaves.sheaf_of_functions`, where we show that dependent functions into any type family form a sheaf, and also `topology.sheaves.local_predicate`, where we characterise the predicates which pick out sub-presheaves and sub-sheaves of these sheaves.) We also set up the ring structure, obtaining `structure_sheaf R : sheaf CommRing (Top.of (prime_spectrum R))`. -/ universe u noncomputable theory variables (R : Type u) [comm_ring R] open Top open topological_space open category_theory open opposite namespace algebraic_geometry /-- $Spec R$, just as a topological space. -/ def Spec.Top : Top := Top.of (prime_spectrum R) namespace structure_sheaf /-- The type family over `prime_spectrum R` consisting of the localization over each point. -/ @[derive [comm_ring, local_ring]] def localizations (P : Spec.Top R) : Type u := localization.at_prime P.as_ideal instance (P : Spec.Top R) : inhabited (localizations R P) := ⟨(localization.of _).to_map 1⟩ variables {R} /-- The predicate saying that a dependent function on an open `U` is realised as a fixed fraction `r / s` in each of the stalks (which are localizations at various prime ideals). -/ def is_fraction {U : opens (Spec.Top R)} (f : Π x : U, localizations R x) : Prop := ∃ (r s : R), ∀ x : U, ¬ (s ∈ x.1.as_ideal) ∧ f x * (localization.of _).to_map s = (localization.of _).to_map r variables (R) /-- The predicate `is_fraction` is "prelocal", in the sense that if it holds on `U` it holds on any open subset `V` of `U`. -/ def is_fraction_prelocal : prelocal_predicate (localizations R) := { pred := λ U f, is_fraction f, res := by { rintro V U i f ⟨r, s, w⟩, exact ⟨r, s, λ x, w (i x)⟩ } } /-- We will define the structure sheaf as the subsheaf of all dependent functions in `Π x : U, localizations R x` consisting of those functions which can locally be expressed as a ratio of (the images in the localization of) elements of `R`. Quoting Hartshorne: For an open set $U ⊆ Spec A$, we define $𝒪(U)$ to be the set of functions $s : U → ⨆_{𝔭 ∈ U} A_𝔭$, such that $s(𝔭) ∈ A_𝔭$ for each $𝔭$, and such that $s$ is locally a quotient of elements of $A$: to be precise, we require that for each $𝔭 ∈ U$, there is a neighborhood $V$ of $𝔭$, contained in $U$, and elements $a, f ∈ A$, such that for each $𝔮 ∈ V, f ∉ 𝔮$, and $s(𝔮) = a/f$ in $A_𝔮$. Now Hartshorne had the disadvantage of not knowing about dependent functions, so we replace his circumlocution about functions into a disjoint union with `Π x : U, localizations x`. -/ def is_locally_fraction : local_predicate (localizations R) := (is_fraction_prelocal R).sheafify @[simp] lemma is_locally_fraction_pred {U : opens (Spec.Top R)} (f : Π x : U, localizations R x) : (is_locally_fraction R).pred f = ∀ x : U, ∃ (V) (m : x.1 ∈ V) (i : V ⟶ U), ∃ (r s : R), ∀ y : V, ¬ (s ∈ y.1.as_ideal) ∧ f (i y : U) * (localization.of _).to_map s = (localization.of _).to_map r := rfl /-- The functions satisfying `is_locally_fraction` form a subring. -/ def sections_subring (U : (opens (Spec.Top R))ᵒᵖ) : subring (Π x : unop U, localizations R x) := { carrier := { f | (is_locally_fraction R).pred f }, zero_mem' := begin refine λ x, ⟨unop U, x.2, 𝟙 _, 0, 1, λ y, ⟨_, _⟩⟩, { rw ←ideal.ne_top_iff_one, exact y.1.is_prime.1, }, { simp, }, end, one_mem' := begin refine λ x, ⟨unop U, x.2, 𝟙 _, 1, 1, λ y, ⟨_, _⟩⟩, { rw ←ideal.ne_top_iff_one, exact y.1.is_prime.1, }, { simp, }, end, add_mem' := begin intros a b ha hb x, rcases ha x with ⟨Va, ma, ia, ra, sa, wa⟩, rcases hb x with ⟨Vb, mb, ib, rb, sb, wb⟩, refine ⟨Va ⊓ Vb, ⟨ma, mb⟩, opens.inf_le_left _ _ ≫ ia, ra * sb + rb * sa, sa * sb, _⟩, intro y, rcases wa (opens.inf_le_left _ _ y) with ⟨nma, wa⟩, rcases wb (opens.inf_le_right _ _ y) with ⟨nmb, wb⟩, fsplit, { intro H, cases y.1.is_prime.mem_or_mem H; contradiction, }, { simp only [add_mul, ring_hom.map_add, pi.add_apply, ring_hom.map_mul], erw [←wa, ←wb], simp only [mul_assoc], congr' 2, rw [mul_comm], refl, } end, neg_mem' := begin intros a ha x, rcases ha x with ⟨V, m, i, r, s, w⟩, refine ⟨V, m, i, -r, s, _⟩, intro y, rcases w y with ⟨nm, w⟩, fsplit, { exact nm, }, { simp only [ring_hom.map_neg, pi.neg_apply], erw [←w], simp only [neg_mul_eq_neg_mul_symm], } end, mul_mem' := begin intros a b ha hb x, rcases ha x with ⟨Va, ma, ia, ra, sa, wa⟩, rcases hb x with ⟨Vb, mb, ib, rb, sb, wb⟩, refine ⟨Va ⊓ Vb, ⟨ma, mb⟩, opens.inf_le_left _ _ ≫ ia, ra * rb, sa * sb, _⟩, intro y, rcases wa (opens.inf_le_left _ _ y) with ⟨nma, wa⟩, rcases wb (opens.inf_le_right _ _ y) with ⟨nmb, wb⟩, fsplit, { intro H, cases y.1.is_prime.mem_or_mem H; contradiction, }, { simp only [pi.mul_apply, ring_hom.map_mul], erw [←wa, ←wb], simp only [mul_left_comm, mul_assoc, mul_comm], refl, } end, } end structure_sheaf open structure_sheaf /-- The structure sheaf (valued in `Type`, not yet `CommRing`) is the subsheaf consisting of functions satisfying `is_locally_fraction`. -/ def structure_sheaf_in_Type : sheaf (Type u) (Spec.Top R):= subsheaf_to_Types (is_locally_fraction R) instance comm_ring_structure_sheaf_in_Type_obj (U : (opens (Spec.Top R))ᵒᵖ) : comm_ring ((structure_sheaf_in_Type R).presheaf.obj U) := (sections_subring R U).to_comm_ring open prime_spectrum /-- The structure presheaf, valued in `CommRing`, constructed by dressing up the `Type` valued structure presheaf. -/ @[simps] def structure_presheaf_in_CommRing : presheaf CommRing (Spec.Top R) := { obj := λ U, CommRing.of ((structure_sheaf_in_Type R).presheaf.obj U), map := λ U V i, { to_fun := ((structure_sheaf_in_Type R).presheaf.map i), map_zero' := rfl, map_add' := λ x y, rfl, map_one' := rfl, map_mul' := λ x y, rfl, }, } /-- Some glue, verifying that that structure presheaf valued in `CommRing` agrees with the `Type` valued structure presheaf. -/ def structure_presheaf_comp_forget : structure_presheaf_in_CommRing R ⋙ (forget CommRing) ≅ (structure_sheaf_in_Type R).presheaf := nat_iso.of_components (λ U, iso.refl _) (by tidy) open Top.presheaf /-- The structure sheaf on $Spec R$, valued in `CommRing`. This is provided as a bundled `SheafedSpace` as `Spec.SheafedSpace R` later. -/ def structure_sheaf : sheaf CommRing (Spec.Top R) := { presheaf := structure_presheaf_in_CommRing R, sheaf_condition := -- We check the sheaf condition under `forget CommRing`. (sheaf_condition_equiv_sheaf_condition_comp _ _).symm (sheaf_condition_equiv_of_iso (structure_presheaf_comp_forget R).symm (structure_sheaf_in_Type R).sheaf_condition), } @[simp] lemma res_apply (U V : opens (Spec.Top R)) (i : V ⟶ U) (s : (structure_sheaf R).presheaf.obj (op U)) (x : V) : ((structure_sheaf R).presheaf.map i.op s).1 x = (s.1 (i x) : _) := rfl /- Notation in this comment X = Spec R OX = structure sheaf In the following we construct an isomorphism between OX_p and R_p given any point p corresponding to a prime ideal in R. We do this via 8 steps: 1. def const (f g : R) (V) (hv : V ≤ D_g) : OX(V) [for api] 2. def to_open (U) : R ⟶ OX(U) 3. [2] def to_stalk (p : Spec R) : R ⟶ OX_p 4. [2] def to_basic_open (f : R) : R_f ⟶ OX(D_f) 5. [3] def localization_to_stalk (p : Spec R) : R_p ⟶ OX_p 6. def open_to_localization (U) (p) (hp : p ∈ U) : OX(U) ⟶ R_p 7. [6] def stalk_to_fiber_ring_hom (p : Spec R) : OX_p ⟶ R_p 8. [5,7] def stalk_iso (p : Spec R) : OX_p ≅ R_p In the square brackets we list the dependencies of a construction on the previous steps. -/ /-- The section of `structure_sheaf R` on an open `U` sending each `x ∈ U` to the element `f/g` in the localization of `R` at `x`. -/ def const (f g : R) (U : opens (Spec.Top R)) (hu : ∀ x ∈ U, g ∈ (x : Spec.Top R).as_ideal.prime_compl) : (structure_sheaf R).presheaf.obj (op U) := ⟨λ x, (localization.of _).mk' f ⟨g, hu x x.2⟩, λ x, ⟨U, x.2, 𝟙 _, f, g, λ y, ⟨hu y y.2, localization_map.mk'_spec _ _ _⟩⟩⟩ @[simp] lemma const_apply (f g : R) (U : opens (Spec.Top R)) (hu : ∀ x ∈ U, g ∈ (x : Spec.Top R).as_ideal.prime_compl) (x : U) : (const R f g U hu).1 x = (localization.of _).mk' f ⟨g, hu x x.2⟩ := rfl lemma const_apply' (f g : R) (U : opens (Spec.Top R)) (hu : ∀ x ∈ U, g ∈ (x : Spec.Top R).as_ideal.prime_compl) (x : U) (hx : g ∈ (as_ideal x.1).prime_compl) : (const R f g U hu).1 x = (localization.of _).mk' f ⟨g, hx⟩ := rfl lemma exists_const (U) (s : (structure_sheaf R).presheaf.obj (op U)) (x : Spec.Top R) (hx : x ∈ U) : ∃ (V : opens (Spec.Top R)) (hxV : x ∈ V) (i : V ⟶ U) (f g : R) hg, const R f g V hg = (structure_sheaf R).presheaf.map i.op s := let ⟨V, hxV, iVU, f, g, hfg⟩ := s.2 ⟨x, hx⟩ in ⟨V, hxV, iVU, f, g, λ y hyV, (hfg ⟨y, hyV⟩).1, subtype.eq $ funext $ λ y, (localization.of _).mk'_eq_iff_eq_mul.2 $ eq.symm $ (hfg y).2⟩ @[simp] lemma res_const (f g : R) (U hu V hv i) : (structure_sheaf R).presheaf.map i (const R f g U hu) = const R f g V hv := rfl lemma res_const' (f g : R) (V hv) : (structure_sheaf R).presheaf.map (hom_of_le hv).op (const R f g (basic_open g) (λ _, id)) = const R f g V hv := rfl lemma const_zero (f : R) (U hu) : const R 0 f U hu = 0 := subtype.eq $ funext $ λ x, (localization.of _).mk'_eq_iff_eq_mul.2 $ by erw [ring_hom.map_zero, subtype.val_eq_coe, subring.coe_zero, pi.zero_apply, zero_mul] lemma const_self (f : R) (U hu) : const R f f U hu = 1 := subtype.eq $ funext $ λ x, localization_map.mk'_self _ _ lemma const_one (U) : const R 1 1 U (λ p _, submonoid.one_mem _) = 1 := const_self R 1 U _ lemma const_add (f₁ f₂ g₁ g₂ : R) (U hu₁ hu₂) : const R f₁ g₁ U hu₁ + const R f₂ g₂ U hu₂ = const R (f₁ * g₂ + f₂ * g₁) (g₁ * g₂) U (λ x hx, submonoid.mul_mem _ (hu₁ x hx) (hu₂ x hx)) := subtype.eq $ funext $ λ x, eq.symm $ by convert (localization.of _).mk'_add f₁ f₂ ⟨g₁, hu₁ x x.2⟩ ⟨g₂, hu₂ x x.2⟩ lemma const_mul (f₁ f₂ g₁ g₂ : R) (U hu₁ hu₂) : const R f₁ g₁ U hu₁ * const R f₂ g₂ U hu₂ = const R (f₁ * f₂) (g₁ * g₂) U (λ x hx, submonoid.mul_mem _ (hu₁ x hx) (hu₂ x hx)) := subtype.eq $ funext $ λ x, eq.symm $ by convert (localization.of _).mk'_mul f₁ f₂ ⟨g₁, hu₁ x x.2⟩ ⟨g₂, hu₂ x x.2⟩ lemma const_ext {f₁ f₂ g₁ g₂ : R} {U hu₁ hu₂} (h : f₁ * g₂ = f₂ * g₁) : const R f₁ g₁ U hu₁ = const R f₂ g₂ U hu₂ := subtype.eq $ funext $ λ x, (localization.of _).mk'_eq_of_eq h.symm lemma const_congr {f₁ f₂ g₁ g₂ : R} {U hu} (hf : f₁ = f₂) (hg : g₁ = g₂) : const R f₁ g₁ U hu = const R f₂ g₂ U (hg ▸ hu) := by substs hf hg lemma const_mul_rev (f g : R) (U hu₁ hu₂) : const R f g U hu₁ * const R g f U hu₂ = 1 := by rw [const_mul, const_congr R rfl (mul_comm g f), const_self] lemma const_mul_cancel (f g₁ g₂ : R) (U hu₁ hu₂) : const R f g₁ U hu₁ * const R g₁ g₂ U hu₂ = const R f g₂ U hu₂ := by { rw [const_mul, const_ext], rw mul_assoc } lemma const_mul_cancel' (f g₁ g₂ : R) (U hu₁ hu₂) : const R g₁ g₂ U hu₂ * const R f g₁ U hu₁ = const R f g₂ U hu₂ := by rw [mul_comm, const_mul_cancel] /-- The canonical ring homomorphism interpreting an element of `R` as a section of the structure sheaf. -/ def to_open (U : opens (Spec.Top R)) : CommRing.of R ⟶ (structure_sheaf R).presheaf.obj (op U) := { to_fun := λ f, ⟨λ x, (localization.of _).to_map f, λ x, ⟨U, x.2, 𝟙 _, f, 1, λ y, ⟨(ideal.ne_top_iff_one _).1 y.1.2.1, by { rw [ring_hom.map_one, mul_one], refl } ⟩⟩⟩, map_one' := subtype.eq $ funext $ λ x, ring_hom.map_one _, map_mul' := λ f g, subtype.eq $ funext $ λ x, ring_hom.map_mul _ _ _, map_zero' := subtype.eq $ funext $ λ x, ring_hom.map_zero _, map_add' := λ f g, subtype.eq $ funext $ λ x, ring_hom.map_add _ _ _ } @[simp] lemma to_open_res (U V : opens (Spec.Top R)) (i : V ⟶ U) : to_open R U ≫ (structure_sheaf R).presheaf.map i.op = to_open R V := rfl @[simp] lemma to_open_apply (U : opens (Spec.Top R)) (f : R) (x : U) : (to_open R U f).1 x = (localization.of _).to_map f := rfl lemma to_open_eq_const (U : opens (Spec.Top R)) (f : R) : to_open R U f = const R f 1 U (λ x _, (ideal.ne_top_iff_one _).1 x.2.1) := subtype.eq $ funext $ λ x, eq.symm $ (localization.of _).mk'_one f /-- The canonical ring homomorphism interpreting an element of `R` as an element of the stalk of `structure_sheaf R` at `x`. -/ def to_stalk (x : Spec.Top R) : CommRing.of R ⟶ (structure_sheaf R).presheaf.stalk x := (to_open R ⊤ ≫ (structure_sheaf R).presheaf.germ ⟨x, ⟨⟩⟩ : _) @[simp] lemma to_open_germ (U : opens (Spec.Top R)) (x : U) : to_open R U ≫ (structure_sheaf R).presheaf.germ x = to_stalk R x := by { rw [← to_open_res R ⊤ U (hom_of_le le_top : U ⟶ ⊤), category.assoc, presheaf.germ_res], refl } @[simp] lemma germ_to_open (U : opens (Spec.Top R)) (x : U) (f : R) : (structure_sheaf R).presheaf.germ x (to_open R U f) = to_stalk R x f := by { rw ← to_open_germ, refl } lemma germ_to_top (x : Spec.Top R) (f : R) : (structure_sheaf R).presheaf.germ (⟨x, trivial⟩ : (⊤ : opens (Spec.Top R))) (to_open R ⊤ f) = to_stalk R x f := rfl lemma is_unit_to_basic_open_self (f : R) : is_unit (to_open R (basic_open f) f) := is_unit_of_mul_eq_one _ (const R 1 f (basic_open f) (λ _, id)) $ by rw [to_open_eq_const, const_mul_rev] /-- The canonical ring homomorphism interpreting `s ∈ R_f` as a section of the structure sheaf on the basic open defined by `f ∈ R`. -/ def to_basic_open (f : R) : CommRing.of (localization (submonoid.powers f)) ⟶ (structure_sheaf R).presheaf.obj (op $ basic_open f) := localization_map.away_map.lift f (localization.away.of f) (is_unit_to_basic_open_self R f) @[simp] lemma to_basic_open_mk' (s f : R) (g : submonoid.powers s) : to_basic_open R s ((localization.of _).mk' f g) = const R f g (basic_open s) (λ x hx, submonoid.powers_subset hx g.2) := ((localization.of _).lift_mk'_spec _ _ _ _).2 $ by rw [to_open_eq_const, to_open_eq_const, const_mul_cancel'] @[simp] lemma localization_to_basic_open (f : R) : @category_theory.category_struct.comp _ _ (CommRing.of R) (CommRing.of (localization (submonoid.powers f))) _ (localization.of $ submonoid.powers f).to_map (to_basic_open R f) = to_open R (basic_open f) := ring_hom.ext $ λ g, (localization.of _).lift_eq _ _ @[simp] lemma to_basic_open_to_map (s f : R) : to_basic_open R s ((localization.of _).to_map f) = const R f 1 (basic_open s) (λ _ _, submonoid.one_mem _) := ((localization.of _).lift_eq _ _).trans $ to_open_eq_const _ _ _ lemma is_unit_to_stalk (x : Spec.Top R) (f : x.as_ideal.prime_compl) : is_unit (to_stalk R x (f : R)) := by { erw ← germ_to_open R (basic_open (f : R)) ⟨x, f.2⟩ (f : R), exact ring_hom.is_unit_map _ (is_unit_to_basic_open_self R f) } /-- The canonical ring homomorphism from the localization of `R` at `p` to the stalk of the structure sheaf at the point `p`. -/ def localization_to_stalk (x : Spec.Top R) : CommRing.of (localization.at_prime x.as_ideal) ⟶ (structure_sheaf R).presheaf.stalk x := (localization.of _).lift (is_unit_to_stalk R x) @[simp] lemma localization_to_stalk_of (x : Spec.Top R) (f : R) : localization_to_stalk R x ((localization.of _).to_map f) = to_stalk R x f := (localization.of _).lift_eq _ f @[simp] lemma localization_to_stalk_mk' (x : Spec.Top R) (f : R) (s : (as_ideal x).prime_compl) : localization_to_stalk R x ((localization.of _).mk' f s) = (structure_sheaf R).presheaf.germ (⟨x, s.2⟩ : basic_open (s : R)) (const R f s (basic_open s) (λ _, id)) := ((localization.of _).lift_mk'_spec _ _ _ _).2 $ by erw [← germ_to_open R (basic_open s) ⟨x, s.2⟩, ← germ_to_open R (basic_open s) ⟨x, s.2⟩, ← ring_hom.map_mul, to_open_eq_const, to_open_eq_const, const_mul_cancel'] /-- The ring homomorphism that takes a section of the structure sheaf of `R` on the open set `U`, implemented as a subtype of dependent functions to localizations at prime ideals, and evaluates the section on the point corresponding to a given prime ideal. -/ def open_to_localization (U : opens (Spec.Top R)) (x : Spec.Top R) (hx : x ∈ U) : (structure_sheaf R).presheaf.obj (op U) ⟶ CommRing.of (localization.at_prime x.as_ideal) := { to_fun := λ s, (s.1 ⟨x, hx⟩ : _), map_one' := rfl, map_mul' := λ _ _, rfl, map_zero' := rfl, map_add' := λ _ _, rfl } @[simp] lemma coe_open_to_localization (U : opens (Spec.Top R)) (x : Spec.Top R) (hx : x ∈ U) : (open_to_localization R U x hx : (structure_sheaf R).presheaf.obj (op U) → localization.at_prime x.as_ideal) = (λ s, (s.1 ⟨x, hx⟩ : _)) := rfl lemma open_to_localization_apply (U : opens (Spec.Top R)) (x : Spec.Top R) (hx : x ∈ U) (s : (structure_sheaf R).presheaf.obj (op U)) : open_to_localization R U x hx s = (s.1 ⟨x, hx⟩ : _) := rfl /-- The ring homomorphism from the stalk of the structure sheaf of `R` at a point corresponding to a prime ideal `p` to the localization of `R` at `p`, formed by gluing the `open_to_localization` maps. -/ def stalk_to_fiber_ring_hom (x : Spec.Top R) : (structure_sheaf R).presheaf.stalk x ⟶ CommRing.of (localization.at_prime x.as_ideal) := limits.colimit.desc (((open_nhds.inclusion x).op) ⋙ (structure_sheaf R).presheaf) { X := _, ι := { app := λ U, open_to_localization R ((open_nhds.inclusion _).obj (unop U)) x (unop U).2, } } @[simp] lemma germ_comp_stalk_to_fiber_ring_hom (U : opens (Spec.Top R)) (x : U) : (structure_sheaf R).presheaf.germ x ≫ stalk_to_fiber_ring_hom R x = open_to_localization R U x x.2 := limits.colimit.ι_desc _ _ @[simp] lemma stalk_to_fiber_ring_hom_germ' (U : opens (Spec.Top R)) (x : Spec.Top R) (hx : x ∈ U) (s : (structure_sheaf R).presheaf.obj (op U)) : stalk_to_fiber_ring_hom R x ((structure_sheaf R).presheaf.germ ⟨x, hx⟩ s) = (s.1 ⟨x, hx⟩ : _) := ring_hom.ext_iff.1 (germ_comp_stalk_to_fiber_ring_hom R U ⟨x, hx⟩ : _) s @[simp] lemma stalk_to_fiber_ring_hom_germ (U : opens (Spec.Top R)) (x : U) (s : (structure_sheaf R).presheaf.obj (op U)) : stalk_to_fiber_ring_hom R x ((structure_sheaf R).presheaf.germ x s) = s.1 x := by { cases x, exact stalk_to_fiber_ring_hom_germ' R U _ _ _ } @[simp] lemma to_stalk_comp_stalk_to_fiber_ring_hom (x : Spec.Top R) : to_stalk R x ≫ stalk_to_fiber_ring_hom R x = (localization.of _).to_map := by { erw [to_stalk, category.assoc, germ_comp_stalk_to_fiber_ring_hom], refl } @[simp] lemma stalk_to_fiber_ring_hom_to_stalk (x : Spec.Top R) (f : R) : stalk_to_fiber_ring_hom R x (to_stalk R x f) = (localization.of _).to_map f := ring_hom.ext_iff.1 (to_stalk_comp_stalk_to_fiber_ring_hom R x) _ /-- The ring isomorphism between the stalk of the structure sheaf of `R` at a point `p` corresponding to a prime ideal in `R` and the localization of `R` at `p`. -/ def stalk_iso (x : Spec.Top R) : (structure_sheaf R).presheaf.stalk x ≅ CommRing.of (localization.at_prime x.as_ideal) := { hom := stalk_to_fiber_ring_hom R x, inv := localization_to_stalk R x, hom_inv_id' := (structure_sheaf R).presheaf.stalk_hom_ext $ λ U hxU, begin ext s, simp only [coe_comp], rw [coe_id, stalk_to_fiber_ring_hom_germ'], obtain ⟨V, hxV, iVU, f, g, hg, hs⟩ := exists_const _ _ s x hxU, erw [← res_apply R U V iVU s ⟨x, hxV⟩, ← hs, const_apply, localization_to_stalk_mk'], refine (structure_sheaf R).presheaf.germ_ext V hxV (hom_of_le hg) iVU _, erw [← hs, res_const'] end, inv_hom_id' := (localization.of x.as_ideal.prime_compl).epic_of_localization_map $ λ f, by simp only [ring_hom.comp_apply, coe_comp, coe_id, localization_to_stalk_of, stalk_to_fiber_ring_hom_to_stalk] } end algebraic_geometry
5a10e86ea537ae84f4bab58641fb06306b44e3c0
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/coe4.lean
f1b2b2f063867b1b185e68cb4bd5856aa6fe8e17
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
837
lean
import logic namespace setoid inductive setoid : Type := mk_setoid: Π (A : Type'), (A → A → Prop) → setoid set_option pp.universes true check setoid definition test : Type.{2} := setoid.{0} definition carrier (s : setoid) := setoid.rec (λ a eq, a) s definition eqv {s : setoid} : carrier s → carrier s → Prop := setoid.rec (λ a eqv, eqv) s infix `≈` := eqv attribute carrier [coercion] inductive morphism (s1 s2 : setoid) : Type := mk : Π (f : s1 → s2), (∀ x y, x ≈ y → f x ≈ f y) → morphism s1 s2 check morphism.mk check λ (s1 s2 : setoid), s1 check λ (s1 s2 : Type), s1 inductive morphism2 (s1 : setoid) (s2 : setoid) : Type := mk : Π (f : s1 → s2), (∀ x y, x ≈ y → f x ≈ f y) → morphism2 s1 s2 check morphism2 check morphism2.mk end setoid
eb6edfd3aa968b0b3214370e30ccf44e80af44b9
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/list/fin_range.lean
cf9423b635b5f3bdb07127a45b2310b71cb8d661
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
2,999
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kenny Lau, Scott Morrison -/ import data.list.of_fn import data.list.perm /-! # Lists of elements of `fin n` > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file develops some results on `fin_range n`. -/ universe u namespace list variables {α : Type u} @[simp] lemma map_coe_fin_range (n : ℕ) : (fin_range n).map coe = list.range n := begin simp_rw [fin_range, map_pmap, fin.coe_mk, pmap_eq_map], exact list.map_id _ end lemma fin_range_succ_eq_map (n : ℕ) : fin_range n.succ = 0 :: (fin_range n).map fin.succ := begin apply map_injective_iff.mpr fin.coe_injective, rw [map_cons, map_coe_fin_range, range_succ_eq_map, fin.coe_zero, ←map_coe_fin_range, map_map, map_map, function.comp, function.comp], congr' 2 with x, exact (fin.coe_succ _).symm, end @[simp] lemma map_nth_le (l : list α) : (fin_range l.length).map (λ n, l.nth_le n n.2) = l := ext_le (by rw [length_map, length_fin_range]) $ λ n _ h, by { rw ← nth_le_map_rev, congr, { rw nth_le_fin_range, refl }, { rw length_fin_range, exact h } } theorem of_fn_eq_pmap {α n} {f : fin n → α} : of_fn f = pmap (λ i hi, f ⟨i, hi⟩) (range n) (λ _, mem_range.1) := by rw [pmap_eq_map_attach]; from ext_le (by simp) (λ i hi1 hi2, by { simp at hi1, simp [nth_le_of_fn f ⟨i, hi1⟩, -subtype.val_eq_coe] }) theorem of_fn_id (n) : of_fn id = fin_range n := of_fn_eq_pmap theorem of_fn_eq_map {α n} {f : fin n → α} : of_fn f = (fin_range n).map f := by rw [← of_fn_id, map_of_fn, function.right_id] theorem nodup_of_fn_of_injective {α n} {f : fin n → α} (hf : function.injective f) : nodup (of_fn f) := by { rw of_fn_eq_pmap, exact (nodup_range n).pmap (λ _ _ _ _ H, fin.veq_of_eq $ hf H) } theorem nodup_of_fn {α n} {f : fin n → α} : nodup (of_fn f) ↔ function.injective f := begin refine ⟨_, nodup_of_fn_of_injective⟩, refine fin.cons_induction _ (λ n x₀ xs ih, _) f, { intro h, exact function.injective_of_subsingleton _ }, { intro h, rw fin.cons_injective_iff, simp_rw [of_fn_succ, fin.cons_succ, nodup_cons, fin.cons_zero, mem_of_fn] at h, exact h.imp_right ih } end end list open list lemma equiv.perm.map_fin_range_perm {n : ℕ} (σ : equiv.perm (fin n)) : map σ (fin_range n) ~ fin_range n := begin rw [perm_ext ((nodup_fin_range n).map σ.injective) $ nodup_fin_range n], simpa only [mem_map, mem_fin_range, true_and, iff_true] using σ.surjective end /-- The list obtained from a permutation of a tuple `f` is permutation equivalent to the list obtained from `f`. -/ lemma equiv.perm.of_fn_comp_perm {n : ℕ} {α : Type u} (σ : equiv.perm (fin n)) (f : fin n → α) : of_fn (f ∘ σ) ~ of_fn f := begin rw [of_fn_eq_map, of_fn_eq_map, ←map_map], exact σ.map_fin_range_perm.map f, end
b742a66245b93a5b11779f667a60cdbd1e3cc050
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/topology/algebra/ring.lean
5d666760ca3a12ec3ab1689d1947b95ca21d2efa
[ "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
7,673
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 Theory of topological rings. -/ import topology.algebra.group import ring_theory.ideal.basic import ring_theory.subring import algebra.ring.prod /-! # Topological (semi)rings A topological (semi)ring is a (semi)ring equipped with a topology such that all operations are continuous. Besides this definition, this file proves that the topological closure of a subring (resp. an ideal) is a subring (resp. an ideal) and defines products and quotients of topological (semi)rings. ## Main Results - `subring.topological_closure`/`subsemiring.topological_closure`: the topological closure of a `subring`/`subsemiring` is itself a `sub(semi)ring`. - `prod.topological_semiring`/`prod.topological_ring`: The product of two topological (semi)rings. - `pi.topological_semiring`/`pi.topological_ring`: The arbitrary product of topological (semi)rings. - `ideal.closure`: The closure of an ideal is an ideal. - `topological_ring_quotient`: The quotient of a topological ring by an ideal is a topological ring. -/ open classical set filter topological_space open_locale classical section topological_ring variables (α : Type*) /-- A topological semiring is a semiring where addition and multiplication are continuous. -/ class topological_semiring [topological_space α] [semiring α] extends has_continuous_add α, has_continuous_mul α : Prop section variables {α} [topological_space α] [semiring α] [topological_semiring α] /-- The (topological-space) closure of a subsemiring of a topological semiring is itself a subsemiring. -/ def subsemiring.topological_closure (s : subsemiring α) : subsemiring α := { carrier := closure (s : set α), ..(s.to_submonoid.topological_closure), ..(s.to_add_submonoid.topological_closure ) } @[simp] lemma subsemiring.topological_closure_coe (s : subsemiring α) : (s.topological_closure : set α) = closure (s : set α) := rfl instance subsemiring.topological_closure_topological_semiring (s : subsemiring α) : topological_semiring (s.topological_closure) := { ..s.to_add_submonoid.topological_closure_has_continuous_add, ..s.to_submonoid.topological_closure_has_continuous_mul } lemma subsemiring.subring_topological_closure (s : subsemiring α) : s ≤ s.topological_closure := subset_closure lemma subsemiring.is_closed_topological_closure (s : subsemiring α) : is_closed (s.topological_closure : set α) := by convert is_closed_closure lemma subsemiring.topological_closure_minimal (s : subsemiring α) {t : subsemiring α} (h : s ≤ t) (ht : is_closed (t : set α)) : s.topological_closure ≤ t := closure_minimal h ht /-- The product topology on the cartesian product of two topological semirings makes the product into a topological semiring. -/ instance {β : Type*} [semiring β] [topological_space β] [topological_semiring β] : topological_semiring (α × β) := {} instance {β : Type*} {C : β → Type*} [∀ b, topological_space (C b)] [Π b, semiring (C b)] [Π b, topological_semiring (C b)] : topological_semiring (Π b, C b) := {} end /-- A topological ring is a ring where the ring operations are continuous. -/ class topological_ring [topological_space α] [ring α] extends topological_add_group α, has_continuous_mul α : Prop variables {α} [ring α] [topological_space α] section variables [t : topological_ring α] @[priority 100] -- see Note [lower instance priority] instance topological_ring.to_topological_semiring : topological_semiring α := {..t} end variables [topological_ring α] /-- The product topology on the cartesian product of two topological rings makes the product into a topological ring. -/ instance {β : Type*} [ring β] [topological_space β] [topological_ring β] : topological_ring (α × β) := { } instance {β : Type*} {C : β → Type*} [Π b, topological_space (C b)] [Π b, ring (C b)] [∀ b, topological_ring (C b)] : topological_ring (Π b, C b) := { continuous_neg := continuous_neg } /-- In a topological ring, the left-multiplication `add_monoid_hom` is continuous. -/ lemma mul_left_continuous (x : α) : continuous (add_monoid_hom.mul_left x) := continuous_const.mul continuous_id /-- In a topological ring, the right-multiplication `add_monoid_hom` is continuous. -/ lemma mul_right_continuous (x : α) : continuous (add_monoid_hom.mul_right x) := continuous_id.mul continuous_const /-- The (topological-space) closure of a subring of a topological semiring is itself a subring. -/ def subring.topological_closure (S : subring α) : subring α := { carrier := closure (S : set α), ..S.to_submonoid.topological_closure, ..S.to_add_subgroup.topological_closure } instance subring.topological_closure_topological_ring (s : subring α) : topological_ring (s.topological_closure) := { ..s.to_add_subgroup.topological_closure_topological_add_group, ..s.to_submonoid.topological_closure_has_continuous_mul } lemma subring.subring_topological_closure (s : subring α) : s ≤ s.topological_closure := subset_closure lemma subring.is_closed_topological_closure (s : subring α) : is_closed (s.topological_closure : set α) := by convert is_closed_closure lemma subring.topological_closure_minimal (s : subring α) {t : subring α} (h : s ≤ t) (ht : is_closed (t : set α)) : s.topological_closure ≤ t := closure_minimal h ht end topological_ring section topological_comm_ring variables {α : Type*} [topological_space α] [comm_ring α] [topological_ring α] /-- The closure of an ideal in a topological ring as an ideal. -/ def ideal.closure (S : ideal α) : ideal α := { carrier := closure S, smul_mem' := λ c x hx, map_mem_closure (mul_left_continuous _) hx $ λ a, S.mul_mem_left c, ..(add_submonoid.topological_closure S.to_add_submonoid) } @[simp] lemma ideal.coe_closure (S : ideal α) : (S.closure : set α) = closure S := rfl end topological_comm_ring section topological_ring variables {α : Type*} [topological_space α] [comm_ring α] (N : ideal α) open ideal.quotient instance topological_ring_quotient_topology : topological_space N.quotient := by dunfold ideal.quotient submodule.quotient; apply_instance -- note for the reader: in the following, `mk` is `ideal.quotient.mk`, the canonical map `R → R/I`. variable [topological_ring α] lemma quotient_ring.is_open_map_coe : is_open_map (mk N) := begin intros s s_op, change is_open (mk N ⁻¹' (mk N '' s)), rw quotient_ring_saturate, exact is_open_Union (λ ⟨n, _⟩, is_open_map_add_left n s s_op) end lemma quotient_ring.quotient_map_coe_coe : quotient_map (λ p : α × α, (mk N p.1, mk N p.2)) := is_open_map.to_quotient_map ((quotient_ring.is_open_map_coe N).prod (quotient_ring.is_open_map_coe N)) ((continuous_quot_mk.comp continuous_fst).prod_mk (continuous_quot_mk.comp continuous_snd)) (by rintro ⟨⟨x⟩, ⟨y⟩⟩; exact ⟨(x, y), rfl⟩) instance topological_ring_quotient : topological_ring N.quotient := { continuous_add := have cont : continuous (mk N ∘ (λ (p : α × α), p.fst + p.snd)) := continuous_quot_mk.comp continuous_add, (quotient_map.continuous_iff (quotient_ring.quotient_map_coe_coe N)).mpr cont, continuous_neg := by convert continuous_quotient_lift _ (continuous_quot_mk.comp continuous_neg); apply_instance, continuous_mul := have cont : continuous (mk N ∘ (λ (p : α × α), p.fst * p.snd)) := continuous_quot_mk.comp continuous_mul, (quotient_map.continuous_iff (quotient_ring.quotient_map_coe_coe N)).mpr cont } end topological_ring
d87a3e2f72e71e6c52237c3b2ba50eb4b5198867
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/test/generalizes.lean
9019e8ccf3bd3fc4fb4185098298af2a9021d2d8
[ "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
3,547
lean
/- Copyright (c) 2020 Jannis Limperg. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jannis Limperg -/ import tactic.generalizes universes u lemma example_from_docs₁ (P : ∀ n, fin n → Prop) (n : ℕ) (f : fin n) (p : ∀ n xs, P n xs) : P (nat.succ n) (fin.succ f) := begin generalizes [n'_eq : nat.succ n = n', f'_eq : fin.succ f == f'], guard_hyp n' := ℕ, guard_hyp n'_eq := n' = nat.succ n, guard_hyp f' := fin n', guard_hyp f'_eq := f' == fin.succ f, exact p n' f' -- Note: `generalizes` fails if we write `n + 1` instead of `nat.succ n` in -- the target because `kabstract` works with a notion of equality that is -- weaker than definitional equality. This is annoying, but we can't do much -- about it short of reimplementing `kabstract`. end lemma example_from_docs₂ (P : ∀ n, fin n → Prop) (n : ℕ) (f : fin n) (p : ∀ n xs, P n xs) : P (nat.succ n) (fin.succ f) := begin generalizes [(nat.succ n = n'), (fin.succ f == f')], guard_hyp n' := ℕ, success_if_fail { guard_hyp n'_eq := n' = nat.succ n }, guard_hyp f' := fin n', success_if_fail { guard_hyp f'_eq := f' == fin.succ f }, exact p n' f' end inductive Vec (α : Sort u) : ℕ → Sort (max 1 u) | nil : Vec 0 | cons {n} (x : α) (xs : Vec n) : Vec (n + 1) namespace Vec inductive eq {α} : ∀ (n m : ℕ), Vec α n → Vec α m → Prop | nil : eq 0 0 nil nil | cons {n m x y xs ys} : x = y → eq n m xs ys → eq (n + 1) (m + 1) (cons x xs) (cons y ys) inductive fancy_unit {α} : ∀ n, Vec α n → Prop | intro (n xs) : fancy_unit n xs -- An example of the difference between multiple calls to `generalize` and -- one call to `generalizes`. lemma test₁ {α n} {x : α} {xs} : fancy_unit (n + 1) (cons x xs) := begin -- Successive `generalize` invocations don't give us the right goal: -- The second generalisation fails due to the dependency between -- `xs' : Vec α (n + 1)` and `n + 1`. success_if_fail { generalize eq_xs' : cons x xs = xs', generalize eq_n' : n + 1 = n', exact fancy_unit.intro n' xs' }, -- `generalizes` gives us the expected result with everything generalised. generalizes [eq_n' : n + 1 = n', eq_xs' : cons x xs = xs'], guard_hyp n' := ℕ, guard_hyp eq_n' := n' = n + 1, guard_hyp xs' := Vec α n', guard_hyp eq_xs' := xs' == cons x xs, exact fancy_unit.intro n' xs' end -- We can also choose to introduce equations for only some of the generalised -- expressions. lemma test₂ {α n} {x : α} {xs} : fancy_unit (n + 1) (cons x xs) := begin generalizes [n + 1 = n', eq_xs' : cons x xs = xs'], guard_hyp n' := ℕ, success_if_fail { guard_hyp eq_n' := n' = n + 1 }, guard_hyp xs' := Vec α n', guard_hyp eq_xs' := xs' == cons x xs, exact fancy_unit.intro n' xs' end -- An example where `generalizes` enables a successful `induction` (though in -- this case, `cases` would suffice and already performs the generalisation). lemma eq_cons_inversion {α} {n m x y} {xs : Vec α n} {ys : Vec α m} : eq (n + 1) (m + 1) (cons x xs) (cons y ys) → eq n m xs ys := begin generalizes [ n'_eq : n + 1 = n' , m'_eq : m + 1 = m' , xs'_eq : cons x xs = xs' , ys'_eq : cons y ys = ys' ], intro h, induction h, case nil { cases n'_eq, }, case cons : n'' m'' x y xs'' ys'' eq_xy eq_xsys'' ih { cases n'_eq, clear n'_eq, cases m'_eq, clear m'_eq, cases xs'_eq, clear xs'_eq, cases ys'_eq, clear ys'_eq, exact eq_xsys'', } end end Vec
024cc6cec2d11be3f89d5e74e3a930c6855c5a64
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/fintype/pi.lean
cee402273dd3e1a82ba3e025e4812bc7c15a5182
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
3,590
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.fintype.basic import data.finset.pi /-! # fintype instances for pi types -/ variables {α : Type*} open finset namespace fintype variables [decidable_eq α] [fintype α] {δ : α → Type*} /-- Given for all `a : α` a finset `t a` of `δ a`, then one can define the finset `fintype.pi_finset t` of all functions taking values in `t a` for all `a`. This is the analogue of `finset.pi` where the base finset is `univ` (but formally they are not the same, as there is an additional condition `i ∈ finset.univ` in the `finset.pi` definition). -/ def pi_finset (t : Π a, finset (δ a)) : finset (Π a, δ a) := (finset.univ.pi t).map ⟨λ f a, f a (mem_univ a), λ _ _, by simp [function.funext_iff]⟩ @[simp] lemma mem_pi_finset {t : Π a, finset (δ a)} {f : Π a, δ a} : f ∈ pi_finset t ↔ ∀ a, f a ∈ t a := begin split, { simp only [pi_finset, mem_map, and_imp, forall_prop_of_true, exists_prop, mem_univ, exists_imp_distrib, mem_pi], rintro g hg hgf a, rw ← hgf, exact hg a }, { simp only [pi_finset, mem_map, forall_prop_of_true, exists_prop, mem_univ, mem_pi], exact λ hf, ⟨λ a ha, f a, hf, rfl⟩ } end @[simp] lemma coe_pi_finset (t : Π a, finset (δ a)) : (pi_finset t : set (Π a, δ a)) = set.pi set.univ (λ a, t a) := set.ext $ λ x, by { rw set.mem_univ_pi, exact fintype.mem_pi_finset } lemma pi_finset_subset (t₁ t₂ : Π a, finset (δ a)) (h : ∀ a, t₁ a ⊆ t₂ a) : pi_finset t₁ ⊆ pi_finset t₂ := λ g hg, mem_pi_finset.2 $ λ a, h a $ mem_pi_finset.1 hg a @[simp] lemma pi_finset_empty [nonempty α] : pi_finset (λ _, ∅ : Π i, finset (δ i)) = ∅ := eq_empty_of_forall_not_mem $ λ _, by simp @[simp] lemma pi_finset_singleton (f : Π i, δ i) : pi_finset (λ i, {f i} : Π i, finset (δ i)) = {f} := ext $ λ _, by simp only [function.funext_iff, fintype.mem_pi_finset, mem_singleton] lemma pi_finset_subsingleton {f : Π i, finset (δ i)} (hf : ∀ i, (f i : set (δ i)).subsingleton) : (fintype.pi_finset f : set (Π i, δ i)).subsingleton := λ a ha b hb, funext $ λ i, hf _ (mem_pi_finset.1 ha _) (mem_pi_finset.1 hb _) lemma pi_finset_disjoint_of_disjoint (t₁ t₂ : Π a, finset (δ a)) {a : α} (h : disjoint (t₁ a) (t₂ a)) : disjoint (pi_finset t₁) (pi_finset t₂) := disjoint_iff_ne.2 $ λ f₁ hf₁ f₂ hf₂ eq₁₂, disjoint_iff_ne.1 h (f₁ a) (mem_pi_finset.1 hf₁ a) (f₂ a) (mem_pi_finset.1 hf₂ a) (congr_fun eq₁₂ a) end fintype /-! ### pi -/ /-- A dependent product of fintypes, indexed by a fintype, is a fintype. -/ instance pi.fintype {α : Type*} {β : α → Type*} [decidable_eq α] [fintype α] [∀ a, fintype (β a)] : fintype (Π a, β a) := ⟨fintype.pi_finset (λ _, univ), by simp⟩ @[simp] lemma fintype.pi_finset_univ {α : Type*} {β : α → Type*} [decidable_eq α] [fintype α] [∀ a, fintype (β a)] : fintype.pi_finset (λ a : α, (finset.univ : finset (β a))) = (finset.univ : finset (Π a, β a)) := rfl instance function.embedding.fintype {α β} [fintype α] [fintype β] [decidable_eq α] [decidable_eq β] : fintype (α ↪ β) := fintype.of_equiv _ (equiv.subtype_injective_equiv_embedding α β) @[simp] lemma finset.univ_pi_univ {α : Type*} {β : α → Type*} [decidable_eq α] [fintype α] [∀ a, fintype (β a)] : finset.univ.pi (λ a : α, (finset.univ : finset (β a))) = finset.univ := by { ext, simp }
78ad783bf547800fea146b204534d200f8149083
9dc8cecdf3c4634764a18254e94d43da07142918
/src/algebra/star/chsh.lean
e6a99191a1fd3026e0044470c9d776dcbe76d4fb
[ "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
10,051
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.star.basic import analysis.special_functions.pow /-! # The Clauser-Horne-Shimony-Holt inequality and Tsirelson's inequality. We establish a version of the Clauser-Horne-Shimony-Holt (CHSH) inequality (which is a generalization of Bell's inequality). This is a foundational result which implies that quantum mechanics is not a local hidden variable theory. As usually stated the CHSH inequality requires substantial language from physics and probability, but it is possible to give a statement that is purely about ordered `*`-algebras. We do that here, to avoid as many practical and logical dependencies as possible. Since the algebra of observables of any quantum system is an ordered `*`-algebra (in particular a von Neumann algebra) this is a strict generalization of the usual statement. Let `R` be a `*`-ring. A CHSH tuple in `R` consists of * four elements `A₀ A₁ B₀ B₁ : R`, such that * each `Aᵢ` and `Bⱼ` is a self-adjoint involution, and * the `Aᵢ` commute with the `Bⱼ`. The physical interpretation is that the four elements are observables (hence self-adjoint) that take values ±1 (hence involutions), and that the `Aᵢ` are spacelike separated from the `Bⱼ` (and hence commute). The CHSH inequality says that when `R` is an ordered `*`-ring (that is, a `*`-ring which is ordered, and for every `r : R`, `0 ≤ star r * r`), which is moreover *commutative*, we have `A₀ * B₀ + A₀ * B₁ + A₁ * B₀ - A₁ * B₁ ≤ 2` On the other hand, Tsirelson's inequality says that for any ordered `*`-ring we have `A₀ * B₀ + A₀ * B₁ + A₁ * B₀ - A₁ * B₁ ≤ 2√2` (A caveat: in the commutative case we need 2⁻¹ in the ring, and in the noncommutative case we need √2 and √2⁻¹. To keep things simple we just assume our rings are ℝ-algebras.) The proofs I've seen in the literature either assume a significant framework for quantum mechanics, or assume the ring is a `C^*`-algebra. In the `C^*`-algebra case, the order structure is completely determined by the `*`-algebra structure: `0 ≤ A` iff there exists some `B` so `A = star B * B`. There's a nice proof of both bounds in this setting at https://en.wikipedia.org/wiki/Tsirelson%27s_bound The proof given here is purely algebraic. ## Future work One can show that Tsirelson's inequality is tight. In the `*`-ring of n-by-n complex matrices, if `A ≤ λ I` for some `λ : ℝ`, then every eigenvalue has absolute value at most `λ`. There is a CHSH tuple in 4-by-4 matrices such that `A₀ * B₀ + A₀ * B₁ + A₁ * B₀ - A₁ * B₁` has `2√2` as an eigenvalue. ## References * [Clauser, Horne, Shimony, Holt, *Proposed experiment to test local hidden-variable theories*][zbMATH06785026] * [Bell, *On the Einstein Podolsky Rosen Paradox*][MR3790629] * [Tsirelson, *Quantum generalizations of Bell's inequality*][MR577178] -/ universes u /-- A CHSH tuple in a *-monoid consists of 4 self-adjoint involutions `A₀ A₁ B₀ B₁` such that the `Aᵢ` commute with the `Bⱼ`. The physical interpretation is that `A₀` and `A₁` are a pair of boolean observables which are spacelike separated from another pair `B₀` and `B₁` of boolean observables. -/ @[nolint has_nonempty_instance] structure is_CHSH_tuple {R} [monoid R] [star_semigroup R] (A₀ A₁ B₀ B₁ : R) := (A₀_inv : A₀^2 = 1) (A₁_inv : A₁^2 = 1) (B₀_inv : B₀^2 = 1) (B₁_inv : B₁^2 = 1) (A₀_sa : star A₀ = A₀) (A₁_sa : star A₁ = A₁) (B₀_sa : star B₀ = B₀) (B₁_sa : star B₁ = B₁) (A₀B₀_commutes : A₀ * B₀ = B₀ * A₀) (A₀B₁_commutes : A₀ * B₁ = B₁ * A₀) (A₁B₀_commutes : A₁ * B₀ = B₀ * A₁) (A₁B₁_commutes : A₁ * B₁ = B₁ * A₁) variables {R : Type u} lemma CHSH_id [comm_ring R] {A₀ A₁ B₀ B₁ : R} (A₀_inv : A₀^2 = 1) (A₁_inv : A₁^2 = 1) (B₀_inv : B₀^2 = 1) (B₁_inv : B₁^2 = 1) : (2 - A₀ * B₀ - A₀ * B₁ - A₁ * B₀ + A₁ * B₁) * (2 - A₀ * B₀ - A₀ * B₁ - A₁ * B₀ + A₁ * B₁) = 4 * (2 - A₀ * B₀ - A₀ * B₁ - A₁ * B₀ + A₁ * B₁) := -- If we had a Gröbner basis algorithm, this would be trivial. -- Without one, it is somewhat tedious! begin rw ← sub_eq_zero, repeat { ring_nf, simp only [A₁_inv, B₁_inv, sub_eq_add_neg, add_mul, mul_add, sub_mul, mul_sub, add_assoc, neg_add, neg_sub, sub_add, sub_sub, neg_mul, ←sq, A₀_inv, B₀_inv, ←sq, ←mul_assoc, one_mul, mul_one, add_right_neg, add_zero, sub_eq_add_neg, A₀_inv, mul_one, add_right_neg, zero_mul] } end /-- Given a CHSH tuple (A₀, A₁, B₀, B₁) in a *commutative* ordered `*`-algebra over ℝ, `A₀ * B₀ + A₀ * B₁ + A₁ * B₀ - A₁ * B₁ ≤ 2`. (We could work over ℤ[⅟2] if we wanted to!) -/ lemma CHSH_inequality_of_comm [ordered_comm_ring R] [star_ordered_ring R] [algebra ℝ R] [ordered_smul ℝ R] (A₀ A₁ B₀ B₁ : R) (T : is_CHSH_tuple A₀ A₁ B₀ B₁) : A₀ * B₀ + A₀ * B₁ + A₁ * B₀ - A₁ * B₁ ≤ 2 := begin let P := (2 - A₀ * B₀ - A₀ * B₁ - A₁ * B₀ + A₁ * B₁), have i₁ : 0 ≤ P, { have idem : P * P = 4 * P := CHSH_id T.A₀_inv T.A₁_inv T.B₀_inv T.B₁_inv, have idem' : P = (1 / 4 : ℝ) • (P * P), { have h : 4 * P = (4 : ℝ) • P := by simp [algebra.smul_def], rw [idem, h, ←mul_smul], norm_num, }, have sa : star P = P, { dsimp [P], simp only [star_add, star_sub, star_mul, star_bit0, star_one, T.A₀_sa, T.A₁_sa, T.B₀_sa, T.B₁_sa, mul_comm B₀, mul_comm B₁], }, rw idem', conv_rhs { congr, skip, congr, rw ←sa, }, convert smul_le_smul_of_nonneg (star_mul_self_nonneg : 0 ≤ star P * P) _, { simp, }, { apply_instance, }, { norm_num, } }, apply le_of_sub_nonneg, simpa only [sub_add_eq_sub_sub, ←sub_add] using i₁, end /-! We now prove some rather specialized lemmas in preparation for the Tsirelson inequality, which we hide in a namespace as they are unlikely to be useful elsewhere. -/ local notation `√2` := (real.sqrt 2 : ℝ) namespace tsirelson_inequality /-! Before proving Tsirelson's bound, we prepare some easy lemmas about √2. -/ -- This calculation, which we need for Tsirelson's bound, -- defeated me. Thanks for the rescue from Shing Tak Lam! lemma tsirelson_inequality_aux : √2 * √2 ^ 3 = √2 * (2 * √2⁻¹ + 4 * (√2⁻¹ * 2⁻¹)) := begin ring_nf, field_simp [(@real.sqrt_pos 2).2 (by norm_num)], convert congr_arg (^2) (@real.sq_sqrt 2 (by norm_num)) using 1; simp only [← pow_mul]; norm_num, end lemma sqrt_two_inv_mul_self : √2⁻¹ * √2⁻¹ = (2⁻¹ : ℝ) := by { rw ←mul_inv, norm_num } end tsirelson_inequality open tsirelson_inequality /-- In a noncommutative ordered `*`-algebra over ℝ, Tsirelson's bound for a CHSH tuple (A₀, A₁, B₀, B₁) is `A₀ * B₀ + A₀ * B₁ + A₁ * B₀ - A₁ * B₁ ≤ 2^(3/2) • 1`. We prove this by providing an explicit sum-of-squares decomposition of the difference. (We could work over `ℤ[2^(1/2), 2^(-1/2)]` if we really wanted to!) -/ lemma tsirelson_inequality [ordered_ring R] [star_ordered_ring R] [algebra ℝ R] [ordered_smul ℝ R] [star_module ℝ R] (A₀ A₁ B₀ B₁ : R) (T : is_CHSH_tuple A₀ A₁ B₀ B₁) : A₀ * B₀ + A₀ * B₁ + A₁ * B₀ - A₁ * B₁ ≤ √2^3 • 1 := begin -- abel will create `ℤ` multiplication. We will `simp` them away to `ℝ` multiplication. have M : ∀ (m : ℤ) (a : ℝ) (x : R), m • a • x = ((m : ℝ) * a) • x := λ m a x, by rw [zsmul_eq_smul_cast ℝ, ← mul_smul], let P := √2⁻¹ • (A₁ + A₀) - B₀, let Q := √2⁻¹ • (A₁ - A₀) + B₁, have w : √2^3 • 1 - A₀ * B₀ - A₀ * B₁ - A₁ * B₀ + A₁ * B₁ = √2⁻¹ • (P^2 + Q^2), { dsimp [P, Q], -- distribute out all the powers and products appearing on the RHS simp only [sq, sub_mul, mul_sub, add_mul, mul_add, smul_add, smul_sub], -- pull all coefficients out to the front, and combine `√2`s where possible simp only [algebra.mul_smul_comm, algebra.smul_mul_assoc, ←mul_smul, sqrt_two_inv_mul_self], -- replace Aᵢ * Aᵢ = 1 and Bᵢ * Bᵢ = 1 simp only [←sq, T.A₀_inv, T.A₁_inv, T.B₀_inv, T.B₁_inv], -- move Aᵢ to the left of Bᵢ simp only [←T.A₀B₀_commutes, ←T.A₀B₁_commutes, ←T.A₁B₀_commutes, ←T.A₁B₁_commutes], -- collect terms, simplify coefficients, and collect terms again: abel, -- all terms coincide, but the last one. Simplify all other terms simp only [M], simp only [neg_mul, int.cast_bit0, one_mul, mul_inv_cancel_of_invertible, int.cast_one, one_smul, int.cast_neg, add_right_inj, neg_smul, ← add_smul], -- just look at the coefficients now: congr, exact mul_left_cancel₀ (by norm_num) tsirelson_inequality_aux, }, have pos : 0 ≤ √2⁻¹ • (P^2 + Q^2), { have P_sa : star P = P, { dsimp [P], simp only [star_smul, star_add, star_sub, star_id_of_comm, T.A₀_sa, T.A₁_sa, T.B₀_sa, T.B₁_sa], }, have Q_sa : star Q = Q, { dsimp [Q], simp only [star_smul, star_add, star_sub, star_id_of_comm, T.A₀_sa, T.A₁_sa, T.B₀_sa, T.B₁_sa], }, have P2_nonneg : 0 ≤ P^2, { rw [sq], conv { congr, skip, congr, rw ←P_sa, }, convert (star_mul_self_nonneg : 0 ≤ star P * P), }, have Q2_nonneg : 0 ≤ Q^2, { rw [sq], conv { congr, skip, congr, rw ←Q_sa, }, convert (star_mul_self_nonneg : 0 ≤ star Q * Q), }, convert smul_le_smul_of_nonneg (add_nonneg P2_nonneg Q2_nonneg) (le_of_lt (show 0 < √2⁻¹, by norm_num)), -- `norm_num` can't directly show `0 ≤ √2⁻¹` simp, }, apply le_of_sub_nonneg, simpa only [sub_add_eq_sub_sub, ←sub_add, w] using pos, end
43775103413ef984fcb569fc75936b5e1de0e566
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/data/set/finite.lean
0a65e12bc734afb8ed592f514f3d1f2e5d44f5b8
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
34,843
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import data.finset.sort /-! # Finite sets This file defines predicates `finite : set α → Prop` and `infinite : set α → Prop` and proves some basic facts about finite sets. -/ 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 _ _ h.fintype @[simp] lemma not_infinite {s : set α} : ¬ s.infinite ↔ s.finite := by simp [infinite] @[simp] theorem finite.mem_to_finset {s : set α} (h : finite s) {a : α} : a ∈ h.to_finset ↔ a ∈ s := @mem_to_finset _ _ h.fintype _ @[simp] theorem finite.to_finset.nonempty {s : set α} (h : finite s) : h.to_finset.nonempty ↔ s.nonempty := show (∃ x, x ∈ h.to_finset) ↔ (∃ x, x ∈ s), from exists_congr (λ _, h.mem_to_finset) @[simp] lemma finite.coe_to_finset {s : set α} (h : finite s) : ↑h.to_finset = s := @set.coe_to_finset _ s h.fintype @[simp] lemma finite.coe_sort_to_finset {s : set α} (h : finite s) : (h.to_finset : Type*) = s := by rw [← finset.coe_sort_coe _, h.coe_to_finset] @[simp] lemma finite_empty_to_finset (h : finite (∅ : set α)) : h.to_finset = ∅ := by rw [← finset.coe_inj, h.coe_to_finset, finset.coe_empty] @[simp] lemma finite.to_finset_inj {s t : set α} {hs : finite s} {ht : finite t} : hs.to_finset = ht.to_finset ↔ s = t := by simp [←finset.coe_inj] lemma subset_to_finset_iff {s : finset α} {t : set α} (ht : finite t) : s ⊆ ht.to_finset ↔ ↑s ⊆ t := by rw [← finset.coe_subset, ht.coe_to_finset] @[simp] lemma finite_to_finset_eq_empty_iff {s : set α} {h : finite s} : h.to_finset = ∅ ↔ s = ∅ := by simp [←finset.coe_inj] 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⟩ theorem exists_finite_iff_finset {p : set α → Prop} : (∃ s, finite s ∧ p s) ↔ ∃ s : finset α, p ↑s := ⟨λ ⟨s, hs, hps⟩, ⟨hs.to_finset, hs.coe_to_finset.symm ▸ hps⟩, λ ⟨s, hs⟩, ⟨↑s, finite_mem_finset s, hs⟩⟩ lemma finite.fin_embedding {s : set α} (h : finite s) : ∃ (n : ℕ) (f : fin n ↪ α), range f = s := ⟨_, (fintype.equiv_fin (h.to_finset : set α)).symm.as_embedding, by simp⟩ lemma finite.fin_param {s : set α} (h : finite s) : ∃ (n : ℕ) (f : fin n → α), injective f ∧ range f = s := let ⟨n, f, hf⟩ := h.fin_embedding in ⟨n, f, f.injective, hf⟩ /-- 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⟩ instance finite.inhabited : inhabited {s : set α // finite s} := ⟨⟨∅, finite_empty⟩⟩ /-- A `fintype` structure on `insert a s`. -/ 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) : (hs.insert a).to_finset = insert a hs.to_finset := finset.ext $ by simp @[simp] lemma insert_to_finset [decidable_eq α] {a : α} {s : set α} [fintype s] : (insert a s).to_finset = insert a s.to_finset := by simp [finset.ext_iff, mem_insert_iff] @[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) (h.insert a)) : 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 α) := unique.fintype @[simp] theorem card_singleton (a : α) : fintype.card ({a} : set α) = 1 := fintype.card_of_subsingleton _ @[simp] theorem finite_singleton (a : α) : finite ({a} : set α) := ⟨set.fintype_singleton _⟩ lemma subsingleton.finite {s : set α} (h : s.subsingleton) : finite s := h.induction_on finite_empty finite_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⟩ /-- If `(set.univ : set α)` is finite then `α` is a finite type. -/ noncomputable def fintype_of_univ_finite (H : (univ : set α).finite ) : fintype α := @fintype.of_equiv _ (univ : set α) H.fintype (equiv.set.univ _) lemma univ_finite_iff_nonempty_fintype : (univ : set α).finite ↔ nonempty (fintype α) := begin split, { intro h, exact ⟨fintype_of_univ_finite h⟩ }, { rintro ⟨_i⟩, exactI finite_univ } end theorem infinite_univ_iff : (@univ α).infinite ↔ _root_.infinite α := ⟨λ h₁, ⟨λ h₂, h₁ $ @finite_univ α h₂⟩, λ ⟨h₁⟩ h₂, h₁ (fintype_of_univ_finite h₂)⟩ theorem infinite_univ [h : _root_.infinite α] : infinite (@univ α) := infinite_univ_iff.2 h theorem infinite_coe_iff {s : set α} : _root_.infinite s ↔ infinite s := ⟨λ ⟨h₁⟩ h₂, h₁ h₂.some, λ h₁, ⟨λ h₂, h₁ ⟨h₂⟩⟩⟩ theorem infinite.to_subtype {s : set α} (h : infinite s) : _root_.infinite s := infinite_coe_iff.2 h /-- Embedding of `ℕ` into an infinite set. -/ noncomputable def infinite.nat_embedding (s : set α) (h : infinite s) : ℕ ↪ s := by { haveI := h.to_subtype, exact infinite.nat_embedding s } lemma infinite.exists_subset_card_eq {s : set α} (hs : infinite s) (n : ℕ) : ∃ t : finset α, ↑t ⊆ s ∧ t.card = n := ⟨((finset.range n).map (hs.nat_embedding _)).map (embedding.subtype _), by simp⟩ lemma infinite.nonempty {s : set α} (h : s.infinite) : s.nonempty := let a := infinite.nat_embedding s h 37 in ⟨a.1, a.2⟩ 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⟩ lemma finite.sup {s t : set α} : finite s → finite t → finite (s ⊔ t) := finite.union lemma infinite_of_finite_compl [_root_.infinite α] {s : set α} (hs : sᶜ.finite) : s.infinite := λ h, set.infinite_univ (by simpa using hs.union h) lemma finite.infinite_compl [_root_.infinite α] {s : set α} (hs : s.finite) : sᶜ.infinite := λ h, set.infinite_univ (by simpa using hs.union h) 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 /-- A `fintype` structure on a set defines a `fintype` structure on its subset. -/ 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⟩ lemma finite.union_iff {s t : set α} : finite (s ∪ t) ↔ finite s ∧ finite t := ⟨λ h, ⟨h.subset (subset_union_left _ _), h.subset (subset_union_right _ _)⟩, λ ⟨hs, ht⟩, hs.union ht⟩ lemma finite.diff {s t u : set α} (hs : s.finite) (ht : t.finite) (h : u \ t ≤ s) : u.finite := begin refine finite.subset (ht.union hs) _, exact diff_subset_iff.mp h end theorem finite.inter_of_left {s : set α} (h : finite s) (t : set α) : finite (s ∩ t) := h.subset (inter_subset_left _ _) theorem finite.inter_of_right {s : set α} (h : finite s) (t : set α) : finite (t ∩ s) := h.subset (inter_subset_right _ _) theorem finite.inf_of_left {s : set α} (h : finite s) (t : set α) : finite (s ⊓ t) := h.inter_of_left t theorem finite.inf_of_right {s : set α} (h : finite s) (t : set α) : finite (t ⊓ s) := h.inter_of_right t theorem infinite_mono {s t : set α} (h : s ⊆ t) : infinite s → infinite t := mt (λ ht, ht.subset 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 (plift ι)] : fintype (range f) := fintype.of_finset (finset.univ.image $ f ∘ plift.down) $ by simp [(@equiv.plift ι).exists_congr_left] theorem finite_range (f : ι → α) [fintype (plift ι)] : 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⟩ theorem infinite_of_infinite_image (f : α → β) {s : set α} (hs : (f '' s).infinite) : s.infinite := mt (finite.image f) hs lemma finite.dependent_image {s : set α} (hs : finite s) (F : Π i ∈ s, β) : finite {y : β | ∃ x (hx : x ∈ s), y = F x hx} := begin letI : fintype s := hs.fintype, convert finite_range (λ x : s, F x x.2), simp only [set_coe.exists, subtype.coe_mk, eq_comm], end theorem finite.of_preimage {f : α → β} {s : set β} (h : finite (f ⁻¹' s)) (hf : surjective f) : finite s := hf.image_preimage s ▸ h.image _ 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 /-- If a function `f` has a partial inverse and sends a set `s` to a set with `[fintype]` instance, then `s` has a `fintype` structure as well. -/ 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 {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_iff_val.1 eq⟩ theorem finite_image_iff {s : set α} {f : α → β} (hi : inj_on f s) : finite (f '' s) ↔ finite s := ⟨finite_of_finite_image hi, finite.image _⟩ theorem infinite_image_iff {s : set α} {f : α → β} (hi : inj_on f s) : infinite (f '' s) ↔ infinite s := not_congr $ finite_image_iff hi theorem infinite_of_inj_on_maps_to {s : set α} {t : set β} {f : α → β} (hi : inj_on f s) (hm : maps_to f s t) (hs : infinite s) : infinite t := infinite_mono (maps_to'.mp hm) $ (infinite_image_iff hi).2 hs theorem infinite.exists_ne_map_eq_of_maps_to {s : set α} {t : set β} {f : α → β} (hs : infinite s) (hf : maps_to f s t) (ht : finite t) : ∃ (x ∈ s) (y ∈ s), x ≠ y ∧ f x = f y := begin unfreezingI { contrapose! ht }, exact infinite_of_inj_on_maps_to (λ x hx y hy, not_imp_not.1 (ht x hx y hy)) hf hs end theorem infinite.exists_lt_map_eq_of_maps_to [linear_order α] {s : set α} {t : set β} {f : α → β} (hs : infinite s) (hf : maps_to f s t) (ht : finite t) : ∃ (x ∈ s) (y ∈ s), x < y ∧ f x = f y := let ⟨x, hx, y, hy, hxy, hf⟩ := hs.exists_ne_map_eq_of_maps_to hf ht in hxy.lt_or_lt.elim (λ hxy, ⟨x, hx, y, hy, hxy, hf⟩) (λ hyx, ⟨y, hy, x, hx, hyx, hf.symm⟩) theorem infinite_range_of_injective [_root_.infinite α] {f : α → β} (hi : injective f) : infinite (range f) := by { rw [←image_univ, infinite_image_iff (inj_on_of_injective hi _)], exact infinite_univ } theorem infinite_of_injective_forall_mem [_root_.infinite α] {s : set β} {f : α → β} (hi : injective f) (hf : ∀ x : α, f x ∈ s) : infinite s := by { rw ←range_subset_iff at hf, exact infinite_mono hf (infinite_range_of_injective hi) } theorem finite.preimage {s : set β} {f : α → β} (I : set.inj_on f (f⁻¹' s)) (h : finite s) : finite (f ⁻¹' s) := finite_of_finite_image I (h.subset (image_preimage_subset f s)) theorem finite.preimage_embedding {s : set β} (f : α ↪ β) (h : s.finite) : (f ⁻¹' s).finite := finite.preimage (λ _ _ _ _ h', f.injective h') h lemma finite_option {s : set (option α)} : finite s ↔ finite {x : α | some x ∈ s} := ⟨λ h, h.preimage_embedding embedding.some, λ h, ((h.image some).insert none).subset $ λ x, option.cases_on x (λ _, or.inl rfl) (λ x hx, or.inr $ mem_image_of_mem _ hx)⟩ instance fintype_Union [decidable_eq α] [fintype (plift ι)] (f : ι → set α) [∀ i, fintype (f i)] : fintype (⋃ i, f i) := fintype.of_finset (finset.univ.bUnion (λ i : plift ι, (f i.down).to_finset)) $ by simp theorem finite_Union [fintype (plift ι)] {f : ι → set α} (H : ∀i, finite (f i)) : finite (⋃ i, f i) := ⟨@set.fintype_Union _ _ (classical.dec_eq α) _ _ (λ i, finite.fintype (H i))⟩ /-- A union of sets with `fintype` structure over a set with `fintype` structure has a `fintype` structure. -/ 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 : Π i ∈ s, 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 _ _) 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⟩ /-- `image2 f s t` is finitype if `s` and `t` are. -/ instance fintype_image2 [decidable_eq γ] (f : α → β → γ) (s : set α) (t : set β) [hs : fintype s] [ht : fintype t] : fintype (image2 f s t : set γ) := by { rw ← image_prod, apply set.fintype_image } lemma finite.image2 (f : α → β → γ) {s : set α} {t : set β} (hs : finite s) (ht : finite t) : finite (image2 f s t) := by { rw ← image_prod, exact (hs.prod ht).image _ } /-- If `s : set α` is a set with `fintype` instance and `f : α → set β` is a function such that each `f a`, `a ∈ s`, has a `fintype` structure, then `s >>= f` has a `fintype` structure. -/ 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 β} (h : finite s) (hf : ∀ a ∈ s, finite (f a)) : finite (s >>= f) := h.bUnion hf instance fintype_seq [decidable_eq β] (f : set (α → β)) (s : set α) [fintype f] [fintype s] : fintype (f.seq s) := by { rw seq_def, apply set.fintype_bUnion' } instance fintype_seq' {α β : Type u} [decidable_eq β] (f : set (α → β)) (s : set α) [fintype f] [fintype s] : fintype (f <*> s) := set.fintype_seq f s theorem finite.seq {f : set (α → β)} {s : set α} (hf : finite f) (hs : finite s) : finite (f.seq s) := by { rw seq_def, exact hf.bUnion (λ f _, hs.image _) } theorem finite.seq' {α β : Type u} {f : set (α → β)} {s : set α} (hf : finite f) (hs : finite s) : finite (f <*> s) := hf.seq hs /-- There are finitely many subsets of a given finite set -/ lemma finite.finite_subsets {α : Type u} {a : set α} (h : finite a) : finite {b | b ⊆ a} := ⟨fintype.of_finset ((finset.powerset h.to_finset).map finset.coe_emb.1) $ λ s, by simpa [← @exists_finite_iff_finset α (λ t, t ⊆ a ∧ t = s), subset_to_finset_iff, ← and.assoc] using h.subset⟩ 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 h1.to_finset.exists_min_image f ⟨x, h1.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 h1.to_finset.exists_max_image f ⟨x, h1.mem_to_finset.2 hx⟩ theorem exists_lower_bound_image [hα : nonempty α] [linear_order β] (s : set α) (f : α → β) (h : s.finite) : ∃ (a : α), ∀ b ∈ s, f a ≤ f b := begin by_cases hs : set.nonempty s, { exact let ⟨x₀, H, hx₀⟩ := set.exists_min_image s f h hs in ⟨x₀, λ x hx, hx₀ x hx⟩ }, { exact nonempty.elim hα (λ a, ⟨a, λ x hx, absurd (set.nonempty_of_mem hx) hs⟩) } end theorem exists_upper_bound_image [hα : nonempty α] [linear_order β] (s : set α) (f : α → β) (h : s.finite) : ∃ (a : α), ∀ b ∈ s, f b ≤ f a := begin by_cases hs : set.nonempty s, { exact let ⟨x₀, H, hx₀⟩ := set.exists_max_image s f h hs in ⟨x₀, λ x hx, hx₀ x hx⟩ }, { exact nonempty.elim hα (λ a, ⟨a, λ x hx, absurd (set.nonempty_of_mem hx) hs⟩) } end end set namespace finset variables [decidable_eq β] variables {s : finset α} lemma finite_to_set (s : finset α) : set.finite (↑s : set α) := set.finite_mem_finset s @[simp] lemma coe_bUnion {f : α → finset β} : ↑(s.bUnion f) = (⋃x ∈ (↑s : set α), ↑(f x) : set β) := by simp [set.ext_iff] @[simp] lemma finite_to_set_to_finset {α : Type*} (s : finset α) : (finite_to_set s).to_finset = s := by { ext, rw [set.finite.mem_to_finset, mem_coe] } end finset namespace set /-- Finite product of finite sets is finite -/ lemma finite.pi {δ : Type*} [fintype δ] {κ : δ → Type*} {t : Π d, set (κ d)} (ht : ∀ d, (t d).finite) : (pi univ t).finite := begin classical, convert (fintype.pi_finset (λ d, (ht d).to_finset)).finite_to_set, ext, simp, end /-- A finite union of finsets is finite. -/ lemma union_finset_finite_of_range_finite (f : α → finset β) (h : (range f).finite) : (⋃ a, (f a : set β)).finite := begin rw ← bUnion_range, exact h.bUnion (λ y hy, y.finite_to_set) end 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 casesI hs, choose f hf using show ∀ x : s, ∃ i, x.1 ∈ t i, {simpa [subset_def] using h}, refine ⟨range f, finite_range f, λ x hx, _⟩, rw [bUnion_range, mem_Union], 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, tfin.subset (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⟩ /-- An increasing union distributes over finite intersection. -/ lemma Union_Inter_of_monotone {ι ι' α : Type*} [fintype ι] [linear_order ι'] [nonempty ι'] {s : ι → ι' → set α} (hs : ∀ i, monotone (s i)) : (⋃ j : ι', ⋂ i : ι, s i j) = ⋂ i : ι, ⋃ j : ι', s i j := begin ext x, refine ⟨λ hx, Union_Inter_subset hx, λ hx, _⟩, simp only [mem_Inter, mem_Union, mem_Inter] at hx ⊢, choose j hj using hx, obtain ⟨j₀⟩ := show nonempty ι', by apply_instance, refine ⟨finset.univ.fold max j₀ j, λ i, hs i _ (hj i)⟩, rw [finset.fold_op_rel_iff_or (@le_max_iff _ _)], exact or.inr ⟨i, finset.mem_univ i, le_rfl⟩ end instance nat.fintype_Iio (n : ℕ) : fintype (Iio n) := fintype.of_finset (finset.range n) $ by simp /-- If `P` is some relation between terms of `γ` and sets in `γ`, such that every finite set `t : set γ` has some `c : γ` related to it, then there is a recursively defined sequence `u` in `γ` so `u n` is related to the image of `{0, 1, ..., n-1}` under `u`. (We use this later to show sequentially compact sets are totally bounded.) -/ lemma seq_of_forall_finite_exists {γ : Type*} {P : γ → set γ → Prop} (h : ∀ t, finite t → ∃ c, P c t) : ∃ u : ℕ → γ, ∀ n, P (u n) (u '' Iio n) := ⟨λ n, @nat.strong_rec_on' (λ _, γ) n $ λ n ih, classical.some $ h (range $ λ m : Iio n, ih m.1 m.2) (finite_range _), λ n, begin classical, refine nat.strong_rec_on' n (λ n ih, _), rw nat.strong_rec_on_beta', convert classical.some_spec (h _ _), ext x, split, { rintros ⟨m, hmn, rfl⟩, exact ⟨⟨m, hmn⟩, rfl⟩ }, { rintros ⟨⟨m, hmn⟩, rfl⟩, exact ⟨m, hmn, rfl⟩ } 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)) := (hf.union hg).subset range_ite_subset lemma finite_range_const {c : β} : finite (range (λ x : α, c)) := (finite_singleton c).subset 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)) := (finset.range (b + 1)).finite_to_set.subset range_find_greatest_subset lemma card_lt_card {s t : set α} [fintype s] [fintype t] (h : s ⊂ t) : fintype.card s < fintype.card t := fintype.card_lt_of_injective_not_surjective (set.inclusion h.1) (set.inclusion_injective h.1) $ λ hst, (ssubset_iff_subset_ne.1 h).2 (eq_of_inclusion_surjective hst) lemma card_le_of_subset {s t : set α} [fintype s] [fintype t] (hsub : s ⊆ t) : fintype.card s ≤ fintype.card t := fintype.card_le_of_injective (set.inclusion hsub) (set.inclusion_injective hsub) 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 subset_iff_to_finset_subset (s t : set α) [fintype s] [fintype t] : s ⊆ t ↔ s.to_finset ⊆ t.to_finset := by simp @[simp, mono] lemma finite.to_finset_mono {s t : set α} {hs : finite s} {ht : finite t} : hs.to_finset ⊆ ht.to_finset ↔ s ⊆ t := begin split, { intros h x, rw [←finite.mem_to_finset hs, ←finite.mem_to_finset ht], exact λ hx, h hx }, { intros h x, rw [finite.mem_to_finset hs, finite.mem_to_finset ht], exact λ hx, h hx } end @[simp, mono] lemma finite.to_finset_strict_mono {s t : set α} {hs : finite s} {ht : finite t} : hs.to_finset ⊂ ht.to_finset ↔ s ⊂ t := begin rw [←lt_eq_ssubset, ←finset.lt_iff_ssubset, lt_iff_le_and_ne, lt_iff_le_and_ne], simp end 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_injective f hf 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 lemma finite.card_to_finset {s : set α} [fintype s] (h : s.finite) : h.to_finset.card = fintype.card s := by { rw [← finset.card_attach, finset.attach_eq_univ, ← fintype.card], congr' 2, funext, rw set.finite.mem_to_finset } section decidable_eq lemma to_finset_compl {α : Type*} [fintype α] [decidable_eq α] (s : set α) [fintype (sᶜ : set α)] [fintype s] : sᶜ.to_finset = (s.to_finset)ᶜ := by ext; simp lemma to_finset_inter {α : Type*} [decidable_eq α] (s t : set α) [fintype (s ∩ t : set α)] [fintype s] [fintype t] : (s ∩ t).to_finset = s.to_finset ∩ t.to_finset := by ext; simp lemma to_finset_union {α : Type*} [decidable_eq α] (s t : set α) [fintype (s ∪ t : set α)] [fintype s] [fintype t] : (s ∪ t).to_finset = s.to_finset ∪ t.to_finset := by ext; simp lemma to_finset_ne_eq_erase {α : Type*} [decidable_eq α] [fintype α] (a : α) [fintype {x : α | x ≠ a}] : {x : α | x ≠ a}.to_finset = finset.univ.erase a := by ext; simp lemma card_ne_eq [fintype α] (a : α) [fintype {x : α | x ≠ a}] : fintype.card {x : α | x ≠ a} = fintype.card α - 1 := begin haveI := classical.dec_eq α, rw [←to_finset_card, to_finset_ne_eq_erase, finset.card_erase_of_mem (finset.mem_univ _), finset.card_univ, nat.pred_eq_sub_one], end end decidable_eq section variables [semilattice_sup α] [nonempty α] {s : set α} /--A finite set is bounded above.-/ protected lemma finite.bdd_above (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 finite.bdd_above_bUnion {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.-/ protected lemma finite.bdd_below (hs : finite s) : bdd_below s := @finite.bdd_above (order_dual α) _ _ _ hs /--A finite union of sets which are all bounded below is still bounded below.-/ lemma finite.bdd_below_bUnion {I : set β} {S : β → set α} (H : finite I) : (bdd_below (⋃i∈I, S i)) ↔ (∀i ∈ I, bdd_below (S i)) := @finite.bdd_above_bUnion (order_dual α) _ _ _ _ _ H end end set namespace finset /-- A finset is bounded above. -/ protected lemma bdd_above [semilattice_sup α] [nonempty α] (s : finset α) : bdd_above (↑s : set α) := s.finite_to_set.bdd_above /-- A finset is bounded below. -/ protected lemma bdd_below [semilattice_inf α] [nonempty α] (s : finset α) : bdd_below (↑s : set α) := s.finite_to_set.bdd_below end finset namespace fintype variables [fintype α] {p q : α → Prop} [decidable_pred p] [decidable_pred q] @[simp] lemma card_subtype_compl : fintype.card {x // ¬ p x} = fintype.card α - fintype.card {x // p x} := begin classical, rw [fintype.card_of_subtype (set.to_finset pᶜ), set.to_finset_compl p, finset.card_compl, fintype.card_of_subtype (set.to_finset p)]; intros; simp; refl end /-- If two subtypes of a fintype have equal cardinality, so do their complements. -/ lemma card_compl_eq_card_compl (h : fintype.card {x // p x} = fintype.card {x // q x}) : fintype.card {x // ¬ p x} = fintype.card {x // ¬ q x} := by simp only [card_subtype_compl, h] end fintype /-- If a set `s` does not contain any elements between any pair of elements `x, z ∈ s` with `x ≤ z` (i.e if given `x, y, z ∈ s` such that `x ≤ y ≤ z`, then `y` is either `x` or `z`), then `s` is finite. -/ lemma set.finite_of_forall_between_eq_endpoints {α : Type*} [linear_order α] (s : set α) (h : ∀ (x ∈ s) (y ∈ s) (z ∈ s), x ≤ y → y ≤ z → x = y ∨ y = z) : set.finite s := begin by_contra hinf, change s.infinite at hinf, rcases hinf.exists_subset_card_eq 3 with ⟨t, hts, ht⟩, let f := t.order_iso_of_fin ht, let x := f 0, let y := f 1, let z := f 2, have := h x (hts x.2) y (hts y.2) z (hts z.2) (f.monotone $ by dec_trivial) (f.monotone $ by dec_trivial), have key₁ : (0 : fin 3) ≠ 1 := by dec_trivial, have key₂ : (1 : fin 3) ≠ 2 := by dec_trivial, cases this, { dsimp only [x, y] at this, exact key₁ (f.injective $ subtype.coe_injective this) }, { dsimp only [y, z] at this, exact key₂ (f.injective $ subtype.coe_injective this) } end
b5ec09dbd1e51feb4489c67a7586b35f9d7e9570
9b9a16fa2cb737daee6b2785474678b6fa91d6d4
/src/tactic/fin_cases.lean
efbf72b7f7a8ddc946f9f8bd5356acdcd1618028
[ "Apache-2.0" ]
permissive
johoelzl/mathlib
253f46daa30b644d011e8e119025b01ad69735c4
592e3c7a2dfbd5826919b4605559d35d4d75938f
refs/heads/master
1,625,657,216,488
1,551,374,946,000
1,551,374,946,000
98,915,829
0
0
Apache-2.0
1,522,917,267,000
1,501,524,499,000
Lean
UTF-8
Lean
false
false
1,954
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Scott Morrison Case bashing on `fin n`, for explicit numerals `n`. -/ import data.fin namespace tactic open lean.parser open interactive interactive.types expr meta def fin_cases_at (e : expr) : tactic unit := do `(fin %%n) ← infer_type e, n ← eval_expr ℕ n, [(_, [val, bd], _)] ← cases_core e [`val, `bd], -- We now call `cases val` n times, rotating the generated goals out of the way. iterate_at_most n (do val ← get_local `val, cases val, rotate 1), -- We've got an absurd hypothesis `bd`, but it is messy: it looks like -- `nat.succ (... (nat.succ val)) < n` -- So we rewrite it as `bd : val + 1 + ... + 1 < n`, and use `dec_trivial` to kill it. ss ← mk_const `nat.succ_eq_add_one, bd ← get_local `bd, (list.range n).mfoldl (λ bd _, do rewrite_hyp ss bd) bd, to_expr ``(absurd %%bd dec_trivial) >>= exact, -- We put the goals back in order, and clear the `bd` hypotheses. iterate_exactly n (do rotate_right 1, try `[rw [fin.mk_val]], try (get_local `bd >>= clear)) namespace interactive private meta def hyp := tk "*" *> return none <|> some <$> ident /-- `fin_cases h` performs case analysis on a hypothesis `h : fin n`, where `n` is an explicit natural number. `fin_cases *` performs case analysis on all suitable hypotheses. As an example, in ``` example (f : ℕ → Prop) (p : fin 3) (h0 : f 0) (h1 : f 1) (h2 : f 2) : f p.val := begin fin_cases p, all_goals { assumption } end ``` after `fin_cases p`, there are three goals, `f 0`, `f 1`, and `f 2`. -/ meta def fin_cases : parse hyp → tactic unit | none := do ctx ← local_context, ctx.mfirst fin_cases_at <|> fail "No explicit `fin n` hypotheses." | (some n) := do h ← get_local n, fin_cases_at h end interactive end tactic
be92edb70bf60b3cc473c688e176f8d86fdaef68
d320d01276642370017b4ce56793b5f73e0016f9
/lean projects and notes/finalreview.lean
c85d0eea22314f60e8278d679b364c5a1d9fcca3
[]
no_license
samiazam00/my-work
388d815ddc7e47860375959ba31be2530be7f11e
e9a8218b2441dce00bf117d3d985d00e6ee14ec0
refs/heads/master
1,608,518,076,248
1,580,268,523,000
1,580,268,523,000
236,280,156
0
0
null
null
null
null
UTF-8
Lean
false
false
4,973
lean
--** Writing functions, recursion: --see HW 3 for more examples -- ex. recursive sum function: def sumto : ℕ → ℕ | 0 := 0 | (nat.succ n') := (nat.succ n') + sumto n' -- ex. function that creates a list of string s repeated n times def repeat : string → ℕ → list string | s 0 := list.nil | s (nat.succ n') := list.cons s (repeat s n') --** Using Prod: --ex. we can use "prod" to rep a pair of values: inductive prod_nat_nat : Type | pair : ℕ → ℕ → prod_nat_nat def nn := prod_nat_nat.pair 2 3 #reduce nn --** High order functions (like map and reduce): def mmap : (ℕ → ℕ) → list ℕ → list ℕ | f [] := [] | f (list.cons h t) := list.cons (f h) (mmap f t) -- An example application of this function #eval mmap (λ n, n + 1) [1, 2, 3, 4, 5] --** Propositions and Proofs: --ex: --propostion: def one_eq_one : Prop := --define a proposition with Prop keyword 1 = 1 --formalize the prop in this line def proof_that_one_eq_one : one_eq_one := --define a proof for prop one_eq_one (eq.refl 1) -- the proof def two_plus_two_eq_four : 2 + 2 = 4 := --2+2=4 is the prop eq.refl 4 --this line is the proof --** Predicate Logic: --Predicates are propostions but with parameters, so you can create -- different props with a predicate. Axioms are accepted as true w/o proof. --ex 1 --and.intro h1 h2 builds a proof of p ∧ q using proofs h1 : p and h2 : q -- example (hp : p) (hq : q) : p ∧ q := and.intro hp hq -- and.elim_left h creates a proof of p from a proof h : p ∧ q -- example (h : p ∧ q) : p := and.elim_left h -- example (h : p ∧ q) : q := and.elim_right h --We can now prove p ∧ q → q ∧ p: --example (h : p ∧ q) : q ∧ p := and.intro (and.right h) (and.left h) -- ex 2 : axioms - 0 is even, and an even number plus 2 is even inductive is_even : ℕ → Prop | pf_zero_is_even : (is_even 0) --base case: 0 is even is assumed true | pf_even_plus_two_is_even : ∀ (n : ℕ), is_even n → is_even (nat.succ (nat.succ n)) --for all n, n is even if n+2 is even --ways to check if 0 is even: open is_even theorem zero_is_even : is_even 0 := pf_zero_is_even theorem zero_is_even' : is_even 0 := begin exact pf_zero_is_even end --here's another example with the type Person: axiom Person : Type axiom Likes : Person → Person → Prop example : (∃ (p : Person), ∀ (q : Person), Likes q p) → (∀ (x : Person), ∃ (y : Person), Likes x y ) := λ h, λ p, match h with | (exists.intro w pf) := exists.intro w (pf p) end example : (∃ (p : Person), ∀ (q : Person), Likes q p) → (∀ (x : Person), ∃ (y : Person), Likes x y ) := begin assume h, --assumes the premise which we do for implies proofs assume p, -- makes p an arbitrary but specific person who likes another person cases h with w pf, exact exists.intro w (pf p) end --more deets /- The "case" breaks apart the first assume statement into two parts: a witness (w) and a proof that everyone likes the person (pf). Think of it as cons h t, which breaks up a list into two parts, head and tail. With exists.intro, we need a witness, and a proof about that witness. W is our witness, a person who is liked, and pf is our "function" that takes a value and says that they like the witness. In other words the proof says that our arbitrary but specific person likes a person, w. -/ --another example: formalizing predicate logic --There exist three natural numbers, a, b, and c, such that a^2 + b^2 = c^2: def py : Prop := ∃ (a b c : ℕ), a^2 + b^2 = c^2 --everyone likes someone: def everyone_likes_someone : Prop := ∀ (p : Person), ∃ (q : Person), Likes p q --"likes" is an example of the transitive property: def likes_is_trans := ∀ (p q r : Person), Likes p q → Likes q r → Likes p r --** Polymorphic functions: /- ex. take a type, α, a value, (s : α), and a nat, n, and return a list in which the value, a, is repeated n times. Make the type argument to this function implicit: -/ def poly_repeat {α : Type} : α → ℕ → list α | a 0 := list.nil | a (nat.succ n') := list.cons a (poly_repeat a n') --polymorphic version of mmap function: def pmap {α β : Type} : (α → β) → list α → list β | f [] := [] | f (list.cons h t) := list.cons (f h) (pmap f t) --** Polymorphic types: --ex. polymorphic tree type: inductive tree (α : Type) : Type | empty : tree | value (a : α) (left : tree) (right : tree) : tree --now a poly function based on the tree type, take tree α and return tt if empty open tree def is_empty (α : Type) : tree α → bool | (tree.empty α) := tt | _ := ff
3dd67a870bbe43bd19dc5e4c0662abc14b66d5e3
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/category_theory/concrete_category/basic.lean
6de88da5ec5a96983efbdef42af1599aff6ba20e
[ "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
6,586
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Johannes Hölzl, Reid Barton, Sean Leather, Yury Kudryashov -/ import category_theory.types import category_theory.full_subcategory /-! # Concrete categories A concrete category is a category `C` with a fixed faithful functor `forget : C ⥤ Type*`. We define concrete categories using `class concrete_category`. In particular, we impose no restrictions on the carrier type `C`, so `Type` is a concrete category with the identity forgetful functor. Each concrete category `C` comes with a canonical faithful functor `forget C : C ⥤ Type*`. We say that a concrete category `C` admits a *forgetful functor* to a concrete category `D`, if it has a functor `forget₂ C D : C ⥤ D` such that `(forget₂ C D) ⋙ (forget D) = forget C`, see `class has_forget₂`. Due to `faithful.div_comp`, it suffices to verify that `forget₂.obj` and `forget₂.map` agree with the equality above; then `forget₂` will satisfy the functor laws automatically, see `has_forget₂.mk'`. Two classes helping construct concrete categories in the two most common cases are provided in the files `bundled_hom` and `unbundled_hom`, see their documentation for details. ## References See [Ahrens and Lumsdaine, *Displayed Categories*][ahrens2017] for related work. -/ universe u namespace category_theory section prio set_option default_priority 100 -- see Note [default priority] /-- A concrete category is a category `C` with a fixed faithful functor `forget : C ⥤ Type`. -/ class concrete_category (C : Type (u+1)) [large_category C] := (forget [] : C ⥤ Type u) [forget_faithful : faithful forget] end prio attribute [instance] concrete_category.forget_faithful /-- The forgetful functor from a concrete category to `Type u`. -/ @[reducible] def forget (C : Type (u+1)) [large_category C] [concrete_category C] : C ⥤ Type u := concrete_category.forget C /-- Provide a coercion to `Type u` for a concrete category. This is not marked as an instance as it could potentially apply to every type, and so is too expensive in typeclass search. You can use it on particular examples as: ``` instance : has_coe_to_sort X := concrete_category.has_coe_to_sort X ``` -/ def concrete_category.has_coe_to_sort (C : Type (u+1)) [large_category C] [concrete_category C] : has_coe_to_sort C := { S := Type u, coe := (concrete_category.forget C).obj } section local attribute [instance] concrete_category.has_coe_to_sort variables {C : Type (u+1)} [large_category C] [concrete_category C] @[simp] lemma forget_obj_eq_coe {X : C} : (forget C).obj X = X := rfl /-- Usually a bundled hom structure already has a coercion to function that works with different universes. So we don't use this as a global instance. -/ def concrete_category.has_coe_to_fun {X Y : C} : has_coe_to_fun (X ⟶ Y) := { F := λ f, X → Y, coe := λ f, (forget _).map f } local attribute [instance] concrete_category.has_coe_to_fun /-- In any concrete category, we can test equality of morphisms by pointwise evaluations.-/ lemma concrete_category.hom_ext {X Y : C} (f g : X ⟶ Y) (w : ∀ x : X, f x = g x) : f = g := begin apply faithful.map_injective (forget C), ext, exact w x, end @[simp] lemma forget_map_eq_coe {X Y : C} (f : X ⟶ Y) : (forget C).map f = f := rfl @[simp] lemma coe_id {X : C} (x : X) : ((𝟙 X) : X → X) x = x := congr_fun ((forget _).map_id X) x @[simp] lemma coe_comp {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) (x : X) : (f ≫ g) x = g (f x) := congr_fun ((forget _).map_comp _ _) x @[simp] lemma coe_hom_inv_id {X Y : C} (f : X ≅ Y) (x : X) : f.inv (f.hom x) = x := congr_fun ((forget C).map_iso f).hom_inv_id x @[simp] lemma coe_inv_hom_id {X Y : C} (f : X ≅ Y) (y : Y) : f.hom (f.inv y) = y := congr_fun ((forget C).map_iso f).inv_hom_id y local attribute [ext] concrete_category.hom_ext /-- In any concrete category, injective morphisms are monomorphisms, by extensionality. -/ lemma concrete_category.mono_of_injective {X Y : C} (f : X ⟶ Y) (i : function.injective f) : mono f := ⟨λ Z g h w, begin ext z, apply i, convert congr_arg (λ k : Z ⟶ Y, (k : Z → Y) z) w; simp only [coe_comp], end⟩ end instance concrete_category.types : concrete_category (Type u) := { forget := 𝟭 _ } /-- `has_forget₂ C D`, where `C` and `D` are both concrete categories, provides a functor `forget₂ C D : C ⥤ D` and a proof that `forget₂ ⋙ (forget D) = forget C`. -/ class has_forget₂ (C D : Type (u+1)) [large_category C] [concrete_category C] [large_category D] [concrete_category D] := (forget₂ : C ⥤ D) (forget_comp : forget₂ ⋙ (forget D) = forget C . obviously) /-- The forgetful functor `C ⥤ D` between concrete categories for which we have an instance `has_forget₂ C `. -/ @[reducible] def forget₂ (C D : Type (u+1)) [large_category C] [concrete_category C] [large_category D] [concrete_category D] [has_forget₂ C D] : C ⥤ D := has_forget₂.forget₂ instance forget_faithful (C D : Type (u+1)) [large_category C] [concrete_category C] [large_category D] [concrete_category D] [has_forget₂ C D] : faithful (forget₂ C D) := has_forget₂.forget_comp.faithful_of_comp instance induced_category.concrete_category {C D : Type (u+1)} [large_category D] [concrete_category D] (f : C → D) : concrete_category (induced_category D f) := { forget := induced_functor f ⋙ forget D } instance induced_category.has_forget₂ {C D : Type (u+1)} [large_category D] [concrete_category D] (f : C → D) : has_forget₂ (induced_category D f) D := { forget₂ := induced_functor f, forget_comp := rfl } /-- In order to construct a “partially forgetting” functor, we do not need to verify functor laws; it suffices to ensure that compositions agree with `forget₂ C D ⋙ forget D = forget C`. -/ def has_forget₂.mk' {C D : Type (u+1)} [large_category C] [concrete_category C] [large_category D] [concrete_category D] (obj : C → D) (h_obj : ∀ X, (forget D).obj (obj X) = (forget C).obj X) (map : Π {X Y}, (X ⟶ Y) → (obj X ⟶ obj Y)) (h_map : ∀ {X Y} {f : X ⟶ Y}, (forget D).map (map f) == (forget C).map f) : has_forget₂ C D := { forget₂ := faithful.div _ _ _ @h_obj _ @h_map, forget_comp := by apply faithful.div_comp } instance has_forget_to_Type (C : Type (u+1)) [large_category C] [concrete_category C] : has_forget₂ C (Type u) := { forget₂ := forget C, forget_comp := functor.comp_id _ } end category_theory
539cf8be4ade017c48cb0cf4d7ab4a9647eee693
4727251e0cd73359b15b664c3170e5d754078599
/src/data/list/zip.lean
137526647df63cf2075c8419d71f127020f8788d
[ "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
15,894
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kenny Lau -/ import data.list.big_operators /-! # zip & unzip This file provides results about `list.zip_with`, `list.zip` and `list.unzip` (definitions are in core Lean). `zip_with f l₁ l₂` applies `f : α → β → γ` pointwise to a list `l₁ : list α` and `l₂ : list β`. It applies, until one of the lists is exhausted. For example, `zip_with f [0, 1, 2] [6.28, 31] = [f 0 6.28, f 1 31]`. `zip` is `zip_with` applied to `prod.mk`. For example, `zip [a₁, a₂] [b₁, b₂, b₃] = [(a₁, b₁), (a₂, b₂)]`. `unzip` undoes `zip`. For example, `unzip [(a₁, b₁), (a₂, b₂)] = ([a₁, a₂], [b₁, b₂])`. -/ universe u open nat namespace list variables {α : Type u} {β γ δ : Type*} @[simp] theorem zip_with_cons_cons (f : α → β → γ) (a : α) (b : β) (l₁ : list α) (l₂ : list β) : zip_with f (a :: l₁) (b :: l₂) = f a b :: zip_with f l₁ l₂ := rfl @[simp] theorem zip_cons_cons (a : α) (b : β) (l₁ : list α) (l₂ : list β) : zip (a :: l₁) (b :: l₂) = (a, b) :: zip l₁ l₂ := rfl @[simp] theorem zip_with_nil_left (f : α → β → γ) (l) : zip_with f [] l = [] := rfl @[simp] theorem zip_with_nil_right (f : α → β → γ) (l) : zip_with f l [] = [] := by cases l; refl @[simp] lemma zip_with_eq_nil_iff {f : α → β → γ} {l l'} : zip_with f l l' = [] ↔ l = [] ∨ l' = [] := by { cases l; cases l'; simp } @[simp] theorem zip_nil_left (l : list α) : zip ([] : list β) l = [] := rfl @[simp] theorem zip_nil_right (l : list α) : zip l ([] : list β) = [] := zip_with_nil_right _ l @[simp] theorem zip_swap : ∀ (l₁ : list α) (l₂ : list β), (zip l₁ l₂).map prod.swap = zip l₂ l₁ | [] l₂ := (zip_nil_right _).symm | l₁ [] := by rw zip_nil_right; refl | (a::l₁) (b::l₂) := by simp only [zip_cons_cons, map_cons, zip_swap l₁ l₂, prod.swap_prod_mk]; split; refl @[simp] theorem length_zip_with (f : α → β → γ) : ∀ (l₁ : list α) (l₂ : list β), length (zip_with f l₁ l₂) = min (length l₁) (length l₂) | [] l₂ := rfl | l₁ [] := by simp only [length, min_zero, zip_with_nil_right] | (a::l₁) (b::l₂) := by simp [length, zip_cons_cons, length_zip_with l₁ l₂, min_add_add_right] @[simp] theorem length_zip : ∀ (l₁ : list α) (l₂ : list β), length (zip l₁ l₂) = min (length l₁) (length l₂) := length_zip_with _ theorem all₂_zip_with {f : α → β → γ} {p : γ → Prop} : ∀ {l₁ : list α} {l₂ : list β} (h : length l₁ = length l₂), all₂ p (zip_with f l₁ l₂) ↔ forall₂ (λ x y, p (f x y)) l₁ l₂ | [] [] _ := by simp | (a :: l₁) (b :: l₂) h := by { simp only [length_cons, add_left_inj] at h, simp [all₂_zip_with h] } lemma lt_length_left_of_zip_with {f : α → β → γ} {i : ℕ} {l : list α} {l' : list β} (h : i < (zip_with f l l').length) : i < l.length := by { rw [length_zip_with, lt_min_iff] at h, exact h.left } lemma lt_length_right_of_zip_with {f : α → β → γ} {i : ℕ} {l : list α} {l' : list β} (h : i < (zip_with f l l').length) : i < l'.length := by { rw [length_zip_with, lt_min_iff] at h, exact h.right } lemma lt_length_left_of_zip {i : ℕ} {l : list α} {l' : list β} (h : i < (zip l l').length) : i < l.length := lt_length_left_of_zip_with h lemma lt_length_right_of_zip {i : ℕ} {l : list α} {l' : list β} (h : i < (zip l l').length) : i < l'.length := lt_length_right_of_zip_with h theorem zip_append : ∀ {l₁ r₁ : list α} {l₂ r₂ : list β} (h : length l₁ = length l₂), zip (l₁ ++ r₁) (l₂ ++ r₂) = zip l₁ l₂ ++ zip r₁ r₂ | [] r₁ l₂ r₂ h := by simp only [eq_nil_of_length_eq_zero h.symm]; refl | l₁ r₁ [] r₂ h := by simp only [eq_nil_of_length_eq_zero h]; refl | (a::l₁) r₁ (b::l₂) r₂ h := by simp only [cons_append, zip_cons_cons, zip_append (succ.inj h)]; split; refl theorem zip_map (f : α → γ) (g : β → δ) : ∀ (l₁ : list α) (l₂ : list β), zip (l₁.map f) (l₂.map g) = (zip l₁ l₂).map (prod.map f g) | [] l₂ := rfl | l₁ [] := by simp only [map, zip_nil_right] | (a::l₁) (b::l₂) := by simp only [map, zip_cons_cons, zip_map l₁ l₂, prod.map]; split; refl theorem zip_map_left (f : α → γ) (l₁ : list α) (l₂ : list β) : zip (l₁.map f) l₂ = (zip l₁ l₂).map (prod.map f id) := by rw [← zip_map, map_id] theorem zip_map_right (f : β → γ) (l₁ : list α) (l₂ : list β) : zip l₁ (l₂.map f) = (zip l₁ l₂).map (prod.map id f) := by rw [← zip_map, map_id] @[simp] lemma zip_with_map {μ} (f : γ → δ → μ) (g : α → γ) (h : β → δ) (as : list α) (bs : list β) : zip_with f (as.map g) (bs.map h) = zip_with (λ a b, f (g a) (h b)) as bs := begin induction as generalizing bs, { simp }, { cases bs; simp * } end lemma zip_with_map_left (f : α → β → γ) (g : δ → α) (l : list δ) (l' : list β) : zip_with f (l.map g) l' = zip_with (f ∘ g) l l' := by { convert (zip_with_map f g id l l'), exact eq.symm (list.map_id _) } lemma zip_with_map_right (f : α → β → γ) (l : list α) (g : δ → β) (l' : list δ) : zip_with f l (l'.map g) = zip_with (λ x, f x ∘ g) l l' := by { convert (list.zip_with_map f id g l l'), exact eq.symm (list.map_id _) } theorem zip_map' (f : α → β) (g : α → γ) : ∀ (l : list α), zip (l.map f) (l.map g) = l.map (λ a, (f a, g a)) | [] := rfl | (a::l) := by simp only [map, zip_cons_cons, zip_map' l]; split; refl lemma map_zip_with {δ : Type*} (f : α → β) (g : γ → δ → α) (l : list γ) (l' : list δ) : map f (zip_with g l l') = zip_with (λ x y, f (g x y)) l l' := begin induction l with hd tl hl generalizing l', { simp }, { cases l', { simp }, { simp [hl] } } end theorem mem_zip {a b} : ∀ {l₁ : list α} {l₂ : list β}, (a, b) ∈ zip l₁ l₂ → a ∈ l₁ ∧ b ∈ l₂ | (_::l₁) (_::l₂) (or.inl rfl) := ⟨or.inl rfl, or.inl rfl⟩ | (a'::l₁) (b'::l₂) (or.inr h) := by split; simp only [mem_cons_iff, or_true, mem_zip h] theorem map_fst_zip : ∀ (l₁ : list α) (l₂ : list β), l₁.length ≤ l₂.length → map prod.fst (zip l₁ l₂) = l₁ | [] bs _ := rfl | (a :: as) (b :: bs) h := by { simp at h, simp! * } | (a :: as) [] h := by { simp at h, contradiction } theorem map_snd_zip : ∀ (l₁ : list α) (l₂ : list β), l₂.length ≤ l₁.length → map prod.snd (zip l₁ l₂) = l₂ | _ [] _ := by { rw zip_nil_right, refl } | [] (b :: bs) h := by { simp at h, contradiction } | (a :: as) (b :: bs) h := by { simp at h, simp! * } @[simp] theorem unzip_nil : unzip (@nil (α × β)) = ([], []) := rfl @[simp] theorem unzip_cons (a : α) (b : β) (l : list (α × β)) : unzip ((a, b) :: l) = (a :: (unzip l).1, b :: (unzip l).2) := by rw unzip; cases unzip l; refl theorem unzip_eq_map : ∀ (l : list (α × β)), unzip l = (l.map prod.fst, l.map prod.snd) | [] := rfl | ((a, b) :: l) := by simp only [unzip_cons, map_cons, unzip_eq_map l] theorem unzip_left (l : list (α × β)) : (unzip l).1 = l.map prod.fst := by simp only [unzip_eq_map] theorem unzip_right (l : list (α × β)) : (unzip l).2 = l.map prod.snd := by simp only [unzip_eq_map] theorem unzip_swap (l : list (α × β)) : unzip (l.map prod.swap) = (unzip l).swap := by simp only [unzip_eq_map, map_map]; split; refl theorem zip_unzip : ∀ (l : list (α × β)), zip (unzip l).1 (unzip l).2 = l | [] := rfl | ((a, b) :: l) := by simp only [unzip_cons, zip_cons_cons, zip_unzip l]; split; refl theorem unzip_zip_left : ∀ {l₁ : list α} {l₂ : list β}, length l₁ ≤ length l₂ → (unzip (zip l₁ l₂)).1 = l₁ | [] l₂ h := rfl | l₁ [] h := by rw eq_nil_of_length_eq_zero (nat.eq_zero_of_le_zero h); refl | (a::l₁) (b::l₂) h := by simp only [zip_cons_cons, unzip_cons, unzip_zip_left (le_of_succ_le_succ h)]; split; refl theorem unzip_zip_right {l₁ : list α} {l₂ : list β} (h : length l₂ ≤ length l₁) : (unzip (zip l₁ l₂)).2 = l₂ := by rw [← zip_swap, unzip_swap]; exact unzip_zip_left h theorem unzip_zip {l₁ : list α} {l₂ : list β} (h : length l₁ = length l₂) : unzip (zip l₁ l₂) = (l₁, l₂) := by rw [← @prod.mk.eta _ _ (unzip (zip l₁ l₂)), unzip_zip_left (le_of_eq h), unzip_zip_right (ge_of_eq h)] lemma zip_of_prod {l : list α} {l' : list β} {lp : list (α × β)} (hl : lp.map prod.fst = l) (hr : lp.map prod.snd = l') : lp = l.zip l' := by rw [←hl, ←hr, ←zip_unzip lp, ←unzip_left, ←unzip_right, zip_unzip, zip_unzip] lemma map_prod_left_eq_zip {l : list α} (f : α → β) : l.map (λ x, (x, f x)) = l.zip (l.map f) := by { rw ←zip_map', congr, exact map_id _ } lemma map_prod_right_eq_zip {l : list α} (f : α → β) : l.map (λ x, (f x, x)) = (l.map f).zip l := by { rw ←zip_map', congr, exact map_id _ } lemma zip_with_comm (f : α → α → β) (comm : ∀ (x y : α), f x y = f y x) (l l' : list α) : zip_with f l l' = zip_with f l' l := begin induction l with hd tl hl generalizing l', { simp }, { cases l', { simp }, { simp [comm, hl] } } end instance (f : α → α → β) [is_symm_op α β f] : is_symm_op (list α) (list β) (zip_with f) := ⟨zip_with_comm f is_symm_op.symm_op⟩ @[simp] theorem length_revzip (l : list α) : length (revzip l) = length l := by simp only [revzip, length_zip, length_reverse, min_self] @[simp] theorem unzip_revzip (l : list α) : (revzip l).unzip = (l, l.reverse) := unzip_zip (length_reverse l).symm @[simp] theorem revzip_map_fst (l : list α) : (revzip l).map prod.fst = l := by rw [← unzip_left, unzip_revzip] @[simp] theorem revzip_map_snd (l : list α) : (revzip l).map prod.snd = l.reverse := by rw [← unzip_right, unzip_revzip] theorem reverse_revzip (l : list α) : reverse l.revzip = revzip l.reverse := by rw [← zip_unzip.{u u} (revzip l).reverse, unzip_eq_map]; simp; simp [revzip] theorem revzip_swap (l : list α) : (revzip l).map prod.swap = revzip l.reverse := by simp [revzip] lemma nth_zip_with (f : α → β → γ) (l₁ : list α) (l₂ : list β) (i : ℕ) : (zip_with f l₁ l₂).nth i = ((l₁.nth i).map f).bind (λ g, (l₂.nth i).map g) := begin induction l₁ generalizing l₂ i, { simp [zip_with, (<*>)] }, { cases l₂; simp only [zip_with, has_seq.seq, functor.map, nth, option.map_none'], { cases ((l₁_hd :: l₁_tl).nth i); refl }, { cases i; simp only [option.map_some', nth, option.some_bind', *] } } end lemma nth_zip_with_eq_some {α β γ} (f : α → β → γ) (l₁ : list α) (l₂ : list β) (z : γ) (i : ℕ) : (zip_with f l₁ l₂).nth i = some z ↔ ∃ x y, l₁.nth i = some x ∧ l₂.nth i = some y ∧ f x y = z := begin induction l₁ generalizing l₂ i, { simp [zip_with] }, { cases l₂; simp only [zip_with, nth, exists_false, and_false, false_and], cases i; simp *, }, end lemma nth_zip_eq_some (l₁ : list α) (l₂ : list β) (z : α × β) (i : ℕ) : (zip l₁ l₂).nth i = some z ↔ l₁.nth i = some z.1 ∧ l₂.nth i = some z.2 := begin cases z, rw [zip, nth_zip_with_eq_some], split, { rintro ⟨x, y, h₀, h₁, h₂⟩, cc }, { rintro ⟨h₀, h₁⟩, exact ⟨_,_,h₀,h₁,rfl⟩ } end @[simp] lemma nth_le_zip_with {f : α → β → γ} {l : list α} {l' : list β} {i : ℕ} {h : i < (zip_with f l l').length} : (zip_with f l l').nth_le i h = f (l.nth_le i (lt_length_left_of_zip_with h)) (l'.nth_le i (lt_length_right_of_zip_with h)) := begin rw [←option.some_inj, ←nth_le_nth, nth_zip_with_eq_some], refine ⟨l.nth_le i (lt_length_left_of_zip_with h), l'.nth_le i (lt_length_right_of_zip_with h), nth_le_nth _, _⟩, simp only [←nth_le_nth, eq_self_iff_true, and_self] end @[simp] lemma nth_le_zip {l : list α} {l' : list β} {i : ℕ} {h : i < (zip l l').length} : (zip l l').nth_le i h = (l.nth_le i (lt_length_left_of_zip h), l'.nth_le i (lt_length_right_of_zip h)) := nth_le_zip_with lemma mem_zip_inits_tails {l : list α} {init tail : list α} : (init, tail) ∈ zip l.inits l.tails ↔ init ++ tail = l := begin induction l generalizing init tail; simp_rw [tails, inits, zip_cons_cons], { simp }, { split; rw [mem_cons_iff, zip_map_left, mem_map, prod.exists], { rintros (⟨rfl, rfl⟩ | ⟨_, _, h, rfl, rfl⟩), { simp }, { simp [l_ih.mp h], }, }, { cases init, { simp }, { intro h, right, use [init_tl, tail], simp * at *, }, }, }, end lemma map_uncurry_zip_eq_zip_with (f : α → β → γ) (l : list α) (l' : list β) : map (function.uncurry f) (l.zip l') = zip_with f l l' := begin induction l with hd tl hl generalizing l', { simp }, { cases l' with hd' tl', { simp }, { simp [hl] } } end @[simp] lemma sum_zip_with_distrib_left {γ : Type*} [semiring γ] (f : α → β → γ) (n : γ) (l : list α) (l' : list β) : (l.zip_with (λ x y, n * f x y) l').sum = n * (l.zip_with f l').sum := begin induction l with hd tl hl generalizing f n l', { simp }, { cases l' with hd' tl', { simp, }, { simp [hl, mul_add] } } end section distrib /-! ### Operations that can be applied before or after a `zip_with` -/ variables (f : α → β → γ) (l : list α) (l' : list β) (n : ℕ) lemma zip_with_distrib_take : (zip_with f l l').take n = zip_with f (l.take n) (l'.take n) := begin induction l with hd tl hl generalizing l' n, { simp }, { cases l', { simp }, { cases n, { simp }, { simp [hl] } } } end lemma zip_with_distrib_drop : (zip_with f l l').drop n = zip_with f (l.drop n) (l'.drop n) := begin induction l with hd tl hl generalizing l' n, { simp }, { cases l', { simp }, { cases n, { simp }, { simp [hl] } } } end lemma zip_with_distrib_tail : (zip_with f l l').tail = zip_with f l.tail l'.tail := by simp_rw [←drop_one, zip_with_distrib_drop] lemma zip_with_append (f : α → β → γ) (l la : list α) (l' lb : list β) (h : l.length = l'.length) : zip_with f (l ++ la) (l' ++ lb) = zip_with f l l' ++ zip_with f la lb := begin induction l with hd tl hl generalizing l', { have : l' = [] := eq_nil_of_length_eq_zero (by simpa using h.symm), simp [this], }, { cases l', { simpa using h }, { simp only [add_left_inj, length] at h, simp [hl _ h] } } end lemma zip_with_distrib_reverse (h : l.length = l'.length) : (zip_with f l l').reverse = zip_with f l.reverse l'.reverse := begin induction l with hd tl hl generalizing l', { simp }, { cases l' with hd' tl', { simp }, { simp only [add_left_inj, length] at h, have : tl.reverse.length = tl'.reverse.length := by simp [h], simp [hl _ h, zip_with_append _ _ _ _ _ this] } } end end distrib section comm_monoid variables [comm_monoid α] @[to_additive] lemma prod_mul_prod_eq_prod_zip_with_mul_prod_drop : ∀ (L L' : list α), L.prod * L'.prod = (zip_with (*) L L').prod * (L.drop L'.length).prod * (L'.drop L.length).prod | [] ys := by simp | xs [] := by simp | (x :: xs) (y :: ys) := begin simp only [drop, length, zip_with_cons_cons, prod_cons], rw [mul_assoc x, mul_comm xs.prod, mul_assoc y, mul_comm ys.prod, prod_mul_prod_eq_prod_zip_with_mul_prod_drop xs ys, mul_assoc, mul_assoc, mul_assoc, mul_assoc] end @[to_additive] lemma prod_mul_prod_eq_prod_zip_with_of_length_eq (L L' : list α) (h : L.length = L'.length) : L.prod * L'.prod = (zip_with (*) L L').prod := (prod_mul_prod_eq_prod_zip_with_mul_prod_drop L L').trans (by simp [h]) end comm_monoid end list
a30db2864b010f9834760225201c67bd44204881
4fa161becb8ce7378a709f5992a594764699e268
/src/analysis/convex/cone.lean
74e490e4618dc769ac79537c7c9ca5f7eefaf807
[ "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
18,763
lean
/- Copyright (c) 2020 Yury Kudryashov All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import linear_algebra.linear_pmap import analysis.convex.basic import order.zorn /-! # Convex cones In a vector space `E` over `ℝ`, we define a convex cone as a subset `s` such that `a • x + b • y ∈ s` whenever `x, y ∈ s` and `a, b > 0`. We prove that convex cones form a `complete_lattice`, and define their images (`convex_cone.map`) and preimages (`convex_cone.comap`) under linear maps. We also define `convex.to_cone` to be the minimal cone that includes a given convex set. ## Main statements We prove two extension theorems: * `riesz_extension`: [M. Riesz extension theorem](https://en.wikipedia.org/wiki/M._Riesz_extension_theorem) says that if `s` is a convex cone in a real vector space `E`, `p` is a submodule of `E` such that `p + s = E`, and `f` is a linear function `p → ℝ` which is nonnegative on `p ∩ s`, then there exists a globally defined linear function `g : E → ℝ` that agrees with `f` on `p`, and is nonnegative on `s`. * `exists_extension_of_le_sublinear`: Hahn-Banach theorem: if `N : E → ℝ` is a sublinear map, `f` is a linear map defined on a subspace of `E`, and `f x ≤ N x` for all `x` in the domain of `f`, then `f` can be extended to the whole space to a linear map `g` such that `g x ≤ N x` for all `x` ## Implementation notes While `convex` is a predicate on sets, `convex_cone` is a bundled convex cone. ## TODO * Define predicates `blunt`, `pointed`, `flat`, `sailent`, see [Wikipedia](https://en.wikipedia.org/wiki/Convex_cone#Blunt,_pointed,_flat,_salient,_and_proper_cones) * Define the dual cone. -/ universes u v open set linear_map open_locale classical variables (E : Type*) [add_comm_group E] [vector_space ℝ E] {F : Type*} [add_comm_group F] [vector_space ℝ F] {G : Type*} [add_comm_group G] [vector_space ℝ G] /-! ### Definition of `convex_cone` and basic properties -/ /-- A convex cone is a subset `s` of a vector space over `ℝ` such that `a • x + b • y ∈ s` whenever `a, b > 0` and `x, y ∈ s`. -/ structure convex_cone := (carrier : set E) (smul_mem' : ∀ ⦃c : ℝ⦄, 0 < c → ∀ ⦃x : E⦄, x ∈ carrier → c • x ∈ carrier) (add_mem' : ∀ ⦃x⦄ (hx : x ∈ carrier) ⦃y⦄ (hy : y ∈ carrier), x + y ∈ carrier) variable {E} namespace convex_cone variables (S T : convex_cone E) instance : has_coe (convex_cone E) (set E) := ⟨convex_cone.carrier⟩ instance : has_mem E (convex_cone E) := ⟨λ m S, m ∈ S.carrier⟩ instance : has_le (convex_cone E) := ⟨λ S T, S.carrier ⊆ T.carrier⟩ instance : has_lt (convex_cone E) := ⟨λ S T, S.carrier ⊂ T.carrier⟩ @[simp, norm_cast] lemma mem_coe {x : E} : x ∈ (S : set E) ↔ x ∈ S := iff.rfl @[simp] lemma mem_mk {s : set E} {h₁ h₂ x} : x ∈ mk s h₁ h₂ ↔ x ∈ s := iff.rfl /-- Two `convex_cone`s are equal if the underlying subsets are equal. -/ theorem ext' {S T : convex_cone E} (h : (S : set E) = T) : S = T := by cases S; cases T; congr' /-- Two `convex_cone`s are equal if and only if the underlying subsets are equal. -/ protected theorem ext'_iff {S T : convex_cone E} : (S : set E) = T ↔ S = T := ⟨ext', λ h, h ▸ rfl⟩ /-- Two `convex_cone`s are equal if they have the same elements. -/ @[ext] theorem ext {S T : convex_cone E} (h : ∀ x, x ∈ S ↔ x ∈ T) : S = T := ext' $ set.ext h lemma smul_mem {c : ℝ} {x : E} (hc : 0 < c) (hx : x ∈ S) : c • x ∈ S := S.smul_mem' hc hx lemma add_mem ⦃x⦄ (hx : x ∈ S) ⦃y⦄ (hy : y ∈ S) : x + y ∈ S := S.add_mem' hx hy lemma smul_mem_iff {c : ℝ} (hc : 0 < c) {x : E} : c • x ∈ S ↔ x ∈ S := ⟨λ h, by simpa only [smul_smul, inv_mul_cancel (ne_of_gt hc), one_smul] using S.smul_mem (inv_pos.2 hc) h, λ h, S.smul_mem hc h⟩ lemma convex : convex (S : set E) := convex_iff_forall_pos.2 $ λ x y hx hy a b ha hb hab, S.add_mem (S.smul_mem ha hx) (S.smul_mem hb hy) instance : has_inf (convex_cone E) := ⟨λ S T, ⟨S ∩ T, λ c hc x hx, ⟨S.smul_mem hc hx.1, T.smul_mem hc hx.2⟩, λ x hx y hy, ⟨S.add_mem hx.1 hy.1, T.add_mem hx.2 hy.2⟩⟩⟩ lemma coe_inf : ((S ⊓ T : convex_cone E) : set E) = ↑S ∩ ↑T := rfl lemma mem_inf {x} : x ∈ S ⊓ T ↔ x ∈ S ∧ x ∈ T := iff.rfl instance : has_Inf (convex_cone E) := ⟨λ S, ⟨⋂ s ∈ S, ↑s, λ c hc x hx, mem_bInter $ λ s hs, s.smul_mem hc $ by apply mem_bInter_iff.1 hx s hs, λ x hx y hy, mem_bInter $ λ s hs, s.add_mem (by apply mem_bInter_iff.1 hx s hs) (by apply mem_bInter_iff.1 hy s hs)⟩⟩ lemma mem_Inf {x : E} {S : set (convex_cone E)} : x ∈ Inf S ↔ ∀ s ∈ S, x ∈ s := mem_bInter_iff instance : has_bot (convex_cone E) := ⟨⟨∅, λ c hc x, false.elim, λ x, false.elim⟩⟩ lemma mem_bot (x : E) : x ∈ (⊥ : convex_cone E) = false := rfl instance : has_top (convex_cone E) := ⟨⟨univ, λ c hc x hx, mem_univ _, λ x hx y hy, mem_univ _⟩⟩ lemma mem_top (x : E) : x ∈ (⊤ : convex_cone E) := mem_univ x instance : complete_lattice (convex_cone E) := { le := (≤), lt := (<), bot := (⊥), bot_le := λ S x, false.elim, top := (⊤), le_top := λ S x hx, mem_top x, inf := (⊓), Inf := has_Inf.Inf, sup := λ a b, Inf {x | a ≤ x ∧ b ≤ x}, Sup := λ s, Inf {T | ∀ S ∈ s, S ≤ T}, le_sup_left := λ a b, λ x hx, mem_Inf.2 $ λ s hs, hs.1 hx, le_sup_right := λ a b, λ x hx, mem_Inf.2 $ λ s hs, hs.2 hx, sup_le := λ a b c ha hb x hx, mem_Inf.1 hx c ⟨ha, hb⟩, le_inf := λ a b c ha hb x hx, ⟨ha hx, hb hx⟩, inf_le_left := λ a b x, and.left, inf_le_right := λ a b x, and.right, le_Sup := λ s p hs x hx, mem_Inf.2 $ λ t ht, ht p hs hx, Sup_le := λ s p hs x hx, mem_Inf.1 hx p hs, le_Inf := λ s a ha x hx, mem_Inf.2 $ λ t ht, ha t ht hx, Inf_le := λ s a ha x hx, mem_Inf.1 hx _ ha, .. partial_order.lift (coe : convex_cone E → set E) (λ a b, ext') } instance : inhabited (convex_cone E) := ⟨⊥⟩ /-- The image of a convex cone under an `ℝ`-linear map is a convex cone. -/ def map (f : E →ₗ[ℝ] F) (S : convex_cone E) : convex_cone F := { carrier := f '' S, smul_mem' := λ c hc y ⟨x, hx, hy⟩, hy ▸ f.map_smul c x ▸ mem_image_of_mem f (S.smul_mem hc hx), add_mem' := λ y₁ ⟨x₁, hx₁, hy₁⟩ y₂ ⟨x₂, hx₂, hy₂⟩, hy₁ ▸ hy₂ ▸ f.map_add x₁ x₂ ▸ mem_image_of_mem f (S.add_mem hx₁ hx₂) } lemma map_map (g : F →ₗ[ℝ] G) (f : E →ₗ[ℝ] F) (S : convex_cone E) : (S.map f).map g = S.map (g.comp f) := ext' $ image_image g f S @[simp] lemma map_id : S.map linear_map.id = S := ext' $ image_id _ /-- The preimage of a convex cone under an `ℝ`-linear map is a convex cone. -/ def comap (f : E →ₗ[ℝ] F) (S : convex_cone F) : convex_cone E := { carrier := f ⁻¹' S, smul_mem' := λ c hc x hx, by { rw [mem_preimage, f.map_smul c], exact S.smul_mem hc hx }, add_mem' := λ x hx y hy, by { rw [mem_preimage, f.map_add], exact S.add_mem hx hy } } @[simp] lemma comap_id : S.comap linear_map.id = S := ext' preimage_id lemma comap_comap (g : F →ₗ[ℝ] G) (f : E →ₗ[ℝ] F) (S : convex_cone G) : (S.comap g).comap f = S.comap (g.comp f) := ext' $ preimage_comp.symm @[simp] lemma mem_comap {f : E →ₗ[ℝ] F} {S : convex_cone F} {x : E} : x ∈ S.comap f ↔ f x ∈ S := iff.rfl end convex_cone /-! ### Cone over a convex set -/ namespace convex local attribute [instance] smul_set /-- The set of vectors proportional to those in a convex set forms a convex cone. -/ def to_cone (s : set E) (hs : convex s) : convex_cone E := begin apply convex_cone.mk (⋃ c > 0, (c : ℝ) • s); simp only [mem_Union, mem_smul_set], { rintros c c_pos _ ⟨c', c'_pos, x, hx, rfl⟩, exact ⟨c * c', mul_pos c_pos c'_pos, x, hx, smul_smul _ _ _⟩ }, { rintros _ ⟨cx, cx_pos, x, hx, rfl⟩ _ ⟨cy, cy_pos, y, hy, rfl⟩, have : 0 < cx + cy, from add_pos cx_pos cy_pos, refine ⟨_, this, _, convex_iff_div.1 hs hx hy (le_of_lt cx_pos) (le_of_lt cy_pos) this, _⟩, simp only [smul_add, smul_smul, mul_div_assoc', mul_div_cancel_left _ (ne_of_gt this)] } end variables {s : set E} (hs : convex s) {x : E} @[nolint ge_or_gt] lemma mem_to_cone : x ∈ hs.to_cone s ↔ ∃ (c > 0) (y ∈ s), (c : ℝ) • y = x := by simp only [to_cone, convex_cone.mem_mk, mem_Union, mem_smul_set, eq_comm] @[nolint ge_or_gt] lemma mem_to_cone' : x ∈ hs.to_cone s ↔ ∃ c > 0, (c : ℝ) • x ∈ s := begin refine hs.mem_to_cone.trans ⟨_, _⟩, { rintros ⟨c, hc, y, hy, rfl⟩, exact ⟨c⁻¹, inv_pos.2 hc, by rwa [smul_smul, inv_mul_cancel (ne_of_gt hc), one_smul]⟩ }, { rintros ⟨c, hc, hcx⟩, exact ⟨c⁻¹, inv_pos.2 hc, _, hcx, by rw [smul_smul, inv_mul_cancel (ne_of_gt hc), one_smul]⟩ } end lemma subset_to_cone : s ⊆ hs.to_cone s := λ x hx, hs.mem_to_cone'.2 ⟨1, zero_lt_one, by rwa one_smul⟩ /-- `hs.to_cone s` is the least cone that includes `s`. -/ lemma to_cone_is_least : is_least { t : convex_cone E | s ⊆ t } (hs.to_cone s) := begin refine ⟨hs.subset_to_cone, λ t ht x hx, _⟩, rcases hs.mem_to_cone.1 hx with ⟨c, hc, y, hy, rfl⟩, exact t.smul_mem hc (ht hy) end lemma to_cone_eq_Inf : hs.to_cone s = Inf { t : convex_cone E | s ⊆ t } := hs.to_cone_is_least.is_glb.Inf_eq.symm end convex lemma convex_hull_to_cone_is_least (s : set E) : is_least {t : convex_cone E | s ⊆ t} ((convex_convex_hull s).to_cone _) := begin convert (convex_convex_hull s).to_cone_is_least, ext t, exact ⟨λ h, convex_hull_min h t.convex, λ h, subset.trans (subset_convex_hull s) h⟩ end lemma convex_hull_to_cone_eq_Inf (s : set E) : (convex_convex_hull s).to_cone _ = Inf {t : convex_cone E | s ⊆ t} := (convex_hull_to_cone_is_least s).is_glb.Inf_eq.symm /-! ### M. Riesz extension theorem Given a convex cone `s` in a vector space `E`, a submodule `p`, and a linear `f : p → ℝ`, assume that `f` is nonnegative on `p ∩ s` and `p + s = E`. Then there exists a globally defined linear function `g : E → ℝ` that agrees with `f` on `p`, and is nonnegative on `s`. We prove this theorem using Zorn's lemma. `riesz_extension.step` is the main part of the proof. It says that if the domain `p` of `f` is not the whole space, then `f` can be extended to a larger subspace `p ⊔ span ℝ {y}` without breaking the non-negativity condition. In `riesz_extension.exists_top` we use Zorn's lemma to prove that we can extend `f` to a linear map `g` on `⊤ : submodule E`. Mathematically this is the same as a linear map on `E` but in Lean `⊤ : submodule E` is isomorphic but is not equal to `E`. In `riesz_extension` we use this isomorphism to prove the theorem. -/ namespace riesz_extension open submodule variables (s : convex_cone E) (f : linear_pmap ℝ E ℝ) /-- Induction step in M. Riesz extension theorem. Given a convex cone `s` in a vector space `E`, a partially defined linear map `f : f.domain → ℝ`, assume that `f` is nonnegative on `f.domain ∩ p` and `p + s = E`. If `f` is not defined on the whole `E`, then we can extend it to a larger submodule without breaking the non-negativity condition. -/ lemma step (nonneg : ∀ x : f.domain, (x : E) ∈ s → 0 ≤ f x) (dense : ∀ y, ∃ x : f.domain, (x : E) + y ∈ s) (hdom : f.domain ≠ ⊤) : ∃ g, f < g ∧ ∀ x : g.domain, (x : E) ∈ s → 0 ≤ g x := begin rcases exists_of_lt (lt_top_iff_ne_top.2 hdom) with ⟨y, hy', hy⟩, clear hy', obtain ⟨c, le_c, c_le⟩ : ∃ c, (∀ x : f.domain, -(x:E) - y ∈ s → f x ≤ c) ∧ (∀ x : f.domain, (x:E) + y ∈ s → c ≤ f x), { set Sp := f '' {x : f.domain | (x:E) + y ∈ s}, set Sn := f '' {x : f.domain | -(x:E) - y ∈ s}, suffices : (upper_bounds Sn ∩ lower_bounds Sp).nonempty, by simpa only [set.nonempty, upper_bounds, lower_bounds, ball_image_iff] using this, refine exists_between_of_forall_le (nonempty.image f _) (nonempty.image f (dense y)) _, { rcases (dense (-y)) with ⟨x, hx⟩, rw [← neg_neg x, coe_neg] at hx, exact ⟨_, hx⟩ }, rintros a ⟨xn, hxn, rfl⟩ b ⟨xp, hxp, rfl⟩, have := s.add_mem hxp hxn, rw [add_assoc, add_sub_cancel'_right, ← sub_eq_add_neg, ← coe_sub] at this, replace := nonneg _ this, rwa [f.map_sub, sub_nonneg] at this }, have hy' : y ≠ 0, from λ hy₀, hy (hy₀.symm ▸ zero_mem _), refine ⟨f.sup (linear_pmap.mk_span_singleton y (-c) hy') _, _, _⟩, { refine linear_pmap.sup_h_of_disjoint _ _ (disjoint_span_singleton.2 _), exact (λ h, (hy h).elim) }, { refine lt_iff_le_not_le.2 ⟨f.left_le_sup _ _, λ H, _⟩, replace H := linear_pmap.domain_mono.monotone H, rw [linear_pmap.domain_sup, linear_pmap.domain_mk_span_singleton, sup_le_iff, span_le, singleton_subset_iff] at H, exact hy H.2 }, { rintros ⟨z, hz⟩ hzs, rcases mem_sup.1 hz with ⟨x, hx, y', hy', rfl⟩, rcases mem_span_singleton.1 hy' with ⟨r, rfl⟩, simp only [subtype.coe_mk] at hzs, rw [linear_pmap.sup_apply _ ⟨x, hx⟩ ⟨_, hy'⟩ ⟨_, hz⟩ rfl, linear_pmap.mk_span_singleton_apply, smul_neg, ← sub_eq_add_neg, sub_nonneg], rcases lt_trichotomy r 0 with hr|hr|hr, { have : -(r⁻¹ • x) - y ∈ s, by rwa [← s.smul_mem_iff (neg_pos.2 hr), smul_sub, smul_neg, neg_smul, neg_neg, smul_smul, mul_inv_cancel (ne_of_lt hr), one_smul, sub_eq_add_neg, neg_smul, neg_neg], replace := le_c (r⁻¹ • ⟨x, hx⟩) this, rwa [← mul_le_mul_left (neg_pos.2 hr), ← neg_mul_eq_neg_mul, ← neg_mul_eq_neg_mul, neg_le_neg_iff, f.map_smul, smul_eq_mul, ← mul_assoc, mul_inv_cancel (ne_of_lt hr), one_mul] at this }, { subst r, simp only [zero_smul, add_zero] at hzs ⊢, apply nonneg, exact hzs }, { have : r⁻¹ • x + y ∈ s, by rwa [← s.smul_mem_iff hr, smul_add, smul_smul, mul_inv_cancel (ne_of_gt hr), one_smul], replace := c_le (r⁻¹ • ⟨x, hx⟩) this, rwa [← mul_le_mul_left hr, f.map_smul, smul_eq_mul, ← mul_assoc, mul_inv_cancel (ne_of_gt hr), one_mul] at this } } end @[nolint ge_or_gt] theorem exists_top (p : linear_pmap ℝ E ℝ) (hp_nonneg : ∀ x : p.domain, (x : E) ∈ s → 0 ≤ p x) (hp_dense : ∀ y, ∃ x : p.domain, (x : E) + y ∈ s) : ∃ q ≥ p, q.domain = ⊤ ∧ ∀ x : q.domain, (x : E) ∈ s → 0 ≤ q x := begin replace hp_nonneg : p ∈ { p | _ }, by { rw mem_set_of_eq, exact hp_nonneg }, obtain ⟨q, hqs, hpq, hq⟩ := zorn.zorn_partial_order₀ _ _ _ hp_nonneg, { refine ⟨q, hpq, _, hqs⟩, contrapose! hq, rcases step s q hqs _ hq with ⟨r, hqr, hr⟩, { exact ⟨r, hr, le_of_lt hqr, ne_of_gt hqr⟩ }, { exact λ y, let ⟨x, hx⟩ := hp_dense y in ⟨of_le hpq.left x, hx⟩ } }, { intros c hcs c_chain y hy, clear hp_nonneg hp_dense p, have cne : c.nonempty := ⟨y, hy⟩, refine ⟨linear_pmap.Sup c c_chain.directed_on, _, λ _, linear_pmap.le_Sup c_chain.directed_on⟩, rintros ⟨x, hx⟩ hxs, have hdir : directed_on (≤) (linear_pmap.domain '' c), from (directed_on_image _).2 (c_chain.directed_on.mono _ linear_pmap.domain_mono.monotone), rcases (mem_Sup_of_directed (cne.image _) hdir).1 hx with ⟨_, ⟨f, hfc, rfl⟩, hfx⟩, have : f ≤ linear_pmap.Sup c c_chain.directed_on, from linear_pmap.le_Sup _ hfc, convert ← hcs hfc ⟨x, hfx⟩ hxs, apply this.2, refl } end end riesz_extension /-- M. Riesz extension theorem: given a convex cone `s` in a vector space `E`, a submodule `p`, and a linear `f : p → ℝ`, assume that `f` is nonnegative on `p ∩ s` and `p + s = E`. Then there exists a globally defined linear function `g : E → ℝ` that agrees with `f` on `p`, and is nonnegative on `s`. -/ theorem riesz_extension (s : convex_cone E) (f : linear_pmap ℝ E ℝ) (nonneg : ∀ x : f.domain, (x : E) ∈ s → 0 ≤ f x) (dense : ∀ y, ∃ x : f.domain, (x : E) + y ∈ s) : ∃ g : E →ₗ[ℝ] ℝ, (∀ x : f.domain, g x = f x) ∧ (∀ x ∈ s, 0 ≤ g x) := begin rcases riesz_extension.exists_top s f nonneg dense with ⟨⟨g_dom, g⟩, ⟨hpg, hfg⟩, htop, hgs⟩, clear hpg, refine ⟨g.comp (linear_equiv.of_top _ htop).symm, _, _⟩; simp only [comp_apply, linear_equiv.coe_coe, linear_equiv.of_top_symm_apply], { exact λ x, (hfg (submodule.coe_mk _ _).symm).symm }, { exact λ x hx, hgs ⟨x, _⟩ hx } end /-- Hahn-Banach theorem: if `N : E → ℝ` is a sublinear map, `f` is a linear map defined on a subspace of `E`, and `f x ≤ N x` for all `x` in the domain of `f`, then `f` can be extended to the whole space to a linear map `g` such that `g x ≤ N x` for all `x`. -/ theorem exists_extension_of_le_sublinear (f : linear_pmap ℝ E ℝ) (N : E → ℝ) (N_hom : ∀ (c : ℝ), 0 < c → ∀ x, N (c • x) = c * N x) (N_add : ∀ x y, N (x + y) ≤ N x + N y) (hf : ∀ x : f.domain, f x ≤ N x) : ∃ g : E →ₗ[ℝ] ℝ, (∀ x : f.domain, g x = f x) ∧ (∀ x, g x ≤ N x) := begin let s : convex_cone (E × ℝ) := { carrier := {p : E × ℝ | N p.1 ≤ p.2 }, smul_mem' := λ c hc p hp, calc N (c • p.1) = c * N p.1 : N_hom c hc p.1 ... ≤ c * p.2 : mul_le_mul_of_nonneg_left hp (le_of_lt hc), add_mem' := λ x hx y hy, le_trans (N_add _ _) (add_le_add hx hy) }, obtain ⟨g, g_eq, g_nonneg⟩ := riesz_extension s ((-f).coprod (linear_map.id.to_pmap ⊤)) _ _; simp only [linear_pmap.coprod_apply, to_pmap_apply, id_apply, linear_pmap.neg_apply, ← sub_eq_neg_add, sub_nonneg, subtype.coe_mk] at *, replace g_eq : ∀ (x : f.domain) (y : ℝ), g (x, y) = y - f x, { intros x y, simpa only [subtype.coe_mk, subtype.coe_eta] using g_eq ⟨(x, y), ⟨x.2, trivial⟩⟩ }, { refine ⟨-g.comp (inl ℝ E ℝ), _, _⟩; simp only [neg_apply, inl_apply, comp_apply], { intro x, simp [g_eq x 0] }, { intro x, have A : (x, N x) = (x, 0) + (0, N x), by simp, have B := g_nonneg ⟨x, N x⟩ (le_refl (N x)), rw [A, map_add, ← neg_le_iff_add_nonneg] at B, have C := g_eq 0 (N x), simp only [submodule.coe_zero, f.map_zero, sub_zero] at C, rwa ← C } }, { exact λ x hx, le_trans (hf _) hx }, { rintros ⟨x, y⟩, refine ⟨⟨(0, N x - y), ⟨f.domain.zero_mem, trivial⟩⟩, _⟩, simp only [convex_cone.mem_mk, mem_set_of_eq, subtype.coe_mk, prod.fst_add, prod.snd_add, zero_add, sub_add_cancel] } end
8a4fca12917a7bc9331fa57c35b28381ff1032c0
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/monoidal/limits.lean
930b3912659abcad2b80f7cadf0ef8bba4784394
[ "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
3,961
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.monoidal.functorial import category_theory.monoidal.functor_category import category_theory.limits.has_limits /-! # `lim : (J ⥤ C) ⥤ C` is lax monoidal when `C` is a monoidal category. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. When `C` is a monoidal category, the functorial association `F ↦ limit F` is lax monoidal, i.e. there are morphisms * `lim_lax.ε : (𝟙_ C) → limit (𝟙_ (J ⥤ C))` * `lim_lax.μ : limit F ⊗ limit G ⟶ limit (F ⊗ G)` satisfying the laws of a lax monoidal functor. -/ open category_theory open category_theory.monoidal_category namespace category_theory.limits universes v u noncomputable theory variables {J : Type v} [small_category J] variables {C : Type u} [category.{v} C] [has_limits C] instance limit_functorial : functorial (λ F : J ⥤ C, limit F) := { ..limits.lim } @[simp] lemma limit_functorial_map {F G : J ⥤ C} (α : F ⟶ G) : map (λ F : J ⥤ C, limit F) α = limits.lim.map α := rfl variables [monoidal_category.{v} C] @[simps] instance limit_lax_monoidal : lax_monoidal (λ F : J ⥤ C, limit F) := { ε := limit.lift _ { X := _, π := { app := λ j, 𝟙 _, } }, μ := λ F G, limit.lift (F ⊗ G) { X := limit F ⊗ limit G, π := { app := λ j, limit.π F j ⊗ limit.π G j, naturality' := λ j j' f, begin dsimp, simp only [category.id_comp, ←tensor_comp, limit.w], end, } }, μ_natural' := λ X Y X' Y' f g, begin ext, dsimp, simp only [limit.lift_π, cones.postcompose_obj_π, monoidal.tensor_hom_app, limit.lift_map, nat_trans.comp_app, category.assoc, ←tensor_comp, lim_map_π], end, associativity' := λ X Y Z, begin ext, dsimp, simp only [limit.lift_π, cones.postcompose_obj_π, monoidal.associator_hom_app, limit.lift_map, nat_trans.comp_app, category.assoc], slice_lhs 2 2 { rw [←tensor_id_comp_id_tensor], }, slice_lhs 1 2 { rw [←comp_tensor_id, limit.lift_π], dsimp, }, slice_lhs 1 2 { rw [tensor_id_comp_id_tensor], }, conv_lhs { rw [associator_naturality], }, conv_rhs { rw [←id_tensor_comp_tensor_id (limit.π (Y ⊗ Z) j)], }, slice_rhs 2 3 { rw [←id_tensor_comp, limit.lift_π], dsimp, }, dsimp, simp, end, left_unitality' := λ X, begin ext, dsimp, simp, conv_rhs { rw [←tensor_id_comp_id_tensor (limit.π X j)], }, slice_rhs 1 2 { rw [←comp_tensor_id], erw [limit.lift_π], dsimp, }, slice_rhs 2 3 { rw [left_unitor_naturality], }, simp, end, right_unitality' := λ X, begin ext, dsimp, simp, conv_rhs { rw [←id_tensor_comp_tensor_id _ (limit.π X j)], }, slice_rhs 1 2 { rw [←id_tensor_comp], erw [limit.lift_π], dsimp, }, slice_rhs 2 3 { rw [right_unitor_naturality], }, simp, end, } /-- The limit functor `F ↦ limit F` bundled as a lax monoidal functor. -/ def lim_lax : lax_monoidal_functor (J ⥤ C) C := lax_monoidal_functor.of (λ F : J ⥤ C, limit F) @[simp] lemma lim_lax_obj (F : J ⥤ C) : lim_lax.obj F = limit F := rfl lemma lim_lax_obj' (F : J ⥤ C) : lim_lax.obj F = lim.obj F := rfl @[simp] lemma lim_lax_map {F G : J ⥤ C} (α : F ⟶ G) : lim_lax.map α = lim.map α := rfl @[simp] lemma lim_lax_ε : (@lim_lax J _ C _ _ _).ε = limit.lift _ { X := _, π := { app := λ j, 𝟙 _, } } := rfl @[simp] lemma lim_lax_μ (F G : J ⥤ C) : (@lim_lax J _ C _ _ _).μ F G = limit.lift (F ⊗ G) { X := limit F ⊗ limit G, π := { app := λ j, limit.π F j ⊗ limit.π G j, naturality' := λ j j' f, begin dsimp, simp only [category.id_comp, ←tensor_comp, limit.w], end, } } := rfl end category_theory.limits
6842c9713255df2fd21554b28ca0bb1751f028b6
675b8263050a5d74b89ceab381ac81ce70535688
/src/data/real/ennreal.lean
e2fc19bfadff4482d8cd8ce93267d5b6698736e2
[ "Apache-2.0" ]
permissive
vozor/mathlib
5921f55235ff60c05f4a48a90d616ea167068adf
f7e728ad8a6ebf90291df2a4d2f9255a6576b529
refs/heads/master
1,675,607,702,231
1,609,023,279,000
1,609,023,279,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
55,948
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl, Yury Kudryashov -/ import data.real.nnreal import data.set.intervals /-! # Extended non-negative reals We define `ennreal := with_no ℝ≥0` to be the type of extended nonnegative real numbers, i.e., the interval `[0, +∞]`. This type is used as the codomain of a `measure_theory.measure`, and of the extended distance `edist` in a `emetric_space`. In this file we define some algebraic operations and a linear order on `ennreal` and prove basic properties of these operations, order, and conversions to/from `ℝ`, `ℝ≥0`, and `ℕ`. ## Main definitions * `ennreal`: the extended nonnegative real numbers `[0, ∞]`; defined as `with_top ℝ≥0`; it is equipped with the following structures: - coercion from `ℝ≥0` defined in the natural way; - the natural structure of a complete dense linear order: `↑p ≤ ↑q ↔ p ≤ q` and `∀ a, a ≤ ∞`; - `a + b` is defined so that `↑p + ↑q = ↑(p + q)` for `(p q : ℝ≥0)` and `a + ∞ = ∞ + a = ∞`; - `a * b` is defined so that `↑p * ↑q = ↑(p * q)` for `(p q : ℝ≥0)`, `0 * ∞ = ∞ * 0 = 0`, and `a * ∞ = ∞ * a = ∞` for `a ≠ 0`; - `a - b` is defined as the minimal `d` such that `a ≤ d + b`; this way we have `↑p - ↑q = ↑(p - q)`, `∞ - ↑p = ∞`, `↑p - ∞ = ∞ - ∞ = 0`; note that there is no negation, only subtraction; - `a⁻¹` is defined as `Inf {b | 1 ≤ a * b}`. This way we have `(↑p)⁻¹ = ↑(p⁻¹)` for `p : ℝ≥0`, `p ≠ 0`, `0⁻¹ = ∞`, and `∞⁻¹ = 0`. - `a / b` is defined as `a * b⁻¹`. The addition and multiplication defined this way together with `0 = ↑0` and `1 = ↑1` turn `ennreal` into a canonically ordered commutative semiring of characteristic zero. * Coercions to/from other types: - coercion `ℝ≥0 → ennreal` is defined as `has_coe`, so one can use `(p : ℝ≥0)` in a context that expects `a : ennreal`, and Lean will apply `coe` automatically; - `ennreal.to_nnreal` sends `↑p` to `p` and `∞` to `0`; - `ennreal.to_real := coe ∘ ennreal.to_nnreal` sends `↑p`, `p : ℝ≥0` to `(↑p : ℝ)` and `∞` to `0`; - `ennreal.of_real := coe ∘ nnreal.of_real` sends `x : ℝ` to `↑⟨max x 0, _⟩` - `ennreal.ne_top_equiv_nnreal` is an equivalence between `{a : ennreal // a ≠ 0}` and `ℝ≥0`. ## Implementation notes We define a `can_lift ennreal ℝ≥0` instance, so one of the ways to prove theorems about an `ennreal` number `a` is to consider the cases `a = ∞` and `a ≠ ∞`, and use the tactic `lift a to ℝ≥0 using ha` in the second case. This instance is even more useful if one already has `ha : a ≠ ∞` in the context, or if we have `(f : α → ennreal) (hf : ∀ x, f x ≠ ∞)`. ## Notations * `ℝ≥0`: type of nonnegative real numbers `[0, ∞)`; defined in `data.real.nnreal`; * `∞`: a localized notation in `ennreal` for `⊤ : ennreal`. -/ noncomputable theory open classical set open_locale classical big_operators nnreal variables {α : Type*} {β : Type*} /-- The extended nonnegative real numbers. This is usually denoted [0, ∞], and is relevant as the codomain of a measure. -/ @[derive canonically_ordered_comm_semiring, derive complete_linear_order, derive densely_ordered, derive nontrivial] def ennreal := with_top ℝ≥0 localized "notation `∞` := (⊤ : ennreal)" in ennreal namespace ennreal variables {a b c d : ennreal} {r p q : ℝ≥0} instance : inhabited ennreal := ⟨0⟩ instance : has_coe ℝ≥0 ennreal := ⟨ option.some ⟩ instance : can_lift ennreal ℝ≥0 := { coe := coe, cond := λ r, r ≠ ∞, prf := λ x hx, ⟨option.get $ option.ne_none_iff_is_some.1 hx, option.some_get _⟩ } @[simp] lemma none_eq_top : (none : ennreal) = ∞ := rfl @[simp] lemma some_eq_coe (a : ℝ≥0) : (some a : ennreal) = (↑a : ennreal) := rfl /-- `to_nnreal x` returns `x` if it is real, otherwise 0. -/ protected def to_nnreal : ennreal → ℝ≥0 | (some r) := r | none := 0 /-- `to_real x` returns `x` if it is real, `0` otherwise. -/ protected def to_real (a : ennreal) : real := coe (a.to_nnreal) /-- `of_real x` returns `x` if it is nonnegative, `0` otherwise. -/ protected def of_real (r : real) : ennreal := coe (nnreal.of_real r) @[simp, norm_cast] lemma to_nnreal_coe : (r : ennreal).to_nnreal = r := rfl @[simp] lemma coe_to_nnreal : ∀{a:ennreal}, a ≠ ∞ → ↑(a.to_nnreal) = a | (some r) h := rfl | none h := (h rfl).elim @[simp] lemma of_real_to_real {a : ennreal} (h : a ≠ ∞) : ennreal.of_real (a.to_real) = a := by simp [ennreal.to_real, ennreal.of_real, h] @[simp] lemma to_real_of_real {r : ℝ} (h : 0 ≤ r) : ennreal.to_real (ennreal.of_real r) = r := by simp [ennreal.to_real, ennreal.of_real, nnreal.coe_of_real _ h] lemma to_real_of_real' {r : ℝ} : ennreal.to_real (ennreal.of_real r) = max r 0 := rfl lemma coe_to_nnreal_le_self : ∀{a:ennreal}, ↑(a.to_nnreal) ≤ a | (some r) := by rw [some_eq_coe, to_nnreal_coe]; exact le_refl _ | none := le_top lemma coe_nnreal_eq (r : ℝ≥0) : (r : ennreal) = ennreal.of_real r := by { rw [ennreal.of_real, nnreal.of_real], cases r with r h, congr, dsimp, rw max_eq_left h } lemma of_real_eq_coe_nnreal {x : ℝ} (h : 0 ≤ x) : ennreal.of_real x = @coe ℝ≥0 ennreal _ (⟨x, h⟩ : ℝ≥0) := by { rw [coe_nnreal_eq], refl } @[simp] lemma of_real_coe_nnreal : ennreal.of_real p = p := (coe_nnreal_eq p).symm @[simp, norm_cast] lemma coe_zero : ↑(0 : ℝ≥0) = (0 : ennreal) := rfl @[simp, norm_cast] lemma coe_one : ↑(1 : ℝ≥0) = (1 : ennreal) := rfl @[simp] lemma to_real_nonneg {a : ennreal} : 0 ≤ a.to_real := by simp [ennreal.to_real] @[simp] lemma top_to_nnreal : ∞.to_nnreal = 0 := rfl @[simp] lemma top_to_real : ∞.to_real = 0 := rfl @[simp] lemma one_to_real : (1 : ennreal).to_real = 1 := rfl @[simp] lemma one_to_nnreal : (1 : ennreal).to_nnreal = 1 := rfl @[simp] lemma coe_to_real (r : ℝ≥0) : (r : ennreal).to_real = r := rfl @[simp] lemma zero_to_nnreal : (0 : ennreal).to_nnreal = 0 := rfl @[simp] lemma zero_to_real : (0 : ennreal).to_real = 0 := rfl @[simp] lemma of_real_zero : ennreal.of_real (0 : ℝ) = 0 := by simp [ennreal.of_real]; refl @[simp] lemma of_real_one : ennreal.of_real (1 : ℝ) = (1 : ennreal) := by simp [ennreal.of_real] lemma of_real_to_real_le {a : ennreal} : ennreal.of_real (a.to_real) ≤ a := if ha : a = ∞ then ha.symm ▸ le_top else le_of_eq (of_real_to_real ha) lemma forall_ennreal {p : ennreal → Prop} : (∀a, p a) ↔ (∀r:ℝ≥0, p r) ∧ p ∞ := ⟨assume h, ⟨assume r, h _, h _⟩, assume ⟨h₁, h₂⟩ a, match a with some r := h₁ _ | none := h₂ end⟩ lemma forall_ne_top {p : ennreal → Prop} : (∀ a ≠ ∞, p a) ↔ ∀ r : ℝ≥0, p r := option.ball_ne_none lemma exists_ne_top {p : ennreal → Prop} : (∃ a ≠ ∞, p a) ↔ ∃ r : ℝ≥0, p r := option.bex_ne_none lemma to_nnreal_eq_zero_iff (x : ennreal) : x.to_nnreal = 0 ↔ x = 0 ∨ x = ∞ := ⟨begin cases x, { simp [none_eq_top] }, { have A : some (0:ℝ≥0) = (0:ennreal) := rfl, simp [ennreal.to_nnreal, A] {contextual := tt} } end, by intro h; cases h; simp [h]⟩ lemma to_real_eq_zero_iff (x : ennreal) : x.to_real = 0 ↔ x = 0 ∨ x = ∞ := by simp [ennreal.to_real, to_nnreal_eq_zero_iff] @[simp] lemma coe_ne_top : (r : ennreal) ≠ ∞ := with_top.coe_ne_top @[simp] lemma top_ne_coe : ∞ ≠ (r : ennreal) := with_top.top_ne_coe @[simp] lemma of_real_ne_top {r : ℝ} : ennreal.of_real r ≠ ∞ := by simp [ennreal.of_real] @[simp] lemma of_real_lt_top {r : ℝ} : ennreal.of_real r < ∞ := lt_top_iff_ne_top.2 of_real_ne_top @[simp] lemma top_ne_of_real {r : ℝ} : ∞ ≠ ennreal.of_real r := by simp [ennreal.of_real] @[simp] lemma zero_ne_top : 0 ≠ ∞ := coe_ne_top @[simp] lemma top_ne_zero : ∞ ≠ 0 := top_ne_coe @[simp] lemma one_ne_top : 1 ≠ ∞ := coe_ne_top @[simp] lemma top_ne_one : ∞ ≠ 1 := top_ne_coe @[simp, norm_cast] lemma coe_eq_coe : (↑r : ennreal) = ↑q ↔ r = q := with_top.coe_eq_coe @[simp, norm_cast] lemma coe_le_coe : (↑r : ennreal) ≤ ↑q ↔ r ≤ q := with_top.coe_le_coe @[simp, norm_cast] lemma coe_lt_coe : (↑r : ennreal) < ↑q ↔ r < q := with_top.coe_lt_coe lemma coe_mono : monotone (coe : ℝ≥0 → ennreal) := λ _ _, coe_le_coe.2 @[simp, norm_cast] lemma coe_eq_zero : (↑r : ennreal) = 0 ↔ r = 0 := coe_eq_coe @[simp, norm_cast] lemma zero_eq_coe : 0 = (↑r : ennreal) ↔ 0 = r := coe_eq_coe @[simp, norm_cast] lemma coe_eq_one : (↑r : ennreal) = 1 ↔ r = 1 := coe_eq_coe @[simp, norm_cast] lemma one_eq_coe : 1 = (↑r : ennreal) ↔ 1 = r := coe_eq_coe @[simp, norm_cast] lemma coe_nonneg : 0 ≤ (↑r : ennreal) ↔ 0 ≤ r := coe_le_coe @[simp, norm_cast] lemma coe_pos : 0 < (↑r : ennreal) ↔ 0 < r := coe_lt_coe @[simp, norm_cast] lemma coe_add : ↑(r + p) = (r + p : ennreal) := with_top.coe_add @[simp, norm_cast] lemma coe_mul : ↑(r * p) = (r * p : ennreal) := with_top.coe_mul @[simp, norm_cast] lemma coe_bit0 : (↑(bit0 r) : ennreal) = bit0 r := coe_add @[simp, norm_cast] lemma coe_bit1 : (↑(bit1 r) : ennreal) = bit1 r := by simp [bit1] lemma coe_two : ((2:ℝ≥0) : ennreal) = 2 := by norm_cast protected lemma zero_lt_one : 0 < (1 : ennreal) := canonically_ordered_semiring.zero_lt_one @[simp] lemma one_lt_two : (1 : ennreal) < 2 := coe_one ▸ coe_two ▸ by exact_mod_cast (@one_lt_two ℕ _ _) @[simp] lemma zero_lt_two : (0:ennreal) < 2 := lt_trans ennreal.zero_lt_one one_lt_two lemma two_ne_zero : (2:ennreal) ≠ 0 := (ne_of_lt zero_lt_two).symm lemma two_ne_top : (2:ennreal) ≠ ∞ := coe_two ▸ coe_ne_top /-- The set of `ennreal` numbers that are not equal to `∞` is equivalent to `ℝ≥0`. -/ def ne_top_equiv_nnreal : {a | a ≠ ∞} ≃ ℝ≥0 := { to_fun := λ x, ennreal.to_nnreal x, inv_fun := λ x, ⟨x, coe_ne_top⟩, left_inv := λ ⟨x, hx⟩, subtype.eq $ coe_to_nnreal hx, right_inv := λ x, to_nnreal_coe } lemma cinfi_ne_top [has_Inf α] (f : ennreal → α) : (⨅ x : {x // x ≠ ∞}, f x) = ⨅ x : ℝ≥0, f x := eq.symm $ infi_congr _ ne_top_equiv_nnreal.symm.surjective $ λ x, rfl lemma infi_ne_top [complete_lattice α] (f : ennreal → α) : (⨅ x ≠ ∞, f x) = ⨅ x : ℝ≥0, f x := by rw [infi_subtype', cinfi_ne_top] lemma csupr_ne_top [has_Sup α] (f : ennreal → α) : (⨆ x : {x // x ≠ ∞}, f x) = ⨆ x : ℝ≥0, f x := @cinfi_ne_top (order_dual α) _ _ lemma supr_ne_top [complete_lattice α] (f : ennreal → α) : (⨆ x ≠ ∞, f x) = ⨆ x : ℝ≥0, f x := @infi_ne_top (order_dual α) _ _ lemma infi_ennreal {α : Type*} [complete_lattice α] {f : ennreal → α} : (⨅ n, f n) = (⨅ n : ℝ≥0, f n) ⊓ f ∞ := le_antisymm (le_inf (le_infi $ assume i, infi_le _ _) (infi_le _ _)) (le_infi $ forall_ennreal.2 ⟨assume r, inf_le_left_of_le $ infi_le _ _, inf_le_right⟩) lemma supr_ennreal {α : Type*} [complete_lattice α] {f : ennreal → α} : (⨆ n, f n) = (⨆ n : ℝ≥0, f n) ⊔ f ∞ := @infi_ennreal (order_dual α) _ _ @[simp] lemma add_top : a + ∞ = ∞ := with_top.add_top @[simp] lemma top_add : ∞ + a = ∞ := with_top.top_add /-- Coercion `ℝ≥0 → ennreal` as a `ring_hom`. -/ def of_nnreal_hom : ℝ≥0 →+* ennreal := ⟨coe, coe_one, λ _ _, coe_mul, coe_zero, λ _ _, coe_add⟩ @[simp] lemma coe_of_nnreal_hom : ⇑of_nnreal_hom = coe := rfl @[simp, norm_cast] lemma coe_indicator {α} (s : set α) (f : α → ℝ≥0) (a : α) : ((s.indicator f a : ℝ≥0) : ennreal) = s.indicator (λ x, f x) a := (of_nnreal_hom : ℝ≥0 →+ ennreal).map_indicator _ _ _ @[simp, norm_cast] lemma coe_pow (n : ℕ) : (↑(r^n) : ennreal) = r^n := of_nnreal_hom.map_pow r n lemma add_eq_top : a + b = ∞ ↔ a = ∞ ∨ b = ∞ := with_top.add_eq_top lemma add_lt_top : a + b < ∞ ↔ a < ∞ ∧ b < ∞ := with_top.add_lt_top lemma to_nnreal_add {r₁ r₂ : ennreal} (h₁ : r₁ < ∞) (h₂ : r₂ < ∞) : (r₁ + r₂).to_nnreal = r₁.to_nnreal + r₂.to_nnreal := begin rw [← coe_eq_coe, coe_add, coe_to_nnreal, coe_to_nnreal, coe_to_nnreal]; apply @ne_top_of_lt ennreal _ _ ∞, exact h₂, exact h₁, exact add_lt_top.2 ⟨h₁, h₂⟩ end /- rw has trouble with the generic lt_top_iff_ne_top and bot_lt_iff_ne_bot (contrary to erw). This is solved with the next lemmas -/ protected lemma lt_top_iff_ne_top : a < ∞ ↔ a ≠ ∞ := lt_top_iff_ne_top protected lemma bot_lt_iff_ne_bot : 0 < a ↔ a ≠ 0 := bot_lt_iff_ne_bot lemma not_lt_top {x : ennreal} : ¬ x < ∞ ↔ x = ∞ := by rw [lt_top_iff_ne_top, not_not] lemma add_ne_top : a + b ≠ ∞ ↔ a ≠ ∞ ∧ b ≠ ∞ := by simpa only [lt_top_iff_ne_top] using add_lt_top lemma mul_top : a * ∞ = (if a = 0 then 0 else ∞) := begin split_ifs, { simp [h] }, { exact with_top.mul_top h } end lemma top_mul : ∞ * a = (if a = 0 then 0 else ∞) := begin split_ifs, { simp [h] }, { exact with_top.top_mul h } end @[simp] lemma top_mul_top : ∞ * ∞ = ∞ := with_top.top_mul_top lemma top_pow {n:ℕ} (h : 0 < n) : ∞^n = ∞ := nat.le_induction (pow_one _) (λ m hm hm', by rw [pow_succ, hm', top_mul_top]) _ (nat.succ_le_of_lt h) lemma mul_eq_top : a * b = ∞ ↔ (a ≠ 0 ∧ b = ∞) ∨ (a = ∞ ∧ b ≠ 0) := with_top.mul_eq_top_iff lemma mul_ne_top : a ≠ ∞ → b ≠ ∞ → a * b ≠ ∞ := by simp [(≠), mul_eq_top] {contextual := tt} lemma mul_lt_top : a < ∞ → b < ∞ → a * b < ∞ := by simpa only [ennreal.lt_top_iff_ne_top] using mul_ne_top lemma ne_top_of_mul_ne_top_left (h : a * b ≠ ∞) (hb : b ≠ 0) : a ≠ ∞ := by { simp [mul_eq_top, hb, not_or_distrib] at h ⊢, exact h.2 } lemma ne_top_of_mul_ne_top_right (h : a * b ≠ ∞) (ha : a ≠ 0) : b ≠ ∞ := ne_top_of_mul_ne_top_left (by rwa [mul_comm]) ha lemma lt_top_of_mul_lt_top_left (h : a * b < ∞) (hb : b ≠ 0) : a < ∞ := by { rw [ennreal.lt_top_iff_ne_top] at h ⊢, exact ne_top_of_mul_ne_top_left h hb } lemma lt_top_of_mul_lt_top_right (h : a * b < ∞) (ha : a ≠ 0) : b < ∞ := lt_top_of_mul_lt_top_left (by rwa [mul_comm]) ha lemma mul_lt_top_iff {a b : ennreal} : a * b < ∞ ↔ (a < ∞ ∧ b < ∞) ∨ a = 0 ∨ b = 0 := begin split, { intro h, rw [← or_assoc, or_iff_not_imp_right, or_iff_not_imp_right], intros hb ha, exact ⟨lt_top_of_mul_lt_top_left h hb, lt_top_of_mul_lt_top_right h ha⟩ }, { rintro (⟨ha, hb⟩|rfl|rfl); [exact mul_lt_top ha hb, simp, simp] } end @[simp] lemma mul_pos : 0 < a * b ↔ 0 < a ∧ 0 < b := by simp only [zero_lt_iff_ne_zero, ne.def, mul_eq_zero, not_or_distrib] lemma pow_eq_top : ∀ n:ℕ, a^n=∞ → a=∞ | 0 := by simp | (n+1) := λ o, (mul_eq_top.1 o).elim (λ h, pow_eq_top n h.2) and.left lemma pow_ne_top (h : a ≠ ∞) {n:ℕ} : a^n ≠ ∞ := mt (pow_eq_top n) h lemma pow_lt_top : a < ∞ → ∀ n:ℕ, a^n < ∞ := by simpa only [lt_top_iff_ne_top] using pow_ne_top @[simp, norm_cast] lemma coe_finset_sum {s : finset α} {f : α → ℝ≥0} : ↑(∑ a in s, f a) = (∑ a in s, f a : ennreal) := of_nnreal_hom.map_sum f s @[simp, norm_cast] lemma coe_finset_prod {s : finset α} {f : α → ℝ≥0} : ↑(∏ a in s, f a) = ((∏ a in s, f a) : ennreal) := of_nnreal_hom.map_prod f s section order @[simp] lemma bot_eq_zero : (⊥ : ennreal) = 0 := rfl @[simp] lemma coe_lt_top : coe r < ∞ := with_top.coe_lt_top r @[simp] lemma not_top_le_coe : ¬ ∞ ≤ ↑r := with_top.not_top_le_coe r lemma zero_lt_coe_iff : 0 < (↑p : ennreal) ↔ 0 < p := coe_lt_coe @[simp, norm_cast] lemma one_le_coe_iff : (1:ennreal) ≤ ↑r ↔ 1 ≤ r := coe_le_coe @[simp, norm_cast] lemma coe_le_one_iff : ↑r ≤ (1:ennreal) ↔ r ≤ 1 := coe_le_coe @[simp, norm_cast] lemma coe_lt_one_iff : (↑p : ennreal) < 1 ↔ p < 1 := coe_lt_coe @[simp, norm_cast] lemma one_lt_coe_iff : 1 < (↑p : ennreal) ↔ 1 < p := coe_lt_coe @[simp, norm_cast] lemma coe_nat (n : nat) : ((n : ℝ≥0) : ennreal) = n := with_top.coe_nat n @[simp] lemma nat_ne_top (n : nat) : (n : ennreal) ≠ ∞ := with_top.nat_ne_top n @[simp] lemma top_ne_nat (n : nat) : ∞ ≠ n := with_top.top_ne_nat n @[simp] lemma one_lt_top : 1 < ∞ := coe_lt_top lemma le_coe_iff : a ≤ ↑r ↔ (∃p:ℝ≥0, a = p ∧ p ≤ r) := with_top.le_coe_iff lemma coe_le_iff : ↑r ≤ a ↔ (∀p:ℝ≥0, a = p → r ≤ p) := with_top.coe_le_iff lemma lt_iff_exists_coe : a < b ↔ (∃p:ℝ≥0, a = p ∧ ↑p < b) := with_top.lt_iff_exists_coe @[simp, norm_cast] lemma coe_finset_sup {s : finset α} {f : α → ℝ≥0} : ↑(s.sup f) = s.sup (λ x, (f x : ennreal)) := finset.comp_sup_eq_sup_comp_of_is_total _ coe_mono rfl lemma pow_le_pow {n m : ℕ} (ha : 1 ≤ a) (h : n ≤ m) : a ^ n ≤ a ^ m := begin cases a, { cases m, { rw eq_bot_iff.mpr h, exact le_refl _ }, { rw [none_eq_top, top_pow (nat.succ_pos m)], exact le_top } }, { rw [some_eq_coe, ← coe_pow, ← coe_pow, coe_le_coe], exact pow_le_pow (by simpa using ha) h } end @[simp] lemma max_eq_zero_iff : max a b = 0 ↔ a = 0 ∧ b = 0 := by simp only [le_zero_iff_eq.symm, max_le_iff] @[simp] lemma max_zero_left : max 0 a = a := max_eq_right (zero_le a) @[simp] lemma max_zero_right : max a 0 = a := max_eq_left (zero_le a) -- TODO: why this is not a `rfl`? There is some hidden diamond here. @[simp] lemma sup_eq_max : a ⊔ b = max a b := eq_of_forall_ge_iff $ λ c, sup_le_iff.trans max_le_iff.symm protected lemma pow_pos : 0 < a → ∀ n : ℕ, 0 < a^n := canonically_ordered_semiring.pow_pos protected lemma pow_ne_zero : a ≠ 0 → ∀ n : ℕ, a^n ≠ 0 := by simpa only [zero_lt_iff_ne_zero] using ennreal.pow_pos @[simp] lemma not_lt_zero : ¬ a < 0 := by simp lemma add_lt_add_iff_left : a < ∞ → (a + c < a + b ↔ c < b) := with_top.add_lt_add_iff_left lemma add_lt_add_iff_right : a < ∞ → (c + a < b + a ↔ c < b) := with_top.add_lt_add_iff_right lemma lt_add_right (ha : a < ∞) (hb : 0 < b) : a < a + b := by rwa [← add_lt_add_iff_left ha, add_zero] at hb lemma le_of_forall_epsilon_le : ∀{a b : ennreal}, (∀ε:ℝ≥0, 0 < ε → b < ∞ → a ≤ b + ε) → a ≤ b | a none h := le_top | none (some a) h := have ∞ ≤ ↑a + ↑(1:ℝ≥0), from h 1 zero_lt_one coe_lt_top, by rw [← coe_add] at this; exact (not_top_le_coe this).elim | (some a) (some b) h := by simp only [none_eq_top, some_eq_coe, coe_add.symm, coe_le_coe, coe_lt_top, true_implies_iff] at *; exact nnreal.le_of_forall_epsilon_le h lemma lt_iff_exists_rat_btwn : a < b ↔ (∃q:ℚ, 0 ≤ q ∧ a < nnreal.of_real q ∧ (nnreal.of_real q:ennreal) < b) := ⟨λ h, begin rcases lt_iff_exists_coe.1 h with ⟨p, rfl, _⟩, rcases exists_between h with ⟨c, pc, cb⟩, rcases lt_iff_exists_coe.1 cb with ⟨r, rfl, _⟩, rcases (nnreal.lt_iff_exists_rat_btwn _ _).1 (coe_lt_coe.1 pc) with ⟨q, hq0, pq, qr⟩, exact ⟨q, hq0, coe_lt_coe.2 pq, lt_trans (coe_lt_coe.2 qr) cb⟩ end, λ ⟨q, q0, qa, qb⟩, lt_trans qa qb⟩ lemma lt_iff_exists_real_btwn : a < b ↔ (∃r:ℝ, 0 ≤ r ∧ a < ennreal.of_real r ∧ (ennreal.of_real r:ennreal) < b) := ⟨λ h, let ⟨q, q0, aq, qb⟩ := ennreal.lt_iff_exists_rat_btwn.1 h in ⟨q, rat.cast_nonneg.2 q0, aq, qb⟩, λ ⟨q, q0, qa, qb⟩, lt_trans qa qb⟩ lemma lt_iff_exists_nnreal_btwn : a < b ↔ (∃r:ℝ≥0, a < r ∧ (r : ennreal) < b) := with_top.lt_iff_exists_coe_btwn lemma lt_iff_exists_add_pos_lt : a < b ↔ (∃ r : ℝ≥0, 0 < r ∧ a + r < b) := begin refine ⟨λ hab, _, λ ⟨r, rpos, hr⟩, lt_of_le_of_lt (le_add_right (le_refl _)) hr⟩, cases a, { simpa using hab }, rcases lt_iff_exists_real_btwn.1 hab with ⟨c, c_nonneg, ac, cb⟩, let d : ℝ≥0 := ⟨c, c_nonneg⟩, have ad : a < d, { rw of_real_eq_coe_nnreal c_nonneg at ac, exact coe_lt_coe.1 ac }, refine ⟨d-a, nnreal.sub_pos.2 ad, _⟩, rw [some_eq_coe, ← coe_add], convert cb, have : nnreal.of_real c = d, by { rw [← nnreal.coe_eq, nnreal.coe_of_real _ c_nonneg], refl }, rw [add_comm, this], exact nnreal.sub_add_cancel_of_le (le_of_lt ad) end lemma coe_nat_lt_coe {n : ℕ} : (n : ennreal) < r ↔ ↑n < r := ennreal.coe_nat n ▸ coe_lt_coe lemma coe_lt_coe_nat {n : ℕ} : (r : ennreal) < n ↔ r < n := ennreal.coe_nat n ▸ coe_lt_coe @[norm_cast] lemma coe_nat_lt_coe_nat {m n : ℕ} : (m : ennreal) < n ↔ m < n := ennreal.coe_nat n ▸ coe_nat_lt_coe.trans nat.cast_lt lemma coe_nat_ne_top {n : ℕ} : (n : ennreal) ≠ ∞ := ennreal.coe_nat n ▸ coe_ne_top lemma coe_nat_mono : strict_mono (coe : ℕ → ennreal) := λ _ _, coe_nat_lt_coe_nat.2 @[norm_cast] lemma coe_nat_le_coe_nat {m n : ℕ} : (m : ennreal) ≤ n ↔ m ≤ n := coe_nat_mono.le_iff_le instance : char_zero ennreal := ⟨coe_nat_mono.injective⟩ protected lemma exists_nat_gt {r : ennreal} (h : r ≠ ∞) : ∃n:ℕ, r < n := begin lift r to ℝ≥0 using h, rcases exists_nat_gt r with ⟨n, hn⟩, exact ⟨n, coe_lt_coe_nat.2 hn⟩, end lemma add_lt_add (ac : a < c) (bd : b < d) : a + b < c + d := begin rcases exists_between ac with ⟨a', aa', a'c⟩, rcases lt_iff_exists_coe.1 aa' with ⟨aR, rfl, _⟩, rcases lt_iff_exists_coe.1 a'c with ⟨a'R, rfl, _⟩, rcases exists_between bd with ⟨b', bb', b'd⟩, rcases lt_iff_exists_coe.1 bb' with ⟨bR, rfl, _⟩, rcases lt_iff_exists_coe.1 b'd with ⟨b'R, rfl, _⟩, have I : ↑aR + ↑bR < ↑a'R + ↑b'R := begin rw [← coe_add, ← coe_add, coe_lt_coe], apply add_lt_add (coe_lt_coe.1 aa') (coe_lt_coe.1 bb') end, have J : ↑a'R + ↑b'R ≤ c + d := add_le_add (le_of_lt a'c) (le_of_lt b'd), apply lt_of_lt_of_le I J end @[norm_cast] lemma coe_min : ((min r p:ℝ≥0):ennreal) = min r p := coe_mono.map_min @[norm_cast] lemma coe_max : ((max r p:ℝ≥0):ennreal) = max r p := coe_mono.map_max lemma le_of_top_imp_top_of_to_nnreal_le {a b : ennreal} (h : a = ⊤ → b = ⊤) (h_nnreal : a ≠ ⊤ → b ≠ ⊤ → a.to_nnreal ≤ b.to_nnreal) : a ≤ b := begin by_cases ha : a = ⊤, { rw h ha, exact le_top, }, by_cases hb : b = ⊤, { rw hb, exact le_top, }, rw [←coe_to_nnreal hb, ←coe_to_nnreal ha, coe_le_coe], exact h_nnreal ha hb, end end order section complete_lattice lemma coe_Sup {s : set ℝ≥0} : bdd_above s → (↑(Sup s) : ennreal) = (⨆a∈s, ↑a) := with_top.coe_Sup lemma coe_Inf {s : set ℝ≥0} : s.nonempty → (↑(Inf s) : ennreal) = (⨅a∈s, ↑a) := with_top.coe_Inf @[simp] lemma top_mem_upper_bounds {s : set ennreal} : ∞ ∈ upper_bounds s := assume x hx, le_top lemma coe_mem_upper_bounds {s : set ℝ≥0} : ↑r ∈ upper_bounds ((coe : ℝ≥0 → ennreal) '' s) ↔ r ∈ upper_bounds s := by simp [upper_bounds, ball_image_iff, -mem_image, *] {contextual := tt} end complete_lattice section mul lemma mul_le_mul : a ≤ b → c ≤ d → a * c ≤ b * d := canonically_ordered_semiring.mul_le_mul lemma mul_left_mono : monotone ((*) a) := λ b c, mul_le_mul (le_refl a) lemma mul_right_mono : monotone (λ x, x * a) := λ b c h, mul_le_mul h (le_refl a) lemma max_mul : max a b * c = max (a * c) (b * c) := mul_right_mono.map_max lemma mul_max : a * max b c = max (a * b) (a * c) := mul_left_mono.map_max lemma mul_eq_mul_left : a ≠ 0 → a ≠ ∞ → (a * b = a * c ↔ b = c) := begin cases a; cases b; cases c; simp [none_eq_top, some_eq_coe, mul_top, top_mul, -coe_mul, coe_mul.symm, nnreal.mul_eq_mul_left] {contextual := tt}, end lemma mul_eq_mul_right : c ≠ 0 → c ≠ ∞ → (a * c = b * c ↔ a = b) := mul_comm c a ▸ mul_comm c b ▸ mul_eq_mul_left lemma mul_le_mul_left : a ≠ 0 → a ≠ ∞ → (a * b ≤ a * c ↔ b ≤ c) := begin cases a; cases b; cases c; simp [none_eq_top, some_eq_coe, mul_top, top_mul, -coe_mul, coe_mul.symm] {contextual := tt}, assume h, exact mul_le_mul_left (zero_lt_iff_ne_zero.2 h) end lemma mul_le_mul_right : c ≠ 0 → c ≠ ∞ → (a * c ≤ b * c ↔ a ≤ b) := mul_comm c a ▸ mul_comm c b ▸ mul_le_mul_left lemma mul_lt_mul_left : a ≠ 0 → a ≠ ∞ → (a * b < a * c ↔ b < c) := λ h0 ht, by simp only [mul_le_mul_left h0 ht, lt_iff_le_not_le] lemma mul_lt_mul_right : c ≠ 0 → c ≠ ∞ → (a * c < b * c ↔ a < b) := mul_comm c a ▸ mul_comm c b ▸ mul_lt_mul_left end mul section sub instance : has_sub ennreal := ⟨λa b, Inf {d | a ≤ d + b}⟩ @[norm_cast] lemma coe_sub : ↑(p - r) = (↑p:ennreal) - r := le_antisymm (le_Inf $ assume b (hb : ↑p ≤ b + r), coe_le_iff.2 $ by rintros d rfl; rwa [← coe_add, coe_le_coe, ← nnreal.sub_le_iff_le_add] at hb) (Inf_le $ show (↑p : ennreal) ≤ ↑(p - r) + ↑r, by rw [← coe_add, coe_le_coe, ← nnreal.sub_le_iff_le_add]) @[simp] lemma top_sub_coe : ∞ - ↑r = ∞ := top_unique $ le_Inf $ by simp [add_eq_top] @[simp] lemma sub_eq_zero_of_le (h : a ≤ b) : a - b = 0 := le_antisymm (Inf_le $ le_add_left h) (zero_le _) @[simp] lemma sub_self : a - a = 0 := sub_eq_zero_of_le $ le_refl _ @[simp] lemma zero_sub : 0 - a = 0 := le_antisymm (Inf_le $ zero_le $ 0 + a) (zero_le _) @[simp] lemma sub_infty : a - ∞ = 0 := le_antisymm (Inf_le $ by simp) (zero_le _) lemma sub_le_sub (h₁ : a ≤ b) (h₂ : d ≤ c) : a - c ≤ b - d := Inf_le_Inf $ assume e (h : b ≤ e + d), calc a ≤ b : h₁ ... ≤ e + d : h ... ≤ e + c : add_le_add (le_refl _) h₂ @[simp] lemma add_sub_self : ∀{a b : ennreal}, b < ∞ → (a + b) - b = a | a none := by simp [none_eq_top] | none (some b) := by simp [none_eq_top, some_eq_coe] | (some a) (some b) := by simp [some_eq_coe]; rw [← coe_add, ← coe_sub, coe_eq_coe, nnreal.add_sub_cancel] @[simp] lemma add_sub_self' (h : a < ∞) : (a + b) - a = b := by rw [add_comm, add_sub_self h] lemma add_right_inj (h : a < ∞) : a + b = a + c ↔ b = c := ⟨λ e, by simpa [h] using congr_arg (λ x, x - a) e, congr_arg _⟩ lemma add_left_inj (h : a < ∞) : b + a = c + a ↔ b = c := by rw [add_comm, add_comm c, add_right_inj h] @[simp] lemma sub_add_cancel_of_le : ∀{a b : ennreal}, b ≤ a → (a - b) + b = a := begin simp [forall_ennreal, le_coe_iff, -add_comm] {contextual := tt}, rintros r p x rfl h, rw [← coe_sub, ← coe_add, nnreal.sub_add_cancel_of_le h] end @[simp] lemma add_sub_cancel_of_le (h : b ≤ a) : b + (a - b) = a := by rwa [add_comm, sub_add_cancel_of_le] lemma sub_add_self_eq_max : (a - b) + b = max a b := match le_total a b with | or.inl h := by simp [h, max_eq_right] | or.inr h := by simp [h, max_eq_left] end lemma le_sub_add_self : a ≤ (a - b) + b := by { rw sub_add_self_eq_max, exact le_max_left a b } @[simp] protected lemma sub_le_iff_le_add : a - b ≤ c ↔ a ≤ c + b := iff.intro (assume h : a - b ≤ c, calc a ≤ (a - b) + b : le_sub_add_self ... ≤ c + b : add_le_add_right h _) (assume h : a ≤ c + b, calc a - b ≤ (c + b) - b : sub_le_sub h (le_refl _) ... ≤ c : Inf_le (le_refl (c + b))) protected lemma sub_le_iff_le_add' : a - b ≤ c ↔ a ≤ b + c := add_comm c b ▸ ennreal.sub_le_iff_le_add lemma sub_eq_of_add_eq : b ≠ ∞ → a + b = c → c - b = a := λ hb hc, hc ▸ add_sub_self (lt_top_iff_ne_top.2 hb) protected lemma sub_le_of_sub_le (h : a - b ≤ c) : a - c ≤ b := ennreal.sub_le_iff_le_add.2 $ by { rw add_comm, exact ennreal.sub_le_iff_le_add.1 h } protected lemma sub_lt_sub_self : a ≠ ∞ → a ≠ 0 → 0 < b → a - b < a := match a, b with | none, _ := by { have := none_eq_top, assume h, contradiction } | (some a), none := by {intros, simp only [none_eq_top, sub_infty, zero_lt_iff_ne_zero], assumption} | (some a), (some b) := begin simp only [some_eq_coe, coe_sub.symm, coe_pos, coe_eq_zero, coe_lt_coe, ne.def], assume h₁ h₂, apply nnreal.sub_lt_self, exact zero_lt_iff_ne_zero.2 h₂ end end @[simp] lemma sub_eq_zero_iff_le : a - b = 0 ↔ a ≤ b := by simpa [-ennreal.sub_le_iff_le_add] using @ennreal.sub_le_iff_le_add a b 0 @[simp] lemma zero_lt_sub_iff_lt : 0 < a - b ↔ b < a := by simpa [ennreal.bot_lt_iff_ne_bot, -sub_eq_zero_iff_le] using not_iff_not.2 (@sub_eq_zero_iff_le a b) lemma lt_sub_iff_add_lt : a < b - c ↔ a + c < b := begin cases a, { simp }, cases c, { simp }, cases b, { simp only [true_iff, coe_lt_top, some_eq_coe, top_sub_coe, none_eq_top, ← coe_add] }, simp only [some_eq_coe], rw [← coe_add, ← coe_sub, coe_lt_coe, coe_lt_coe, nnreal.lt_sub_iff_add_lt], end lemma sub_le_self (a b : ennreal) : a - b ≤ a := ennreal.sub_le_iff_le_add.2 $ le_add_right (le_refl a) @[simp] lemma sub_zero : a - 0 = a := eq.trans (add_zero (a - 0)).symm $ by simp /-- A version of triangle inequality for difference as a "distance". -/ lemma sub_le_sub_add_sub : a - c ≤ a - b + (b - c) := ennreal.sub_le_iff_le_add.2 $ calc a ≤ a - b + b : le_sub_add_self ... ≤ a - b + ((b - c) + c) : add_le_add_left le_sub_add_self _ ... = a - b + (b - c) + c : (add_assoc _ _ _).symm lemma sub_sub_cancel (h : a < ∞) (h2 : b ≤ a) : a - (a - b) = b := by rw [← add_left_inj (lt_of_le_of_lt (sub_le_self _ _) h), sub_add_cancel_of_le (sub_le_self _ _), add_sub_cancel_of_le h2] lemma sub_right_inj {a b c : ennreal} (ha : a < ∞) (hb : b ≤ a) (hc : c ≤ a) : a - b = a - c ↔ b = c := iff.intro begin assume h, have : a - (a - b) = a - (a - c), rw h, rw [sub_sub_cancel ha hb, sub_sub_cancel ha hc] at this, exact this end (λ h, by rw h) lemma sub_mul (h : 0 < b → b < a → c ≠ ∞) : (a - b) * c = a * c - b * c := begin cases le_or_lt a b with hab hab, { simp [hab, mul_right_mono hab] }, symmetry, cases eq_or_lt_of_le (zero_le b) with hb hb, { subst b, simp }, apply sub_eq_of_add_eq, { exact mul_ne_top (ne_top_of_lt hab) (h hb hab) }, rw [← add_mul, sub_add_cancel_of_le (le_of_lt hab)] end lemma mul_sub (h : 0 < c → c < b → a ≠ ∞) : a * (b - c) = a * b - a * c := by { simp only [mul_comm a], exact sub_mul h } lemma sub_mul_ge : a * c - b * c ≤ (a - b) * c := begin -- with `0 < b → b < a → c ≠ ∞` Lean names the first variable `a` by_cases h : ∀ (hb : 0 < b), b < a → c ≠ ∞, { rw [sub_mul h], exact le_refl _ }, { push_neg at h, rcases h with ⟨hb, hba, hc⟩, subst c, simp only [mul_top, if_neg (ne_of_gt hb), if_neg (ne_of_gt $ lt_trans hb hba), sub_self, zero_le] } end end sub section sum open finset /-- A sum of finite numbers is still finite -/ lemma sum_lt_top {s : finset α} {f : α → ennreal} : (∀a∈s, f a < ∞) → ∑ a in s, f a < ∞ := with_top.sum_lt_top /-- A sum of finite numbers is still finite -/ lemma sum_lt_top_iff {s : finset α} {f : α → ennreal} : ∑ a in s, f a < ∞ ↔ (∀a∈s, f a < ∞) := with_top.sum_lt_top_iff /-- A sum of numbers is infinite iff one of them is infinite -/ lemma sum_eq_top_iff {s : finset α} {f : α → ennreal} : (∑ x in s, f x) = ∞ ↔ (∃a∈s, f a = ∞) := with_top.sum_eq_top_iff /-- seeing `ennreal` as `ℝ≥0` does not change their sum, unless one of the `ennreal` is infinity -/ lemma to_nnreal_sum {s : finset α} {f : α → ennreal} (hf : ∀a∈s, f a < ∞) : ennreal.to_nnreal (∑ a in s, f a) = ∑ a in s, ennreal.to_nnreal (f a) := begin rw [← coe_eq_coe, coe_to_nnreal, coe_finset_sum, sum_congr], { refl }, { intros x hx, exact (coe_to_nnreal (hf x hx).ne).symm }, { exact (sum_lt_top hf).ne } end /-- seeing `ennreal` as `real` does not change their sum, unless one of the `ennreal` is infinity -/ lemma to_real_sum {s : finset α} {f : α → ennreal} (hf : ∀a∈s, f a < ∞) : ennreal.to_real (∑ a in s, f a) = ∑ a in s, ennreal.to_real (f a) := by { rw [ennreal.to_real, to_nnreal_sum hf, nnreal.coe_sum], refl } end sum section interval variables {x y z : ennreal} {ε ε₁ ε₂ : ennreal} {s : set ennreal} protected lemma Ico_eq_Iio : (Ico 0 y) = (Iio y) := ext $ assume a, iff.intro (assume ⟨_, hx⟩, hx) (assume hx, ⟨zero_le _, hx⟩) lemma mem_Iio_self_add : x ≠ ∞ → 0 < ε → x ∈ Iio (x + ε) := assume xt ε0, lt_add_right (by rwa lt_top_iff_ne_top) ε0 lemma not_mem_Ioo_self_sub : x = 0 → x ∉ Ioo (x - ε) y := assume x0, by simp [x0] lemma mem_Ioo_self_sub_add : x ≠ ∞ → x ≠ 0 → 0 < ε₁ → 0 < ε₂ → x ∈ Ioo (x - ε₁) (x + ε₂) := assume xt x0 ε0 ε0', ⟨ennreal.sub_lt_sub_self xt x0 ε0, lt_add_right (by rwa [lt_top_iff_ne_top]) ε0'⟩ end interval section bit @[simp] lemma bit0_inj : bit0 a = bit0 b ↔ a = b := ⟨λh, begin rcases (lt_trichotomy a b) with h₁| h₂| h₃, { exact (absurd h (ne_of_lt (add_lt_add h₁ h₁))) }, { exact h₂ }, { exact (absurd h.symm (ne_of_lt (add_lt_add h₃ h₃))) } end, λh, congr_arg _ h⟩ @[simp] lemma bit0_eq_zero_iff : bit0 a = 0 ↔ a = 0 := by simpa only [bit0_zero] using @bit0_inj a 0 @[simp] lemma bit0_eq_top_iff : bit0 a = ∞ ↔ a = ∞ := by rw [bit0, add_eq_top, or_self] @[simp] lemma bit1_inj : bit1 a = bit1 b ↔ a = b := ⟨λh, begin unfold bit1 at h, rwa [add_left_inj, bit0_inj] at h, simp [lt_top_iff_ne_top] end, λh, congr_arg _ h⟩ @[simp] lemma bit1_ne_zero : bit1 a ≠ 0 := by unfold bit1; simp @[simp] lemma bit1_eq_one_iff : bit1 a = 1 ↔ a = 0 := by simpa only [bit1_zero] using @bit1_inj a 0 @[simp] lemma bit1_eq_top_iff : bit1 a = ∞ ↔ a = ∞ := by unfold bit1; rw add_eq_top; simp end bit section inv instance : has_inv ennreal := ⟨λa, Inf {b | 1 ≤ a * b}⟩ instance : has_div ennreal := ⟨λa b, a * b⁻¹⟩ lemma div_def : a / b = a * b⁻¹ := rfl lemma mul_div_assoc : (a * b) / c = a * (b / c) := mul_assoc _ _ _ @[simp] lemma inv_zero : (0 : ennreal)⁻¹ = ∞ := show Inf {b : ennreal | 1 ≤ 0 * b} = ∞, by simp; refl @[simp] lemma inv_top : ∞⁻¹ = 0 := bot_unique $ le_of_forall_le_of_dense $ λ a (h : a > 0), Inf_le $ by simp [*, ne_of_gt h, top_mul] @[simp, norm_cast] lemma coe_inv (hr : r ≠ 0) : (↑r⁻¹ : ennreal) = (↑r)⁻¹ := le_antisymm (le_Inf $ assume b (hb : 1 ≤ ↑r * b), coe_le_iff.2 $ by rintros b rfl; rwa [← coe_mul, ← coe_one, coe_le_coe, ← nnreal.inv_le hr] at hb) (Inf_le $ by simp; rw [← coe_mul, nnreal.mul_inv_cancel hr]; exact le_refl 1) lemma coe_inv_le : (↑r⁻¹ : ennreal) ≤ (↑r)⁻¹ := if hr : r = 0 then by simp only [hr, nnreal.inv_zero, inv_zero, coe_zero, zero_le] else by simp only [coe_inv hr, le_refl] @[norm_cast] lemma coe_inv_two : ((2⁻¹:ℝ≥0):ennreal) = 2⁻¹ := by rw [coe_inv (ne_of_gt _root_.zero_lt_two), coe_two] @[simp, norm_cast] lemma coe_div (hr : r ≠ 0) : (↑(p / r) : ennreal) = p / r := show ↑(p * r⁻¹) = ↑p * (↑r)⁻¹, by rw [coe_mul, coe_inv hr] @[simp] lemma inv_one : (1:ennreal)⁻¹ = 1 := by simpa only [coe_inv one_ne_zero, coe_one] using coe_eq_coe.2 nnreal.inv_one @[simp] lemma div_one {a : ennreal} : a / 1 = a := by simp [ennreal.div_def] protected lemma inv_pow {n : ℕ} : (a^n)⁻¹ = (a⁻¹)^n := begin by_cases a = 0; cases a; cases n; simp [*, none_eq_top, some_eq_coe, zero_pow, top_pow, nat.zero_lt_succ] at *, rw [← coe_inv h, ← coe_pow, ← coe_inv, nnreal.inv_pow, coe_pow], rw [← ne.def] at h, rw [← zero_lt_iff_ne_zero] at *, apply pow_pos h end @[simp] lemma inv_inv : (a⁻¹)⁻¹ = a := by by_cases a = 0; cases a; simp [*, none_eq_top, some_eq_coe, -coe_inv, (coe_inv _).symm] at * lemma inv_involutive : function.involutive (λ a:ennreal, a⁻¹) := λ a, ennreal.inv_inv lemma inv_bijective : function.bijective (λ a:ennreal, a⁻¹) := ennreal.inv_involutive.bijective @[simp] lemma inv_eq_inv : a⁻¹ = b⁻¹ ↔ a = b := inv_bijective.1.eq_iff @[simp] lemma inv_eq_top : a⁻¹ = ∞ ↔ a = 0 := inv_zero ▸ inv_eq_inv lemma inv_ne_top : a⁻¹ ≠ ∞ ↔ a ≠ 0 := by simp @[simp] lemma inv_lt_top {x : ennreal} : x⁻¹ < ∞ ↔ 0 < x := by { simp only [lt_top_iff_ne_top, inv_ne_top, zero_lt_iff_ne_zero] } lemma div_lt_top {x y : ennreal} (h1 : x < ∞) (h2 : 0 < y) : x / y < ∞ := mul_lt_top h1 (inv_lt_top.mpr h2) @[simp] lemma inv_eq_zero : a⁻¹ = 0 ↔ a = ∞ := inv_top ▸ inv_eq_inv lemma inv_ne_zero : a⁻¹ ≠ 0 ↔ a ≠ ∞ := by simp @[simp] lemma inv_pos : 0 < a⁻¹ ↔ a ≠ ∞ := zero_lt_iff_ne_zero.trans inv_ne_zero @[simp] lemma inv_lt_inv : a⁻¹ < b⁻¹ ↔ b < a := begin cases a; cases b; simp only [some_eq_coe, none_eq_top, inv_top], { simp only [lt_irrefl] }, { exact inv_pos.trans lt_top_iff_ne_top.symm }, { simp only [not_lt_zero, not_top_lt] }, { cases eq_or_lt_of_le (zero_le a) with ha ha; cases eq_or_lt_of_le (zero_le b) with hb hb, { subst a, subst b, simp }, { subst a, simp }, { subst b, simp [zero_lt_iff_ne_zero, lt_top_iff_ne_top, inv_ne_top] }, { rw [← coe_inv (ne_of_gt ha), ← coe_inv (ne_of_gt hb), coe_lt_coe, coe_lt_coe], simp only [nnreal.coe_lt_coe.symm] at *, exact inv_lt_inv ha hb } } end lemma inv_lt_iff_inv_lt : a⁻¹ < b ↔ b⁻¹ < a := by simpa only [inv_inv] using @inv_lt_inv a b⁻¹ lemma lt_inv_iff_lt_inv : a < b⁻¹ ↔ b < a⁻¹ := by simpa only [inv_inv] using @inv_lt_inv a⁻¹ b @[simp, priority 1100] -- higher than le_inv_iff_mul_le lemma inv_le_inv : a⁻¹ ≤ b⁻¹ ↔ b ≤ a := by simp only [le_iff_lt_or_eq, inv_lt_inv, inv_eq_inv, eq_comm] lemma inv_le_iff_inv_le : a⁻¹ ≤ b ↔ b⁻¹ ≤ a := by simpa only [inv_inv] using @inv_le_inv a b⁻¹ lemma le_inv_iff_le_inv : a ≤ b⁻¹ ↔ b ≤ a⁻¹ := by simpa only [inv_inv] using @inv_le_inv a⁻¹ b @[simp] lemma inv_lt_one : a⁻¹ < 1 ↔ 1 < a := inv_lt_iff_inv_lt.trans $ by rw [inv_one] @[simp] lemma div_top : a / ∞ = 0 := by simp only [div_def, inv_top, mul_zero] @[simp] lemma top_div_coe : ∞ / p = ∞ := by simp [div_def, top_mul] lemma top_div_of_ne_top (h : a ≠ ∞) : ∞ / a = ∞ := by { lift a to ℝ≥0 using h, exact top_div_coe } lemma top_div_of_lt_top (h : a < ∞) : ∞ / a = ∞ := top_div_of_ne_top h.ne lemma top_div : ∞ / a = if a = ∞ then 0 else ∞ := by by_cases a = ∞; simp [top_div_of_ne_top, *] @[simp] lemma zero_div : 0 / a = 0 := zero_mul a⁻¹ lemma div_eq_top : a / b = ∞ ↔ (a ≠ 0 ∧ b = 0) ∨ (a = ∞ ∧ b ≠ ∞) := by simp [ennreal.div_def, ennreal.mul_eq_top] lemma le_div_iff_mul_le (h0 : b ≠ 0 ∨ c ≠ 0) (ht : b ≠ ∞ ∨ c ≠ ∞) : a ≤ c / b ↔ a * b ≤ c := begin cases b, { simp at ht, split, { assume ha, simp at ha, simp [ha] }, { contrapose, assume ha, simp at ha, have : a * ∞ = ∞, by simp [ennreal.mul_eq_top, ha], simp [this, ht] } }, by_cases hb : b ≠ 0, { have : (b : ennreal) ≠ 0, by simp [hb], rw [← ennreal.mul_le_mul_left this coe_ne_top], suffices : ↑b * a ≤ (↑b * ↑b⁻¹) * c ↔ a * ↑b ≤ c, { simpa [some_eq_coe, div_def, hb, mul_left_comm, mul_comm, mul_assoc] }, rw [← coe_mul, nnreal.mul_inv_cancel hb, coe_one, one_mul, mul_comm] }, { simp at hb, simp [hb] at h0, have : c / 0 = ∞, by simp [div_eq_top, h0], simp [hb, this] } end lemma div_le_iff_le_mul (hb0 : b ≠ 0 ∨ c ≠ ∞) (hbt : b ≠ ∞ ∨ c ≠ 0) : a / b ≤ c ↔ a ≤ c * b := begin suffices : a * b⁻¹ ≤ c ↔ a ≤ c / b⁻¹, by simpa [div_def], apply (le_div_iff_mul_le _ _).symm, simpa [inv_ne_zero] using hbt, simpa [inv_ne_zero] using hb0 end lemma div_le_of_le_mul (h : a ≤ b * c) : a / c ≤ b := begin by_cases h0 : c = 0, { have : a = 0, by simpa [h0] using h, simp [*] }, by_cases hinf : c = ∞, by simp [hinf], exact (div_le_iff_le_mul (or.inl h0) (or.inl hinf)).2 h end protected lemma div_lt_iff (h0 : b ≠ 0 ∨ c ≠ 0) (ht : b ≠ ∞ ∨ c ≠ ∞) : c / b < a ↔ c < a * b := lt_iff_lt_of_le_iff_le $ le_div_iff_mul_le h0 ht lemma mul_lt_of_lt_div (h : a < b / c) : a * c < b := by { contrapose! h, exact ennreal.div_le_of_le_mul h } lemma inv_le_iff_le_mul : (b = ∞ → a ≠ 0) → (a = ∞ → b ≠ 0) → (a⁻¹ ≤ b ↔ 1 ≤ a * b) := begin cases a; cases b; simp [none_eq_top, some_eq_coe, mul_top, top_mul] {contextual := tt}, by_cases a = 0; simp [*, -coe_mul, coe_mul.symm, -coe_inv, (coe_inv _).symm, nnreal.inv_le] end @[simp] lemma le_inv_iff_mul_le : a ≤ b⁻¹ ↔ a * b ≤ 1 := begin cases b, { by_cases a = 0; simp [*, none_eq_top, mul_top] }, by_cases b = 0; simp [*, some_eq_coe, le_div_iff_mul_le], suffices : a ≤ 1 / b ↔ a * b ≤ 1, { simpa [div_def, h] }, exact le_div_iff_mul_le (or.inl (mt coe_eq_coe.1 h)) (or.inl coe_ne_top) end lemma mul_inv_cancel (h0 : a ≠ 0) (ht : a ≠ ∞) : a * a⁻¹ = 1 := begin lift a to ℝ≥0 using ht, norm_cast at h0, norm_cast, exact nnreal.mul_inv_cancel h0 end lemma inv_mul_cancel (h0 : a ≠ 0) (ht : a ≠ ∞) : a⁻¹ * a = 1 := mul_comm a a⁻¹ ▸ mul_inv_cancel h0 ht lemma mul_le_iff_le_inv {a b r : ennreal} (hr₀ : r ≠ 0) (hr₁ : r ≠ ∞) : (r * a ≤ b ↔ a ≤ r⁻¹ * b) := by rw [← @ennreal.mul_le_mul_left _ a _ hr₀ hr₁, ← mul_assoc, mul_inv_cancel hr₀ hr₁, one_mul] lemma le_of_forall_lt_one_mul_lt : ∀{x y : ennreal}, (∀a<1, a * x ≤ y) → x ≤ y := forall_ennreal.2 $ and.intro (assume r, forall_ennreal.2 $ and.intro (assume q h, coe_le_coe.2 $ nnreal.le_of_forall_lt_one_mul_lt $ assume a ha, begin rw [← coe_le_coe, coe_mul], exact h _ (coe_lt_coe.2 ha) end) (assume h, le_top)) (assume r hr, have ((1 / 2 : ℝ≥0) : ennreal) * ∞ ≤ r := hr _ (coe_lt_coe.2 ((@nnreal.coe_lt_coe (1/2) 1).1 one_half_lt_one)), have ne : ((1 / 2 : ℝ≥0) : ennreal) ≠ 0, begin rw [(≠), coe_eq_zero], refine zero_lt_iff_ne_zero.1 _, show 0 < (1 / 2 : ℝ), linarith, end, by rwa [mul_top, if_neg ne] at this) lemma div_add_div_same {a b c : ennreal} : a / c + b / c = (a + b) / c := eq.symm $ right_distrib a b (c⁻¹) lemma div_self (h0 : a ≠ 0) (hI : a ≠ ∞) : a / a = 1 := mul_inv_cancel h0 hI lemma mul_div_cancel (h0 : a ≠ 0) (hI : a ≠ ∞) : (b / a) * a = b := by rw [div_def, mul_assoc, inv_mul_cancel h0 hI, mul_one] lemma mul_div_cancel' (h0 : a ≠ 0) (hI : a ≠ ∞) : a * (b / a) = b := by rw [mul_comm, mul_div_cancel h0 hI] lemma inv_two_add_inv_two : (2:ennreal)⁻¹ + 2⁻¹ = 1 := by rw [← two_mul, ← div_def, div_self two_ne_zero two_ne_top] lemma add_halves (a : ennreal) : a / 2 + a / 2 = a := by rw [div_def, ← mul_add, inv_two_add_inv_two, mul_one] @[simp] lemma div_zero_iff : a / b = 0 ↔ a = 0 ∨ b = ∞ := by simp [div_def, mul_eq_zero] @[simp] lemma div_pos_iff : 0 < a / b ↔ a ≠ 0 ∧ b ≠ ∞ := by simp [zero_lt_iff_ne_zero, not_or_distrib] lemma half_pos {a : ennreal} (h : 0 < a) : 0 < a / 2 := by simp [ne_of_gt h] lemma one_half_lt_one : (2⁻¹:ennreal) < 1 := inv_lt_one.2 $ one_lt_two lemma half_lt_self {a : ennreal} (hz : a ≠ 0) (ht : a ≠ ∞) : a / 2 < a := begin lift a to ℝ≥0 using ht, have h : (2 : ennreal) = ((2 : ℝ≥0) : ennreal), from rfl, have h' : (2 : ℝ≥0) ≠ 0, from _root_.two_ne_zero', rw [h, ← coe_div h', coe_lt_coe], -- `norm_cast` fails to apply `coe_div` norm_cast at hz, exact nnreal.half_lt_self hz end lemma sub_half (h : a ≠ ∞) : a - a / 2 = a / 2 := begin lift a to ℝ≥0 using h, exact sub_eq_of_add_eq (mul_ne_top coe_ne_top $ by simp) (add_halves a) end lemma one_sub_inv_two : (1:ennreal) - 2⁻¹ = 2⁻¹ := by simpa only [div_def, one_mul] using sub_half one_ne_top lemma exists_inv_nat_lt {a : ennreal} (h : a ≠ 0) : ∃n:ℕ, (n:ennreal)⁻¹ < a := @inv_inv a ▸ by simp only [inv_lt_inv, ennreal.exists_nat_gt (inv_ne_top.2 h)] lemma exists_nat_pos_mul_gt (ha : a ≠ 0) (hb : b ≠ ∞) : ∃ n > 0, b < (n : ℕ) * a := begin have : b / a ≠ ∞, from mul_ne_top hb (inv_ne_top.2 ha), refine (ennreal.exists_nat_gt this).imp (λ n hn, _), have : 0 < (n : ennreal), from (zero_le _).trans_lt hn, refine ⟨coe_nat_lt_coe_nat.1 this, _⟩, rwa [← ennreal.div_lt_iff (or.inl ha) (or.inr hb)] end lemma exists_nat_mul_gt (ha : a ≠ 0) (hb : b ≠ ∞) : ∃ n : ℕ, b < n * a := (exists_nat_pos_mul_gt ha hb).imp $ λ n, Exists.snd lemma exists_nat_pos_inv_mul_lt (ha : a ≠ ∞) (hb : b ≠ 0) : ∃ n > 0, ((n : ℕ) : ennreal)⁻¹ * a < b := begin rcases exists_nat_pos_mul_gt hb ha with ⟨n, npos, hn⟩, have : (n : ennreal) ≠ 0 := nat.cast_ne_zero.2 npos.lt.ne', use [n, npos], rwa [← one_mul b, ← inv_mul_cancel this coe_nat_ne_top, mul_assoc, mul_lt_mul_left (inv_ne_zero.2 coe_nat_ne_top) (inv_ne_top.2 this)] end lemma exists_nnreal_pos_mul_lt (ha : a ≠ ∞) (hb : b ≠ 0) : ∃ n > 0, ↑(n : ℝ≥0) * a < b := begin rcases exists_nat_pos_inv_mul_lt ha hb with ⟨n, npos : 0 < n, hn⟩, use (n : ℝ≥0)⁻¹, simp [*, npos.ne', zero_lt_one] end end inv section real lemma to_real_add (ha : a ≠ ∞) (hb : b ≠ ∞) : (a+b).to_real = a.to_real + b.to_real := begin lift a to ℝ≥0 using ha, lift b to ℝ≥0 using hb, refl end lemma to_real_add_le : (a+b).to_real ≤ a.to_real + b.to_real := if ha : a = ∞ then by simp only [ha, top_add, top_to_real, zero_add, to_real_nonneg] else if hb : b = ∞ then by simp only [hb, add_top, top_to_real, add_zero, to_real_nonneg] else le_of_eq (to_real_add ha hb) lemma of_real_add {p q : ℝ} (hp : 0 ≤ p) (hq : 0 ≤ q) : ennreal.of_real (p + q) = ennreal.of_real p + ennreal.of_real q := by rw [ennreal.of_real, ennreal.of_real, ennreal.of_real, ← coe_add, coe_eq_coe, nnreal.of_real_add hp hq] lemma of_real_add_le {p q : ℝ} : ennreal.of_real (p + q) ≤ ennreal.of_real p + ennreal.of_real q := coe_le_coe.2 nnreal.of_real_add_le @[simp] lemma to_real_le_to_real (ha : a ≠ ∞) (hb : b ≠ ∞) : a.to_real ≤ b.to_real ↔ a ≤ b := begin lift a to ℝ≥0 using ha, lift b to ℝ≥0 using hb, norm_cast end @[simp] lemma to_real_lt_to_real (ha : a ≠ ∞) (hb : b ≠ ∞) : a.to_real < b.to_real ↔ a < b := begin lift a to ℝ≥0 using ha, lift b to ℝ≥0 using hb, norm_cast end lemma to_real_max (hr : a ≠ ∞) (hp : b ≠ ∞) : ennreal.to_real (max a b) = max (ennreal.to_real a) (ennreal.to_real b) := (le_total a b).elim (λ h, by simp only [h, (ennreal.to_real_le_to_real hr hp).2 h, max_eq_right]) (λ h, by simp only [h, (ennreal.to_real_le_to_real hp hr).2 h, max_eq_left]) lemma to_nnreal_pos_iff : 0 < a.to_nnreal ↔ (0 < a ∧ a ≠ ∞) := begin cases a, { simp [none_eq_top] }, { simp [some_eq_coe] } end lemma to_real_pos_iff : 0 < a.to_real ↔ (0 < a ∧ a ≠ ∞):= (nnreal.coe_pos).trans to_nnreal_pos_iff lemma of_real_le_of_real {p q : ℝ} (h : p ≤ q) : ennreal.of_real p ≤ ennreal.of_real q := by simp [ennreal.of_real, nnreal.of_real_le_of_real h] lemma of_real_le_of_le_to_real {a : ℝ} {b : ennreal} (h : a ≤ ennreal.to_real b) : ennreal.of_real a ≤ b := (of_real_le_of_real h).trans of_real_to_real_le @[simp] lemma of_real_le_of_real_iff {p q : ℝ} (h : 0 ≤ q) : ennreal.of_real p ≤ ennreal.of_real q ↔ p ≤ q := by rw [ennreal.of_real, ennreal.of_real, coe_le_coe, nnreal.of_real_le_of_real_iff h] @[simp] lemma of_real_lt_of_real_iff {p q : ℝ} (h : 0 < q) : ennreal.of_real p < ennreal.of_real q ↔ p < q := by rw [ennreal.of_real, ennreal.of_real, coe_lt_coe, nnreal.of_real_lt_of_real_iff h] lemma of_real_lt_of_real_iff_of_nonneg {p q : ℝ} (hp : 0 ≤ p) : ennreal.of_real p < ennreal.of_real q ↔ p < q := by rw [ennreal.of_real, ennreal.of_real, coe_lt_coe, nnreal.of_real_lt_of_real_iff_of_nonneg hp] @[simp] lemma of_real_pos {p : ℝ} : 0 < ennreal.of_real p ↔ 0 < p := by simp [ennreal.of_real] @[simp] lemma of_real_eq_zero {p : ℝ} : ennreal.of_real p = 0 ↔ p ≤ 0 := by simp [ennreal.of_real] lemma of_real_le_iff_le_to_real {a : ℝ} {b : ennreal} (hb : b ≠ ∞) : ennreal.of_real a ≤ b ↔ a ≤ ennreal.to_real b := begin lift b to ℝ≥0 using hb, simpa [ennreal.of_real, ennreal.to_real] using nnreal.of_real_le_iff_le_coe end lemma of_real_lt_iff_lt_to_real {a : ℝ} {b : ennreal} (ha : 0 ≤ a) (hb : b ≠ ∞) : ennreal.of_real a < b ↔ a < ennreal.to_real b := begin lift b to ℝ≥0 using hb, simpa [ennreal.of_real, ennreal.to_real] using nnreal.of_real_lt_iff_lt_coe ha end lemma le_of_real_iff_to_real_le {a : ennreal} {b : ℝ} (ha : a ≠ ∞) (hb : 0 ≤ b) : a ≤ ennreal.of_real b ↔ ennreal.to_real a ≤ b := begin lift a to ℝ≥0 using ha, simpa [ennreal.of_real, ennreal.to_real] using nnreal.le_of_real_iff_coe_le hb end lemma to_real_le_of_le_of_real {a : ennreal} {b : ℝ} (hb : 0 ≤ b) (h : a ≤ ennreal.of_real b) : ennreal.to_real a ≤ b := have ha : a ≠ ∞, from ne_top_of_le_ne_top of_real_ne_top h, (le_of_real_iff_to_real_le ha hb).1 h lemma lt_of_real_iff_to_real_lt {a : ennreal} {b : ℝ} (ha : a ≠ ∞) : a < ennreal.of_real b ↔ ennreal.to_real a < b := begin lift a to ℝ≥0 using ha, simpa [ennreal.of_real, ennreal.to_real] using nnreal.lt_of_real_iff_coe_lt end lemma of_real_mul {p q : ℝ} (hp : 0 ≤ p) : ennreal.of_real (p * q) = (ennreal.of_real p) * (ennreal.of_real q) := by { simp only [ennreal.of_real, coe_mul.symm, coe_eq_coe], exact nnreal.of_real_mul hp } lemma of_real_inv_of_pos {x : ℝ} (hx : 0 < x) : (ennreal.of_real x)⁻¹ = ennreal.of_real x⁻¹ := by rw [ennreal.of_real, ennreal.of_real, ←@coe_inv (nnreal.of_real x) (by simp [hx]), coe_eq_coe, nnreal.of_real_inv.symm] lemma of_real_div_of_pos {x y : ℝ} (hy : 0 < y) : ennreal.of_real (x / y) = ennreal.of_real x / ennreal.of_real y := by rw [div_def, of_real_inv_of_pos hy, mul_comm, ←of_real_mul (inv_nonneg.mpr (le_of_lt hy)), div_eq_mul_inv, mul_comm] lemma to_real_of_real_mul (c : ℝ) (a : ennreal) (h : 0 ≤ c) : ennreal.to_real ((ennreal.of_real c) * a) = c * ennreal.to_real a := begin cases a, { simp only [none_eq_top, ennreal.to_real, top_to_nnreal, nnreal.coe_zero, mul_zero, mul_top], by_cases h' : c ≤ 0, { rw [if_pos], { simp }, { convert of_real_zero, exact le_antisymm h' h } }, { rw [if_neg], refl, rw [of_real_eq_zero], assumption } }, { simp only [ennreal.to_real, ennreal.to_nnreal], simp only [some_eq_coe, ennreal.of_real, coe_mul.symm, to_nnreal_coe, nnreal.coe_mul], congr, apply nnreal.coe_of_real, exact h } end @[simp] lemma to_nnreal_mul_top (a : ennreal) : ennreal.to_nnreal (a * ∞) = 0 := begin by_cases h : a = 0, { rw [h, zero_mul, zero_to_nnreal] }, { rw [mul_top, if_neg h, top_to_nnreal] } end @[simp] lemma to_nnreal_top_mul (a : ennreal) : ennreal.to_nnreal (∞ * a) = 0 := by rw [mul_comm, to_nnreal_mul_top] @[simp] lemma to_real_mul_top (a : ennreal) : ennreal.to_real (a * ∞) = 0 := by rw [ennreal.to_real, to_nnreal_mul_top, nnreal.coe_zero] @[simp] lemma to_real_top_mul (a : ennreal) : ennreal.to_real (∞ * a) = 0 := by { rw mul_comm, exact to_real_mul_top _ } lemma to_real_eq_to_real (ha : a < ∞) (hb : b < ∞) : ennreal.to_real a = ennreal.to_real b ↔ a = b := begin lift a to ℝ≥0 using ha.ne, lift b to ℝ≥0 using hb.ne, simp only [coe_eq_coe, nnreal.coe_eq, coe_to_real], end /-- `ennreal.to_nnreal` as a `monoid_hom`. -/ def to_nnreal_hom : ennreal →* ℝ≥0 := { to_fun := ennreal.to_nnreal, map_one' := to_nnreal_coe, map_mul' := by rintro (_|x) (_|y); simp only [← coe_mul, none_eq_top, some_eq_coe, to_nnreal_top_mul, to_nnreal_mul_top, top_to_nnreal, mul_zero, zero_mul, to_nnreal_coe] } lemma to_nnreal_mul {a b : ennreal}: (a * b).to_nnreal = a.to_nnreal * b.to_nnreal := to_nnreal_hom.map_mul a b lemma to_nnreal_pow (a : ennreal) (n : ℕ) : (a ^ n).to_nnreal = a.to_nnreal ^ n := to_nnreal_hom.map_pow a n lemma to_nnreal_prod {ι : Type*} {s : finset ι} {f : ι → ennreal} : (∏ i in s, f i).to_nnreal = ∏ i in s, (f i).to_nnreal := to_nnreal_hom.map_prod _ _ /-- `ennreal.to_real` as a `monoid_hom`. -/ def to_real_hom : ennreal →* ℝ := (nnreal.to_real_hom : ℝ≥0 →* ℝ).comp to_nnreal_hom lemma to_real_mul : (a * b).to_real = a.to_real * b.to_real := to_real_hom.map_mul a b lemma to_real_pow (a : ennreal) (n : ℕ) : (a ^ n).to_real = a.to_real ^ n := to_real_hom.map_pow a n lemma to_real_prod {ι : Type*} {s : finset ι} {f : ι → ennreal} : (∏ i in s, f i).to_real = ∏ i in s, (f i).to_real := to_real_hom.map_prod _ _ end real section infi variables {ι : Sort*} {f g : ι → ennreal} lemma infi_add : infi f + a = ⨅i, f i + a := le_antisymm (le_infi $ assume i, add_le_add (infi_le _ _) $ le_refl _) (ennreal.sub_le_iff_le_add.1 $ le_infi $ assume i, ennreal.sub_le_iff_le_add.2 $ infi_le _ _) lemma supr_sub : (⨆i, f i) - a = (⨆i, f i - a) := le_antisymm (ennreal.sub_le_iff_le_add.2 $ supr_le $ assume i, ennreal.sub_le_iff_le_add.1 $ le_supr _ i) (supr_le $ assume i, ennreal.sub_le_sub (le_supr _ _) (le_refl a)) lemma sub_infi : a - (⨅i, f i) = (⨆i, a - f i) := begin refine (eq_of_forall_ge_iff $ λ c, _), rw [ennreal.sub_le_iff_le_add, add_comm, infi_add], simp [ennreal.sub_le_iff_le_add, sub_eq_add_neg, add_comm], end lemma Inf_add {s : set ennreal} : Inf s + a = ⨅b∈s, b + a := by simp [Inf_eq_infi, infi_add] lemma add_infi {a : ennreal} : a + infi f = ⨅b, a + f b := by rw [add_comm, infi_add]; simp [add_comm] lemma infi_add_infi (h : ∀i j, ∃k, f k + g k ≤ f i + g j) : infi f + infi g = (⨅a, f a + g a) := suffices (⨅a, f a + g a) ≤ infi f + infi g, from le_antisymm (le_infi $ assume a, add_le_add (infi_le _ _) (infi_le _ _)) this, calc (⨅a, f a + g a) ≤ (⨅ a a', f a + g a') : le_infi $ assume a, le_infi $ assume a', let ⟨k, h⟩ := h a a' in infi_le_of_le k h ... ≤ infi f + infi g : by simp [add_infi, infi_add, -add_comm, -le_infi_iff]; exact le_refl _ lemma infi_sum {f : ι → α → ennreal} {s : finset α} [nonempty ι] (h : ∀(t : finset α) (i j : ι), ∃k, ∀a∈t, f k a ≤ f i a ∧ f k a ≤ f j a) : (⨅i, ∑ a in s, f i a) = ∑ a in s, ⨅i, f i a := finset.induction_on s (by simp) $ assume a s ha ih, have ∀ (i j : ι), ∃ (k : ι), f k a + ∑ b in s, f k b ≤ f i a + ∑ b in s, f j b, from assume i j, let ⟨k, hk⟩ := h (insert a s) i j in ⟨k, add_le_add (hk a (finset.mem_insert_self _ _)).left $ finset.sum_le_sum $ assume a ha, (hk _ $ finset.mem_insert_of_mem ha).right⟩, by simp [ha, ih.symm, infi_add_infi this] lemma infi_mul {ι} [nonempty ι] {f : ι → ennreal} {x : ennreal} (h : x ≠ ∞) : infi f * x = ⨅i, f i * x := begin by_cases h2 : x = 0, simp only [h2, mul_zero, infi_const], refine le_antisymm (le_infi $ λ i, mul_right_mono $ infi_le _ _) ((div_le_iff_le_mul (or.inl h2) $ or.inl h).mp $ le_infi $ λ i, (div_le_iff_le_mul (or.inl h2) $ or.inl h).mpr $ infi_le _ _) end lemma mul_infi {ι} [nonempty ι] {f : ι → ennreal} {x : ennreal} (h : x ≠ ∞) : x * infi f = ⨅i, x * f i := by { rw [mul_comm, infi_mul h], simp only [mul_comm], assumption } /-! `supr_mul`, `mul_supr` and variants are in `topology.instances.ennreal`. -/ end infi section supr lemma supr_coe_nat : (⨆n:ℕ, (n : ennreal)) = ∞ := (supr_eq_top _).2 $ assume b hb, ennreal.exists_nat_gt (lt_top_iff_ne_top.1 hb) end supr /-- `le_of_add_le_add_left` is normally applicable to `ordered_cancel_add_comm_monoid`, but it holds in `ennreal` with the additional assumption that `a < ∞`. -/ lemma le_of_add_le_add_left {a b c : ennreal} : a < ∞ → a + b ≤ a + c → b ≤ c := by cases a; cases b; cases c; simp [← ennreal.coe_add, ennreal.coe_le_coe] end ennreal
9093f6c18e22b023d552103c6e7f044862778bf2
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/limits/shapes/equalizers.lean
750dc84ea4f73c4f17d39146b3ae07d337ddea1e
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
45,892
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Markus Himmel -/ import category_theory.epi_mono import category_theory.limits.has_limits /-! # Equalizers and coequalizers This file defines (co)equalizers as special cases of (co)limits. An equalizer is the categorical generalization of the subobject {a ∈ A | f(a) = g(a)} known from abelian groups or modules. It is a limit cone over the diagram formed by `f` and `g`. A coequalizer is the dual concept. ## Main definitions * `walking_parallel_pair` is the indexing category used for (co)equalizer_diagrams * `parallel_pair` is a functor from `walking_parallel_pair` to our category `C`. * a `fork` is a cone over a parallel pair. * there is really only one interesting morphism in a fork: the arrow from the vertex of the fork to the domain of f and g. It is called `fork.ι`. * an `equalizer` is now just a `limit (parallel_pair f g)` Each of these has a dual. ## Main statements * `equalizer.ι_mono` states that every equalizer map is a monomorphism * `is_iso_limit_cone_parallel_pair_of_self` states that the identity on the domain of `f` is an equalizer of `f` and `f`. ## Implementation notes As with the other special shapes in the limits library, all the definitions here are given as `abbreviation`s of the general statements for limits, so all the `simp` lemmas and theorems about general limits can be used. ## References * [F. Borceux, *Handbook of Categorical Algebra 1*][borceux-vol1] -/ noncomputable theory open category_theory opposite namespace category_theory.limits local attribute [tidy] tactic.case_bash universes v v₂ u u₂ /-- The type of objects for the diagram indexing a (co)equalizer. -/ @[derive decidable_eq, derive inhabited] inductive walking_parallel_pair : Type | zero | one open walking_parallel_pair /-- The type family of morphisms for the diagram indexing a (co)equalizer. -/ @[derive decidable_eq] inductive walking_parallel_pair_hom : walking_parallel_pair → walking_parallel_pair → Type | left : walking_parallel_pair_hom zero one | right : walking_parallel_pair_hom zero one | id : Π X : walking_parallel_pair, walking_parallel_pair_hom X X /-- Satisfying the inhabited linter -/ instance : inhabited (walking_parallel_pair_hom zero one) := { default := walking_parallel_pair_hom.left } open walking_parallel_pair_hom /-- Composition of morphisms in the indexing diagram for (co)equalizers. -/ def walking_parallel_pair_hom.comp : Π (X Y Z : walking_parallel_pair) (f : walking_parallel_pair_hom X Y) (g : walking_parallel_pair_hom Y Z), walking_parallel_pair_hom X Z | _ _ _ (id _) h := h | _ _ _ left (id one) := left | _ _ _ right (id one) := right . instance walking_parallel_pair_hom_category : small_category walking_parallel_pair := { hom := walking_parallel_pair_hom, id := walking_parallel_pair_hom.id, comp := walking_parallel_pair_hom.comp } @[simp] lemma walking_parallel_pair_hom_id (X : walking_parallel_pair) : walking_parallel_pair_hom.id X = 𝟙 X := rfl /-- The functor `walking_parallel_pair ⥤ walking_parallel_pairᵒᵖ` sending left to left and right to right. -/ def walking_parallel_pair_op : walking_parallel_pair ⥤ walking_parallel_pairᵒᵖ := { obj := (λ x, op $ by { cases x, exacts [one, zero] }), map := λ i j f, by { cases f; apply quiver.hom.op, exacts [left, right, walking_parallel_pair_hom.id _] }, map_comp' := by { rintros (_|_) (_|_) (_|_) (_|_|_) (_|_|_); refl } } @[simp] lemma walking_parallel_pair_op_zero : walking_parallel_pair_op.obj zero = op one := rfl @[simp] lemma walking_parallel_pair_op_one : walking_parallel_pair_op.obj one = op zero := rfl @[simp] lemma walking_parallel_pair_op_left : walking_parallel_pair_op.map left = @quiver.hom.op _ _ zero one left := rfl @[simp] lemma walking_parallel_pair_op_right : walking_parallel_pair_op.map right = @quiver.hom.op _ _ zero one right := rfl /-- The equivalence `walking_parallel_pair ⥤ walking_parallel_pairᵒᵖ` sending left to left and right to right. -/ @[simps functor inverse] def walking_parallel_pair_op_equiv : walking_parallel_pair ≌ walking_parallel_pairᵒᵖ := { functor := walking_parallel_pair_op, inverse := walking_parallel_pair_op.left_op, unit_iso := nat_iso.of_components (λ j, eq_to_iso (by { cases j; refl })) (by { rintros (_|_) (_|_) (_|_|_); refl }), counit_iso := nat_iso.of_components (λ j, eq_to_iso (by { induction j using opposite.rec, cases j; refl })) (λ i j f, by { induction i using opposite.rec, induction j using opposite.rec, let g := f.unop, have : f = g.op := rfl, clear_value g, subst this, rcases i with (_|_); rcases j with (_|_); rcases g with (_|_|_); refl }) } @[simp] lemma walking_parallel_pair_op_equiv_unit_iso_zero : walking_parallel_pair_op_equiv.unit_iso.app zero = iso.refl zero := rfl @[simp] lemma walking_parallel_pair_op_equiv_unit_iso_one : walking_parallel_pair_op_equiv.unit_iso.app one = iso.refl one := rfl @[simp] lemma walking_parallel_pair_op_equiv_counit_iso_zero : walking_parallel_pair_op_equiv.counit_iso.app (op zero) = iso.refl (op zero) := rfl @[simp] lemma walking_parallel_pair_op_equiv_counit_iso_one : walking_parallel_pair_op_equiv.counit_iso.app (op one) = iso.refl (op one) := rfl variables {C : Type u} [category.{v} C] variables {X Y : C} /-- `parallel_pair f g` is the diagram in `C` consisting of the two morphisms `f` and `g` with common domain and codomain. -/ def parallel_pair (f g : X ⟶ Y) : walking_parallel_pair ⥤ C := { obj := λ x, match x with | zero := X | one := Y end, map := λ x y h, match x, y, h with | _, _, (id _) := 𝟙 _ | _, _, left := f | _, _, right := g end, -- `tidy` can cope with this, but it's too slow: map_comp' := begin rintros (⟨⟩|⟨⟩) (⟨⟩|⟨⟩) (⟨⟩|⟨⟩) ⟨⟩⟨⟩; { unfold_aux, simp; refl }, end, }. @[simp] lemma parallel_pair_obj_zero (f g : X ⟶ Y) : (parallel_pair f g).obj zero = X := rfl @[simp] lemma parallel_pair_obj_one (f g : X ⟶ Y) : (parallel_pair f g).obj one = Y := rfl @[simp] lemma parallel_pair_map_left (f g : X ⟶ Y) : (parallel_pair f g).map left = f := rfl @[simp] lemma parallel_pair_map_right (f g : X ⟶ Y) : (parallel_pair f g).map right = g := rfl @[simp] lemma parallel_pair_functor_obj {F : walking_parallel_pair ⥤ C} (j : walking_parallel_pair) : (parallel_pair (F.map left) (F.map right)).obj j = F.obj j := begin cases j; refl end /-- Every functor indexing a (co)equalizer is naturally isomorphic (actually, equal) to a `parallel_pair` -/ @[simps] def diagram_iso_parallel_pair (F : walking_parallel_pair ⥤ C) : F ≅ parallel_pair (F.map left) (F.map right) := nat_iso.of_components (λ j, eq_to_iso $ by cases j; tidy) $ by tidy /-- Construct a morphism between parallel pairs. -/ def parallel_pair_hom {X' Y' : C} (f g : X ⟶ Y) (f' g' : X' ⟶ Y') (p : X ⟶ X') (q : Y ⟶ Y') (wf : f ≫ q = p ≫ f') (wg : g ≫ q = p ≫ g') : parallel_pair f g ⟶ parallel_pair f' g' := { app := λ j, match j with | zero := p | one := q end, naturality' := begin rintros (⟨⟩|⟨⟩) (⟨⟩|⟨⟩) ⟨⟩; { unfold_aux, simp [wf, wg], }, end } @[simp] lemma parallel_pair_hom_app_zero {X' Y' : C} (f g : X ⟶ Y) (f' g' : X' ⟶ Y') (p : X ⟶ X') (q : Y ⟶ Y') (wf : f ≫ q = p ≫ f') (wg : g ≫ q = p ≫ g') : (parallel_pair_hom f g f' g' p q wf wg).app zero = p := rfl @[simp] lemma parallel_pair_hom_app_one {X' Y' : C} (f g : X ⟶ Y) (f' g' : X' ⟶ Y') (p : X ⟶ X') (q : Y ⟶ Y') (wf : f ≫ q = p ≫ f') (wg : g ≫ q = p ≫ g') : (parallel_pair_hom f g f' g' p q wf wg).app one = q := rfl /-- Construct a natural isomorphism between functors out of the walking parallel pair from its components. -/ @[simps] def parallel_pair.ext {F G : walking_parallel_pair ⥤ C} (zero : F.obj zero ≅ G.obj zero) (one : F.obj one ≅ G.obj one) (left : F.map left ≫ one.hom = zero.hom ≫ G.map left) (right : F.map right ≫ one.hom = zero.hom ≫ G.map right) : F ≅ G := nat_iso.of_components (by { rintro ⟨j⟩, exacts [zero, one] }) (by { rintro ⟨j₁⟩ ⟨j₂⟩ ⟨f⟩; simp [left, right], }) /-- Construct a natural isomorphism between `parallel_pair f g` and `parallel_pair f' g'` given equalities `f = f'` and `g = g'`. -/ @[simps] def parallel_pair.eq_of_hom_eq {f g f' g' : X ⟶ Y} (hf : f = f') (hg : g = g') : parallel_pair f g ≅ parallel_pair f' g' := parallel_pair.ext (iso.refl _) (iso.refl _) (by simp [hf]) (by simp [hg]) /-- A fork on `f` and `g` is just a `cone (parallel_pair f g)`. -/ abbreviation fork (f g : X ⟶ Y) := cone (parallel_pair f g) /-- A cofork on `f` and `g` is just a `cocone (parallel_pair f g)`. -/ abbreviation cofork (f g : X ⟶ Y) := cocone (parallel_pair f g) variables {f g : X ⟶ Y} /-- A fork `t` on the parallel pair `f g : X ⟶ Y` consists of two morphisms `t.π.app zero : t.X ⟶ X` and `t.π.app one : t.X ⟶ Y`. Of these, only the first one is interesting, and we give it the shorter name `fork.ι t`. -/ def fork.ι (t : fork f g) := t.π.app zero @[simp] lemma fork.app_zero_eq_ι (t : fork f g) : t.π.app zero = t.ι := rfl /-- A cofork `t` on the parallel_pair `f g : X ⟶ Y` consists of two morphisms `t.ι.app zero : X ⟶ t.X` and `t.ι.app one : Y ⟶ t.X`. Of these, only the second one is interesting, and we give it the shorter name `cofork.π t`. -/ def cofork.π (t : cofork f g) := t.ι.app one @[simp] lemma cofork.app_one_eq_π (t : cofork f g) : t.ι.app one = t.π := rfl @[simp] lemma fork.app_one_eq_ι_comp_left (s : fork f g) : s.π.app one = s.ι ≫ f := by rw [←s.app_zero_eq_ι, ←s.w left, parallel_pair_map_left] @[reassoc] lemma fork.app_one_eq_ι_comp_right (s : fork f g) : s.π.app one = s.ι ≫ g := by rw [←s.app_zero_eq_ι, ←s.w right, parallel_pair_map_right] @[simp] lemma cofork.app_zero_eq_comp_π_left (s : cofork f g) : s.ι.app zero = f ≫ s.π := by rw [←s.app_one_eq_π, ←s.w left, parallel_pair_map_left] @[reassoc] lemma cofork.app_zero_eq_comp_π_right (s : cofork f g) : s.ι.app zero = g ≫ s.π := by rw [←s.app_one_eq_π, ←s.w right, parallel_pair_map_right] /-- A fork on `f g : X ⟶ Y` is determined by the morphism `ι : P ⟶ X` satisfying `ι ≫ f = ι ≫ g`. -/ @[simps] def fork.of_ι {P : C} (ι : P ⟶ X) (w : ι ≫ f = ι ≫ g) : fork f g := { X := P, π := { app := λ X, begin cases X, exact ι, exact ι ≫ f, end, naturality' := λ X Y f, begin cases X; cases Y; cases f; dsimp; simp, { dsimp, simp, }, -- See note [dsimp, simp]. { exact w }, { dsimp, simp, }, end } } /-- A cofork on `f g : X ⟶ Y` is determined by the morphism `π : Y ⟶ P` satisfying `f ≫ π = g ≫ π`. -/ @[simps] def cofork.of_π {P : C} (π : Y ⟶ P) (w : f ≫ π = g ≫ π) : cofork f g := { X := P, ι := { app := λ X, walking_parallel_pair.cases_on X (f ≫ π) π, naturality' := λ i j f, by { cases f; dsimp; simp [w] } } } -- See note [dsimp, simp] @[simp] lemma fork.ι_of_ι {P : C} (ι : P ⟶ X) (w : ι ≫ f = ι ≫ g) : (fork.of_ι ι w).ι = ι := rfl @[simp] lemma cofork.π_of_π {P : C} (π : Y ⟶ P) (w : f ≫ π = g ≫ π) : (cofork.of_π π w).π = π := rfl @[simp, reassoc] lemma fork.condition (t : fork f g) : t.ι ≫ f = t.ι ≫ g := by rw [←t.app_one_eq_ι_comp_left, ←t.app_one_eq_ι_comp_right] @[simp, reassoc] lemma cofork.condition (t : cofork f g) : f ≫ t.π = g ≫ t.π := by rw [←t.app_zero_eq_comp_π_left, ←t.app_zero_eq_comp_π_right] /-- To check whether two maps are equalized by both maps of a fork, it suffices to check it for the first map -/ lemma fork.equalizer_ext (s : fork f g) {W : C} {k l : W ⟶ s.X} (h : k ≫ s.ι = l ≫ s.ι) : ∀ (j : walking_parallel_pair), k ≫ s.π.app j = l ≫ s.π.app j | zero := h | one := by rw [s.app_one_eq_ι_comp_left, reassoc_of h] /-- To check whether two maps are coequalized by both maps of a cofork, it suffices to check it for the second map -/ lemma cofork.coequalizer_ext (s : cofork f g) {W : C} {k l : s.X ⟶ W} (h : cofork.π s ≫ k = cofork.π s ≫ l) : ∀ (j : walking_parallel_pair), s.ι.app j ≫ k = s.ι.app j ≫ l | zero := by simp only [s.app_zero_eq_comp_π_left, category.assoc, h] | one := h lemma fork.is_limit.hom_ext {s : fork f g} (hs : is_limit s) {W : C} {k l : W ⟶ s.X} (h : k ≫ fork.ι s = l ≫ fork.ι s) : k = l := hs.hom_ext $ fork.equalizer_ext _ h lemma cofork.is_colimit.hom_ext {s : cofork f g} (hs : is_colimit s) {W : C} {k l : s.X ⟶ W} (h : cofork.π s ≫ k = cofork.π s ≫ l) : k = l := hs.hom_ext $ cofork.coequalizer_ext _ h @[simp, reassoc] lemma fork.is_limit.lift_ι {s t : fork f g} (hs : is_limit s) : hs.lift t ≫ s.ι = t.ι := hs.fac _ _ @[simp, reassoc] lemma cofork.is_colimit.π_desc {s t : cofork f g} (hs : is_colimit s) : s.π ≫ hs.desc t = t.π := hs.fac _ _ /-- If `s` is a limit fork over `f` and `g`, then a morphism `k : W ⟶ X` satisfying `k ≫ f = k ≫ g` induces a morphism `l : W ⟶ s.X` such that `l ≫ fork.ι s = k`. -/ def fork.is_limit.lift' {s : fork f g} (hs : is_limit s) {W : C} (k : W ⟶ X) (h : k ≫ f = k ≫ g) : {l : W ⟶ s.X // l ≫ fork.ι s = k} := ⟨hs.lift $ fork.of_ι _ h, hs.fac _ _⟩ /-- If `s` is a colimit cofork over `f` and `g`, then a morphism `k : Y ⟶ W` satisfying `f ≫ k = g ≫ k` induces a morphism `l : s.X ⟶ W` such that `cofork.π s ≫ l = k`. -/ def cofork.is_colimit.desc' {s : cofork f g} (hs : is_colimit s) {W : C} (k : Y ⟶ W) (h : f ≫ k = g ≫ k) : {l : s.X ⟶ W // cofork.π s ≫ l = k} := ⟨hs.desc $ cofork.of_π _ h, hs.fac _ _⟩ lemma fork.is_limit.exists_unique {s : fork f g} (hs : is_limit s) {W : C} (k : W ⟶ X) (h : k ≫ f = k ≫ g) : ∃! (l : W ⟶ s.X), l ≫ fork.ι s = k := ⟨hs.lift $ fork.of_ι _ h, hs.fac _ _, λ m hm, fork.is_limit.hom_ext hs $ hm.symm ▸ (hs.fac (fork.of_ι _ h) walking_parallel_pair.zero).symm⟩ lemma cofork.is_colimit.exists_unique {s : cofork f g} (hs : is_colimit s) {W : C} (k : Y ⟶ W) (h : f ≫ k = g ≫ k) : ∃! (d : s.X ⟶ W), cofork.π s ≫ d = k := ⟨hs.desc $ cofork.of_π _ h, hs.fac _ _, λ m hm, cofork.is_colimit.hom_ext hs $ hm.symm ▸ (hs.fac (cofork.of_π _ h) walking_parallel_pair.one).symm⟩ /-- This is a slightly more convenient method to verify that a fork is a limit cone. It only asks for a proof of facts that carry any mathematical content -/ @[simps lift] def fork.is_limit.mk (t : fork f g) (lift : Π (s : fork f g), s.X ⟶ t.X) (fac : ∀ (s : fork f g), lift s ≫ fork.ι t = fork.ι s) (uniq : ∀ (s : fork f g) (m : s.X ⟶ t.X) (w : m ≫ t.ι = s.ι), m = lift s) : is_limit t := { lift := lift, fac' := λ s j, walking_parallel_pair.cases_on j (fac s) $ by erw [←s.w left, ←t.w left, ←category.assoc, fac]; refl, uniq' := λ s m j, by tidy } /-- This is another convenient method to verify that a fork is a limit cone. It only asks for a proof of facts that carry any mathematical content, and allows access to the same `s` for all parts. -/ def fork.is_limit.mk' {X Y : C} {f g : X ⟶ Y} (t : fork f g) (create : Π (s : fork f g), {l // l ≫ t.ι = s.ι ∧ ∀ {m}, m ≫ t.ι = s.ι → m = l}) : is_limit t := fork.is_limit.mk t (λ s, (create s).1) (λ s, (create s).2.1) (λ s m w, (create s).2.2 w) /-- This is a slightly more convenient method to verify that a cofork is a colimit cocone. It only asks for a proof of facts that carry any mathematical content -/ def cofork.is_colimit.mk (t : cofork f g) (desc : Π (s : cofork f g), t.X ⟶ s.X) (fac : ∀ (s : cofork f g), cofork.π t ≫ desc s = cofork.π s) (uniq : ∀ (s : cofork f g) (m : t.X ⟶ s.X) (w : t.π ≫ m = s.π), m = desc s) : is_colimit t := { desc := desc, fac' := λ s j, walking_parallel_pair.cases_on j (by erw [←s.w left, ←t.w left, category.assoc, fac]; refl) (fac s), uniq' := by tidy } /-- This is another convenient method to verify that a fork is a limit cone. It only asks for a proof of facts that carry any mathematical content, and allows access to the same `s` for all parts. -/ def cofork.is_colimit.mk' {X Y : C} {f g : X ⟶ Y} (t : cofork f g) (create : Π (s : cofork f g), {l : t.X ⟶ s.X // t.π ≫ l = s.π ∧ ∀ {m}, t.π ≫ m = s.π → m = l}) : is_colimit t := cofork.is_colimit.mk t (λ s, (create s).1) (λ s, (create s).2.1) (λ s m w, (create s).2.2 w) /-- Noncomputably make a limit cone from the existence of unique factorizations. -/ def fork.is_limit.of_exists_unique {t : fork f g} (hs : ∀ (s : fork f g), ∃! l : s.X ⟶ t.X, l ≫ fork.ι t = fork.ι s) : is_limit t := by { choose d hd hd' using hs, exact fork.is_limit.mk _ d hd (λ s m hm, hd' _ _ hm) } /-- Noncomputably make a colimit cocone from the existence of unique factorizations. -/ def cofork.is_colimit.of_exists_unique {t : cofork f g} (hs : ∀ (s : cofork f g), ∃! d : t.X ⟶ s.X, cofork.π t ≫ d = cofork.π s) : is_colimit t := by { choose d hd hd' using hs, exact cofork.is_colimit.mk _ d hd (λ s m hm, hd' _ _ hm) } /-- Given a limit cone for the pair `f g : X ⟶ Y`, for any `Z`, morphisms from `Z` to its point are in bijection with morphisms `h : Z ⟶ X` such that `h ≫ f = h ≫ g`. Further, this bijection is natural in `Z`: see `fork.is_limit.hom_iso_natural`. This is a special case of `is_limit.hom_iso'`, often useful to construct adjunctions. -/ @[simps] def fork.is_limit.hom_iso {X Y : C} {f g : X ⟶ Y} {t : fork f g} (ht : is_limit t) (Z : C) : (Z ⟶ t.X) ≃ {h : Z ⟶ X // h ≫ f = h ≫ g} := { to_fun := λ k, ⟨k ≫ t.ι, by simp only [category.assoc, t.condition]⟩, inv_fun := λ h, (fork.is_limit.lift' ht _ h.prop).1, left_inv := λ k, fork.is_limit.hom_ext ht (fork.is_limit.lift' _ _ _).prop, right_inv := λ h, subtype.ext (fork.is_limit.lift' ht _ _).prop } /-- The bijection of `fork.is_limit.hom_iso` is natural in `Z`. -/ lemma fork.is_limit.hom_iso_natural {X Y : C} {f g : X ⟶ Y} {t : fork f g} (ht : is_limit t) {Z Z' : C} (q : Z' ⟶ Z) (k : Z ⟶ t.X) : (fork.is_limit.hom_iso ht _ (q ≫ k) : Z' ⟶ X) = q ≫ (fork.is_limit.hom_iso ht _ k : Z ⟶ X) := category.assoc _ _ _ /-- Given a colimit cocone for the pair `f g : X ⟶ Y`, for any `Z`, morphisms from the cocone point to `Z` are in bijection with morphisms `h : Y ⟶ Z` such that `f ≫ h = g ≫ h`. Further, this bijection is natural in `Z`: see `cofork.is_colimit.hom_iso_natural`. This is a special case of `is_colimit.hom_iso'`, often useful to construct adjunctions. -/ @[simps] def cofork.is_colimit.hom_iso {X Y : C} {f g : X ⟶ Y} {t : cofork f g} (ht : is_colimit t) (Z : C) : (t.X ⟶ Z) ≃ {h : Y ⟶ Z // f ≫ h = g ≫ h} := { to_fun := λ k, ⟨t.π ≫ k, by simp only [←category.assoc, t.condition]⟩, inv_fun := λ h, (cofork.is_colimit.desc' ht _ h.prop).1, left_inv := λ k, cofork.is_colimit.hom_ext ht (cofork.is_colimit.desc' _ _ _).prop, right_inv := λ h, subtype.ext (cofork.is_colimit.desc' ht _ _).prop } /-- The bijection of `cofork.is_colimit.hom_iso` is natural in `Z`. -/ lemma cofork.is_colimit.hom_iso_natural {X Y : C} {f g : X ⟶ Y} {t : cofork f g} {Z Z' : C} (q : Z ⟶ Z') (ht : is_colimit t) (k : t.X ⟶ Z) : (cofork.is_colimit.hom_iso ht _ (k ≫ q) : Y ⟶ Z') = (cofork.is_colimit.hom_iso ht _ k : Y ⟶ Z) ≫ q := (category.assoc _ _ _).symm /-- This is a helper construction that can be useful when verifying that a category has all equalizers. Given `F : walking_parallel_pair ⥤ C`, which is really the same as `parallel_pair (F.map left) (F.map right)`, and a fork on `F.map left` and `F.map right`, we get a cone on `F`. If you're thinking about using this, have a look at `has_equalizers_of_has_limit_parallel_pair`, which you may find to be an easier way of achieving your goal. -/ def cone.of_fork {F : walking_parallel_pair ⥤ C} (t : fork (F.map left) (F.map right)) : cone F := { X := t.X, π := { app := λ X, t.π.app X ≫ eq_to_hom (by tidy), naturality' := λ j j' g, by { cases j; cases j'; cases g; dsimp; simp } } } /-- This is a helper construction that can be useful when verifying that a category has all coequalizers. Given `F : walking_parallel_pair ⥤ C`, which is really the same as `parallel_pair (F.map left) (F.map right)`, and a cofork on `F.map left` and `F.map right`, we get a cocone on `F`. If you're thinking about using this, have a look at `has_coequalizers_of_has_colimit_parallel_pair`, which you may find to be an easier way of achieving your goal. -/ def cocone.of_cofork {F : walking_parallel_pair ⥤ C} (t : cofork (F.map left) (F.map right)) : cocone F := { X := t.X, ι := { app := λ X, eq_to_hom (by tidy) ≫ t.ι.app X, naturality' := λ j j' g, by { cases j; cases j'; cases g; dsimp; simp } } } @[simp] lemma cone.of_fork_π {F : walking_parallel_pair ⥤ C} (t : fork (F.map left) (F.map right)) (j) : (cone.of_fork t).π.app j = t.π.app j ≫ eq_to_hom (by tidy) := rfl @[simp] lemma cocone.of_cofork_ι {F : walking_parallel_pair ⥤ C} (t : cofork (F.map left) (F.map right)) (j) : (cocone.of_cofork t).ι.app j = eq_to_hom (by tidy) ≫ t.ι.app j := rfl /-- Given `F : walking_parallel_pair ⥤ C`, which is really the same as `parallel_pair (F.map left) (F.map right)` and a cone on `F`, we get a fork on `F.map left` and `F.map right`. -/ def fork.of_cone {F : walking_parallel_pair ⥤ C} (t : cone F) : fork (F.map left) (F.map right) := { X := t.X, π := { app := λ X, t.π.app X ≫ eq_to_hom (by tidy) } } /-- Given `F : walking_parallel_pair ⥤ C`, which is really the same as `parallel_pair (F.map left) (F.map right)` and a cocone on `F`, we get a cofork on `F.map left` and `F.map right`. -/ def cofork.of_cocone {F : walking_parallel_pair ⥤ C} (t : cocone F) : cofork (F.map left) (F.map right) := { X := t.X, ι := { app := λ X, eq_to_hom (by tidy) ≫ t.ι.app X } } @[simp] lemma fork.of_cone_π {F : walking_parallel_pair ⥤ C} (t : cone F) (j) : (fork.of_cone t).π.app j = t.π.app j ≫ eq_to_hom (by tidy) := rfl @[simp] lemma cofork.of_cocone_ι {F : walking_parallel_pair ⥤ C} (t : cocone F) (j) : (cofork.of_cocone t).ι.app j = eq_to_hom (by tidy) ≫ t.ι.app j := rfl @[simp] lemma fork.ι_postcompose {f' g' : X ⟶ Y} {α : parallel_pair f g ⟶ parallel_pair f' g'} {c : fork f g} : fork.ι ((cones.postcompose α).obj c) = c.ι ≫ α.app _ := rfl @[simp] lemma cofork.π_precompose {f' g' : X ⟶ Y} {α : parallel_pair f g ⟶ parallel_pair f' g'} {c : cofork f' g'} : cofork.π ((cocones.precompose α).obj c) = α.app _ ≫ c.π := rfl /-- Helper function for constructing morphisms between equalizer forks. -/ @[simps] def fork.mk_hom {s t : fork f g} (k : s.X ⟶ t.X) (w : k ≫ t.ι = s.ι) : s ⟶ t := { hom := k, w' := begin rintro ⟨_|_⟩, { exact w }, { simp only [fork.app_one_eq_ι_comp_left, reassoc_of w] }, end } /-- To construct an isomorphism between forks, it suffices to give an isomorphism between the cone points and check that it commutes with the `ι` morphisms. -/ @[simps] def fork.ext {s t : fork f g} (i : s.X ≅ t.X) (w : i.hom ≫ t.ι = s.ι) : s ≅ t := { hom := fork.mk_hom i.hom w, inv := fork.mk_hom i.inv (by rw [← w, iso.inv_hom_id_assoc]) } /-- Every fork is isomorphic to one of the form `fork.of_ι _ _`. -/ def fork.iso_fork_of_ι (c : fork f g) : c ≅ fork.of_ι c.ι c.condition := fork.ext (by simp only [fork.of_ι_X, functor.const_obj_obj]) (by simp) /-- Helper function for constructing morphisms between coequalizer coforks. -/ @[simps] def cofork.mk_hom {s t : cofork f g} (k : s.X ⟶ t.X) (w : s.π ≫ k = t.π) : s ⟶ t := { hom := k, w' := begin rintro ⟨_|_⟩, { simp [cofork.app_zero_eq_comp_π_left, w] }, { exact w } end } @[simp, reassoc] lemma fork.hom_comp_ι {s t : fork f g} (f : s ⟶ t) : f.hom ≫ t.ι = s.ι := by tidy @[simp, reassoc] lemma fork.π_comp_hom {s t : cofork f g} (f : s ⟶ t) : s.π ≫ f.hom = t.π := by tidy /-- To construct an isomorphism between coforks, it suffices to give an isomorphism between the cocone points and check that it commutes with the `π` morphisms. -/ @[simps] def cofork.ext {s t : cofork f g} (i : s.X ≅ t.X) (w : s.π ≫ i.hom = t.π) : s ≅ t := { hom := cofork.mk_hom i.hom w, inv := cofork.mk_hom i.inv (by rw [iso.comp_inv_eq, w]) } /-- Every cofork is isomorphic to one of the form `cofork.of_π _ _`. -/ def cofork.iso_cofork_of_π (c : cofork f g) : c ≅ cofork.of_π c.π c.condition := cofork.ext (by simp only [cofork.of_π_X, functor.const_obj_obj]) (by dsimp; simp) variables (f g) section /-- `has_equalizer f g` represents a particular choice of limiting cone for the parallel pair of morphisms `f` and `g`. -/ abbreviation has_equalizer := has_limit (parallel_pair f g) variables [has_equalizer f g] /-- If an equalizer of `f` and `g` exists, we can access an arbitrary choice of such by saying `equalizer f g`. -/ abbreviation equalizer : C := limit (parallel_pair f g) /-- If an equalizer of `f` and `g` exists, we can access the inclusion `equalizer f g ⟶ X` by saying `equalizer.ι f g`. -/ abbreviation equalizer.ι : equalizer f g ⟶ X := limit.π (parallel_pair f g) zero /-- An equalizer cone for a parallel pair `f` and `g`. -/ abbreviation equalizer.fork : fork f g := limit.cone (parallel_pair f g) @[simp] lemma equalizer.fork_ι : (equalizer.fork f g).ι = equalizer.ι f g := rfl @[simp] lemma equalizer.fork_π_app_zero : (equalizer.fork f g).π.app zero = equalizer.ι f g := rfl @[reassoc] lemma equalizer.condition : equalizer.ι f g ≫ f = equalizer.ι f g ≫ g := fork.condition $ limit.cone $ parallel_pair f g /-- The equalizer built from `equalizer.ι f g` is limiting. -/ def equalizer_is_equalizer : is_limit (fork.of_ι (equalizer.ι f g) (equalizer.condition f g)) := is_limit.of_iso_limit (limit.is_limit _) (fork.ext (iso.refl _) (by tidy)) variables {f g} /-- A morphism `k : W ⟶ X` satisfying `k ≫ f = k ≫ g` factors through the equalizer of `f` and `g` via `equalizer.lift : W ⟶ equalizer f g`. -/ abbreviation equalizer.lift {W : C} (k : W ⟶ X) (h : k ≫ f = k ≫ g) : W ⟶ equalizer f g := limit.lift (parallel_pair f g) (fork.of_ι k h) @[simp, reassoc] lemma equalizer.lift_ι {W : C} (k : W ⟶ X) (h : k ≫ f = k ≫ g) : equalizer.lift k h ≫ equalizer.ι f g = k := limit.lift_π _ _ /-- A morphism `k : W ⟶ X` satisfying `k ≫ f = k ≫ g` induces a morphism `l : W ⟶ equalizer f g` satisfying `l ≫ equalizer.ι f g = k`. -/ def equalizer.lift' {W : C} (k : W ⟶ X) (h : k ≫ f = k ≫ g) : {l : W ⟶ equalizer f g // l ≫ equalizer.ι f g = k} := ⟨equalizer.lift k h, equalizer.lift_ι _ _⟩ /-- Two maps into an equalizer are equal if they are are equal when composed with the equalizer map. -/ @[ext] lemma equalizer.hom_ext {W : C} {k l : W ⟶ equalizer f g} (h : k ≫ equalizer.ι f g = l ≫ equalizer.ι f g) : k = l := fork.is_limit.hom_ext (limit.is_limit _) h lemma equalizer.exists_unique {W : C} (k : W ⟶ X) (h : k ≫ f = k ≫ g) : ∃! (l : W ⟶ equalizer f g), l ≫ equalizer.ι f g = k := fork.is_limit.exists_unique (limit.is_limit _) _ h /-- An equalizer morphism is a monomorphism -/ instance equalizer.ι_mono : mono (equalizer.ι f g) := { right_cancellation := λ Z h k w, equalizer.hom_ext w } end section variables {f g} /-- The equalizer morphism in any limit cone is a monomorphism. -/ lemma mono_of_is_limit_fork {c : fork f g} (i : is_limit c) : mono (fork.ι c) := { right_cancellation := λ Z h k w, fork.is_limit.hom_ext i w } end section variables {f g} /-- The identity determines a cone on the equalizer diagram of `f` and `g` if `f = g`. -/ def id_fork (h : f = g) : fork f g := fork.of_ι (𝟙 X) $ h ▸ rfl /-- The identity on `X` is an equalizer of `(f, g)`, if `f = g`. -/ def is_limit_id_fork (h : f = g) : is_limit (id_fork h) := fork.is_limit.mk _ (λ s, fork.ι s) (λ s, category.comp_id _) (λ s m h, by { convert h, exact (category.comp_id _).symm }) /-- Every equalizer of `(f, g)`, where `f = g`, is an isomorphism. -/ lemma is_iso_limit_cone_parallel_pair_of_eq (h₀ : f = g) {c : fork f g} (h : is_limit c) : is_iso c.ι := is_iso.of_iso $ is_limit.cone_point_unique_up_to_iso h $ is_limit_id_fork h₀ /-- The equalizer of `(f, g)`, where `f = g`, is an isomorphism. -/ lemma equalizer.ι_of_eq [has_equalizer f g] (h : f = g) : is_iso (equalizer.ι f g) := is_iso_limit_cone_parallel_pair_of_eq h $ limit.is_limit _ /-- Every equalizer of `(f, f)` is an isomorphism. -/ lemma is_iso_limit_cone_parallel_pair_of_self {c : fork f f} (h : is_limit c) : is_iso c.ι := is_iso_limit_cone_parallel_pair_of_eq rfl h /-- An equalizer that is an epimorphism is an isomorphism. -/ lemma is_iso_limit_cone_parallel_pair_of_epi {c : fork f g} (h : is_limit c) [epi (c.ι)] : is_iso c.ι := is_iso_limit_cone_parallel_pair_of_eq ((cancel_epi _).1 (fork.condition c)) h /-- Two morphisms are equal if there is a fork whose inclusion is epi. -/ lemma eq_of_epi_fork_ι (t : fork f g) [epi (fork.ι t)] : f = g := (cancel_epi (fork.ι t)).1 $ fork.condition t /-- If the equalizer of two morphisms is an epimorphism, then the two morphisms are equal. -/ lemma eq_of_epi_equalizer [has_equalizer f g] [epi (equalizer.ι f g)] : f = g := (cancel_epi (equalizer.ι f g)).1 $ equalizer.condition _ _ end instance has_equalizer_of_self : has_equalizer f f := has_limit.mk { cone := id_fork rfl, is_limit := is_limit_id_fork rfl } /-- The equalizer inclusion for `(f, f)` is an isomorphism. -/ instance equalizer.ι_of_self : is_iso (equalizer.ι f f) := equalizer.ι_of_eq rfl /-- The equalizer of a morphism with itself is isomorphic to the source. -/ def equalizer.iso_source_of_self : equalizer f f ≅ X := as_iso (equalizer.ι f f) @[simp] lemma equalizer.iso_source_of_self_hom : (equalizer.iso_source_of_self f).hom = equalizer.ι f f := rfl @[simp] lemma equalizer.iso_source_of_self_inv : (equalizer.iso_source_of_self f).inv = equalizer.lift (𝟙 X) (by simp) := by { ext, simp [equalizer.iso_source_of_self], } section /-- `has_coequalizer f g` represents a particular choice of colimiting cocone for the parallel pair of morphisms `f` and `g`. -/ abbreviation has_coequalizer := has_colimit (parallel_pair f g) variables [has_coequalizer f g] /-- If a coequalizer of `f` and `g` exists, we can access an arbitrary choice of such by saying `coequalizer f g`. -/ abbreviation coequalizer : C := colimit (parallel_pair f g) /-- If a coequalizer of `f` and `g` exists, we can access the corresponding projection by saying `coequalizer.π f g`. -/ abbreviation coequalizer.π : Y ⟶ coequalizer f g := colimit.ι (parallel_pair f g) one /-- An arbitrary choice of coequalizer cocone for a parallel pair `f` and `g`. -/ abbreviation coequalizer.cofork : cofork f g := colimit.cocone (parallel_pair f g) @[simp] lemma coequalizer.cofork_π : (coequalizer.cofork f g).π = coequalizer.π f g := rfl @[simp] lemma coequalizer.cofork_ι_app_one : (coequalizer.cofork f g).ι.app one = coequalizer.π f g := rfl @[reassoc] lemma coequalizer.condition : f ≫ coequalizer.π f g = g ≫ coequalizer.π f g := cofork.condition $ colimit.cocone $ parallel_pair f g /-- The cofork built from `coequalizer.π f g` is colimiting. -/ def coequalizer_is_coequalizer : is_colimit (cofork.of_π (coequalizer.π f g) (coequalizer.condition f g)) := is_colimit.of_iso_colimit (colimit.is_colimit _) (cofork.ext (iso.refl _) (by tidy)) variables {f g} /-- Any morphism `k : Y ⟶ W` satisfying `f ≫ k = g ≫ k` factors through the coequalizer of `f` and `g` via `coequalizer.desc : coequalizer f g ⟶ W`. -/ abbreviation coequalizer.desc {W : C} (k : Y ⟶ W) (h : f ≫ k = g ≫ k) : coequalizer f g ⟶ W := colimit.desc (parallel_pair f g) (cofork.of_π k h) @[simp, reassoc] lemma coequalizer.π_desc {W : C} (k : Y ⟶ W) (h : f ≫ k = g ≫ k) : coequalizer.π f g ≫ coequalizer.desc k h = k := colimit.ι_desc _ _ lemma coequalizer.π_colim_map_desc {X' Y' Z : C} (f' g' : X' ⟶ Y') [has_coequalizer f' g'] (p : X ⟶ X') (q : Y ⟶ Y') (wf : f ≫ q = p ≫ f') (wg : g ≫ q = p ≫ g') (h : Y' ⟶ Z) (wh : f' ≫ h = g' ≫ h) : coequalizer.π f g ≫ colim_map (parallel_pair_hom f g f' g' p q wf wg) ≫ coequalizer.desc h wh = q ≫ h := by rw [ι_colim_map_assoc, parallel_pair_hom_app_one, coequalizer.π_desc] /-- Any morphism `k : Y ⟶ W` satisfying `f ≫ k = g ≫ k` induces a morphism `l : coequalizer f g ⟶ W` satisfying `coequalizer.π ≫ g = l`. -/ def coequalizer.desc' {W : C} (k : Y ⟶ W) (h : f ≫ k = g ≫ k) : {l : coequalizer f g ⟶ W // coequalizer.π f g ≫ l = k} := ⟨coequalizer.desc k h, coequalizer.π_desc _ _⟩ /-- Two maps from a coequalizer are equal if they are equal when composed with the coequalizer map -/ @[ext] lemma coequalizer.hom_ext {W : C} {k l : coequalizer f g ⟶ W} (h : coequalizer.π f g ≫ k = coequalizer.π f g ≫ l) : k = l := cofork.is_colimit.hom_ext (colimit.is_colimit _) h lemma coequalizer.exists_unique {W : C} (k : Y ⟶ W) (h : f ≫ k = g ≫ k) : ∃! (d : coequalizer f g ⟶ W), coequalizer.π f g ≫ d = k := cofork.is_colimit.exists_unique (colimit.is_colimit _) _ h /-- A coequalizer morphism is an epimorphism -/ instance coequalizer.π_epi : epi (coequalizer.π f g) := { left_cancellation := λ Z h k w, coequalizer.hom_ext w } end section variables {f g} /-- The coequalizer morphism in any colimit cocone is an epimorphism. -/ lemma epi_of_is_colimit_cofork {c : cofork f g} (i : is_colimit c) : epi c.π := { left_cancellation := λ Z h k w, cofork.is_colimit.hom_ext i w } end section variables {f g} /-- The identity determines a cocone on the coequalizer diagram of `f` and `g`, if `f = g`. -/ def id_cofork (h : f = g) : cofork f g := cofork.of_π (𝟙 Y) $ h ▸ rfl /-- The identity on `Y` is a coequalizer of `(f, g)`, where `f = g`. -/ def is_colimit_id_cofork (h : f = g) : is_colimit (id_cofork h) := cofork.is_colimit.mk _ (λ s, cofork.π s) (λ s, category.id_comp _) (λ s m h, by { convert h, exact (category.id_comp _).symm }) /-- Every coequalizer of `(f, g)`, where `f = g`, is an isomorphism. -/ lemma is_iso_colimit_cocone_parallel_pair_of_eq (h₀ : f = g) {c : cofork f g} (h : is_colimit c) : is_iso c.π := is_iso.of_iso $ is_colimit.cocone_point_unique_up_to_iso (is_colimit_id_cofork h₀) h /-- The coequalizer of `(f, g)`, where `f = g`, is an isomorphism. -/ lemma coequalizer.π_of_eq [has_coequalizer f g] (h : f = g) : is_iso (coequalizer.π f g) := is_iso_colimit_cocone_parallel_pair_of_eq h $ colimit.is_colimit _ /-- Every coequalizer of `(f, f)` is an isomorphism. -/ lemma is_iso_colimit_cocone_parallel_pair_of_self {c : cofork f f} (h : is_colimit c) : is_iso c.π := is_iso_colimit_cocone_parallel_pair_of_eq rfl h /-- A coequalizer that is a monomorphism is an isomorphism. -/ lemma is_iso_limit_cocone_parallel_pair_of_epi {c : cofork f g} (h : is_colimit c) [mono c.π] : is_iso c.π := is_iso_colimit_cocone_parallel_pair_of_eq ((cancel_mono _).1 (cofork.condition c)) h /-- Two morphisms are equal if there is a cofork whose projection is mono. -/ lemma eq_of_mono_cofork_π (t : cofork f g) [mono (cofork.π t)] : f = g := (cancel_mono (cofork.π t)).1 $ cofork.condition t /-- If the coequalizer of two morphisms is a monomorphism, then the two morphisms are equal. -/ lemma eq_of_mono_coequalizer [has_coequalizer f g] [mono (coequalizer.π f g)] : f = g := (cancel_mono (coequalizer.π f g)).1 $ coequalizer.condition _ _ end instance has_coequalizer_of_self : has_coequalizer f f := has_colimit.mk { cocone := id_cofork rfl, is_colimit := is_colimit_id_cofork rfl } /-- The coequalizer projection for `(f, f)` is an isomorphism. -/ instance coequalizer.π_of_self : is_iso (coequalizer.π f f) := coequalizer.π_of_eq rfl /-- The coequalizer of a morphism with itself is isomorphic to the target. -/ def coequalizer.iso_target_of_self : coequalizer f f ≅ Y := (as_iso (coequalizer.π f f)).symm @[simp] lemma coequalizer.iso_target_of_self_hom : (coequalizer.iso_target_of_self f).hom = coequalizer.desc (𝟙 Y) (by simp) := by { ext, simp [coequalizer.iso_target_of_self], } @[simp] lemma coequalizer.iso_target_of_self_inv : (coequalizer.iso_target_of_self f).inv = coequalizer.π f f := rfl section comparison variables {D : Type u₂} [category.{v₂} D] (G : C ⥤ D) /-- The comparison morphism for the equalizer of `f,g`. This is an isomorphism iff `G` preserves the equalizer of `f,g`; see `category_theory/limits/preserves/shapes/equalizers.lean` -/ def equalizer_comparison [has_equalizer f g] [has_equalizer (G.map f) (G.map g)] : G.obj (equalizer f g) ⟶ equalizer (G.map f) (G.map g) := equalizer.lift (G.map (equalizer.ι _ _)) (by simp only [←G.map_comp, equalizer.condition]) @[simp, reassoc] lemma equalizer_comparison_comp_π [has_equalizer f g] [has_equalizer (G.map f) (G.map g)] : equalizer_comparison f g G ≫ equalizer.ι (G.map f) (G.map g) = G.map (equalizer.ι f g) := equalizer.lift_ι _ _ @[simp, reassoc] lemma map_lift_equalizer_comparison [has_equalizer f g] [has_equalizer (G.map f) (G.map g)] {Z : C} {h : Z ⟶ X} (w : h ≫ f = h ≫ g) : G.map (equalizer.lift h w) ≫ equalizer_comparison f g G = equalizer.lift (G.map h) (by simp only [←G.map_comp, w]) := by { ext, simp [← G.map_comp] } /-- The comparison morphism for the coequalizer of `f,g`. -/ def coequalizer_comparison [has_coequalizer f g] [has_coequalizer (G.map f) (G.map g)] : coequalizer (G.map f) (G.map g) ⟶ G.obj (coequalizer f g) := coequalizer.desc (G.map (coequalizer.π _ _)) (by simp only [←G.map_comp, coequalizer.condition]) @[simp, reassoc] lemma ι_comp_coequalizer_comparison [has_coequalizer f g] [has_coequalizer (G.map f) (G.map g)] : coequalizer.π _ _ ≫ coequalizer_comparison f g G = G.map (coequalizer.π _ _) := coequalizer.π_desc _ _ @[simp, reassoc] lemma coequalizer_comparison_map_desc [has_coequalizer f g] [has_coequalizer (G.map f) (G.map g)] {Z : C} {h : Y ⟶ Z} (w : f ≫ h = g ≫ h) : coequalizer_comparison f g G ≫ G.map (coequalizer.desc h w) = coequalizer.desc (G.map h) (by simp only [←G.map_comp, w]) := by { ext, simp [← G.map_comp] } end comparison variables (C) /-- `has_equalizers` represents a choice of equalizer for every pair of morphisms -/ abbreviation has_equalizers := has_limits_of_shape walking_parallel_pair C /-- `has_coequalizers` represents a choice of coequalizer for every pair of morphisms -/ abbreviation has_coequalizers := has_colimits_of_shape walking_parallel_pair C /-- If `C` has all limits of diagrams `parallel_pair f g`, then it has all equalizers -/ lemma has_equalizers_of_has_limit_parallel_pair [Π {X Y : C} {f g : X ⟶ Y}, has_limit (parallel_pair f g)] : has_equalizers C := { has_limit := λ F, has_limit_of_iso (diagram_iso_parallel_pair F).symm } /-- If `C` has all colimits of diagrams `parallel_pair f g`, then it has all coequalizers -/ lemma has_coequalizers_of_has_colimit_parallel_pair [Π {X Y : C} {f g : X ⟶ Y}, has_colimit (parallel_pair f g)] : has_coequalizers C := { has_colimit := λ F, has_colimit_of_iso (diagram_iso_parallel_pair F) } section -- In this section we show that a split mono `f` equalizes `(retraction f ≫ f)` and `(𝟙 Y)`. variables {C} [is_split_mono f] /-- A split mono `f` equalizes `(retraction f ≫ f)` and `(𝟙 Y)`. Here we build the cone, and show in `is_split_mono_equalizes` that it is a limit cone. -/ @[simps {rhs_md := semireducible}] def cone_of_is_split_mono : fork (𝟙 Y) (retraction f ≫ f) := fork.of_ι f (by simp) @[simp] lemma cone_of_is_split_mono_ι : (cone_of_is_split_mono f).ι = f := rfl /-- A split mono `f` equalizes `(retraction f ≫ f)` and `(𝟙 Y)`. -/ def is_split_mono_equalizes {X Y : C} (f : X ⟶ Y) [is_split_mono f] : is_limit (cone_of_is_split_mono f) := fork.is_limit.mk' _ $ λ s, ⟨s.ι ≫ retraction f, by { dsimp, rw [category.assoc, ←s.condition], apply category.comp_id }, λ m hm, by simp [←hm]⟩ end /-- We show that the converse to `is_split_mono_equalizes` is true: Whenever `f` equalizes `(r ≫ f)` and `(𝟙 Y)`, then `r` is a retraction of `f`. -/ def split_mono_of_equalizer {X Y : C} {f : X ⟶ Y} {r : Y ⟶ X} (hr : f ≫ r ≫ f = f) (h : is_limit (fork.of_ι f (hr.trans (category.comp_id _).symm : f ≫ r ≫ f = f ≫ 𝟙 Y))) : split_mono f := { retraction := r, id' := fork.is_limit.hom_ext h ((category.assoc _ _ _).trans $ hr.trans (category.id_comp _).symm) } variables {C f g} /-- The fork obtained by postcomposing an equalizer fork with a monomorphism is an equalizer. -/ def is_equalizer_comp_mono {c : fork f g} (i : is_limit c) {Z : C} (h : Y ⟶ Z) [hm : mono h] : is_limit (fork.of_ι c.ι (by simp [reassoc_of c.condition]) : fork (f ≫ h) (g ≫ h)) := fork.is_limit.mk' _ $ λ s, let s' : fork f g := fork.of_ι s.ι (by apply hm.right_cancellation; simp [s.condition]) in let l := fork.is_limit.lift' i s'.ι s'.condition in ⟨l.1, l.2, λ m hm, by apply fork.is_limit.hom_ext i; rw fork.ι_of_ι at hm; rw hm; exact l.2.symm⟩ variables (C f g) @[instance] lemma has_equalizer_comp_mono [has_equalizer f g] {Z : C} (h : Y ⟶ Z) [mono h] : has_equalizer (f ≫ h) (g ≫ h) := ⟨⟨{ cone := _, is_limit := is_equalizer_comp_mono (limit.is_limit _) h }⟩⟩ /-- An equalizer of an idempotent morphism and the identity is split mono. -/ @[simps] def split_mono_of_idempotent_of_is_limit_fork {X : C} {f : X ⟶ X} (hf : f ≫ f = f) {c : fork (𝟙 X) f} (i : is_limit c) : split_mono c.ι := { retraction := i.lift (fork.of_ι f (by simp [hf])), id' := begin letI := mono_of_is_limit_fork i, rw [←cancel_mono_id c.ι, category.assoc, fork.is_limit.lift_ι, fork.ι_of_ι, ←c.condition], exact category.comp_id c.ι end } /-- The equalizer of an idempotent morphism and the identity is split mono. -/ def split_mono_of_idempotent_equalizer {X : C} {f : X ⟶ X} (hf : f ≫ f = f) [has_equalizer (𝟙 X) f] : split_mono (equalizer.ι (𝟙 X) f) := split_mono_of_idempotent_of_is_limit_fork _ hf (limit.is_limit _) section -- In this section we show that a split epi `f` coequalizes `(f ≫ section_ f)` and `(𝟙 X)`. variables {C} [is_split_epi f] /-- A split epi `f` coequalizes `(f ≫ section_ f)` and `(𝟙 X)`. Here we build the cocone, and show in `is_split_epi_coequalizes` that it is a colimit cocone. -/ @[simps {rhs_md := semireducible}] def cocone_of_is_split_epi : cofork (𝟙 X) (f ≫ section_ f) := cofork.of_π f (by simp) @[simp] lemma cocone_of_is_split_epi_π : (cocone_of_is_split_epi f).π = f := rfl /-- A split epi `f` coequalizes `(f ≫ section_ f)` and `(𝟙 X)`. -/ def is_split_epi_coequalizes {X Y : C} (f : X ⟶ Y) [is_split_epi f] : is_colimit (cocone_of_is_split_epi f) := cofork.is_colimit.mk' _ $ λ s, ⟨section_ f ≫ s.π, by { dsimp, rw [← category.assoc, ← s.condition, category.id_comp] }, λ m hm, by simp [← hm]⟩ end /-- We show that the converse to `is_split_epi_equalizes` is true: Whenever `f` coequalizes `(f ≫ s)` and `(𝟙 X)`, then `s` is a section of `f`. -/ def split_epi_of_coequalizer {X Y : C} {f : X ⟶ Y} {s : Y ⟶ X} (hs : f ≫ s ≫ f = f) (h : is_colimit (cofork.of_π f ((category.assoc _ _ _).trans $ hs.trans (category.id_comp f).symm : (f ≫ s) ≫ f = 𝟙 X ≫ f))) : split_epi f := { section_ := s, id' := cofork.is_colimit.hom_ext h (hs.trans (category.comp_id _).symm) } variables {C f g} /-- The cofork obtained by precomposing a coequalizer cofork with an epimorphism is a coequalizer. -/ def is_coequalizer_epi_comp {c : cofork f g} (i : is_colimit c) {W : C} (h : W ⟶ X) [hm : epi h] : is_colimit (cofork.of_π c.π (by simp) : cofork (h ≫ f) (h ≫ g)) := cofork.is_colimit.mk' _ $ λ s, let s' : cofork f g := cofork.of_π s.π (by apply hm.left_cancellation; simp_rw [←category.assoc, s.condition]) in let l := cofork.is_colimit.desc' i s'.π s'.condition in ⟨l.1, l.2, λ m hm,by apply cofork.is_colimit.hom_ext i; rw cofork.π_of_π at hm; rw hm; exact l.2.symm⟩ lemma has_coequalizer_epi_comp [has_coequalizer f g] {W : C} (h : W ⟶ X) [hm : epi h] : has_coequalizer (h ≫ f) (h ≫ g) := ⟨⟨{ cocone := _, is_colimit := is_coequalizer_epi_comp (colimit.is_colimit _) h }⟩⟩ variables (C f g) /-- A coequalizer of an idempotent morphism and the identity is split epi. -/ @[simps] def split_epi_of_idempotent_of_is_colimit_cofork {X : C} {f : X ⟶ X} (hf : f ≫ f = f) {c : cofork (𝟙 X) f} (i : is_colimit c) : split_epi c.π := { section_ := i.desc (cofork.of_π f (by simp [hf])), id' := begin letI := epi_of_is_colimit_cofork i, rw [← cancel_epi_id c.π, ← category.assoc, cofork.is_colimit.π_desc, cofork.π_of_π, ← c.condition], exact category.id_comp _, end } /-- The coequalizer of an idempotent morphism and the identity is split epi. -/ def split_epi_of_idempotent_coequalizer {X : C} {f : X ⟶ X} (hf : f ≫ f = f) [has_coequalizer (𝟙 X) f] : split_epi (coequalizer.π (𝟙 X) f) := split_epi_of_idempotent_of_is_colimit_cofork _ hf (colimit.is_colimit _) end category_theory.limits
a4384428eacd2495e621372518e987c120ea07f9
46125763b4dbf50619e8846a1371029346f4c3db
/src/algebra/module.lean
076027745fc900e317a90ef62c4dc0c1c64f0454
[ "Apache-2.0" ]
permissive
thjread/mathlib
a9d97612cedc2c3101060737233df15abcdb9eb1
7cffe2520a5518bba19227a107078d83fa725ddc
refs/heads/master
1,615,637,696,376
1,583,953,063,000
1,583,953,063,000
246,680,271
0
0
Apache-2.0
1,583,960,875,000
1,583,960,875,000
null
UTF-8
Lean
false
false
18,407
lean
/- Copyright (c) 2015 Nathaniel Thomas. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nathaniel Thomas, Jeremy Avigad, Johannes Hölzl, Mario Carneiro Modules over a ring. ## Implementation notes Throughout the `linear_map` section implicit `{}` brackets are often used instead of type class `[]` brackets. This is done when the instances can be inferred because they are implicit arguments to the type `linear_map`. When they can be inferred from the type it is faster to use this method than to use type class inference -/ import algebra.ring algebra.big_operators group_theory.subgroup group_theory.group_action open function universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} -- /-- Typeclass for types with a scalar multiplication operation, denoted `•` (`\bu`) -/ -- class has_scalar (α : Type u) (γ : Type v) := (smul : α → γ → γ) -- infixr ` • `:73 := has_scalar.smul section prio set_option default_priority 100 -- see Note [default priority] /-- A semimodule is a generalization of vector spaces to a scalar semiring. It consists of a scalar semiring `α` and an additive monoid of "vectors" `β`, connected by a "scalar multiplication" operation `r • x : β` (where `r : α` and `x : β`) with some natural associativity and distributivity axioms similar to those on a ring. -/ class semimodule (α : Type u) (β : Type v) [semiring α] [add_comm_monoid β] extends distrib_mul_action α β := (add_smul : ∀(r s : α) (x : β), (r + s) • x = r • x + s • x) (zero_smul : ∀x : β, (0 : α) • x = 0) end prio section semimodule variables [R:semiring α] [add_comm_monoid β] [semimodule α β] (r s : α) (x y : β) include R theorem add_smul : (r + s) • x = r • x + s • x := semimodule.add_smul r s x variables (α) @[simp] theorem zero_smul : (0 : α) • x = 0 := semimodule.zero_smul α x variable {α} lemma semimodule.eq_zero_of_zero_eq_one (zero_eq_one : (0 : α) = 1) : x = 0 := by rw [←one_smul α x, ←zero_eq_one, zero_smul] instance smul.is_add_monoid_hom (x : β) : is_add_monoid_hom (λ r:α, r • x) := { map_zero := zero_smul _ x, map_add := λ r₁ r₂, add_smul r₁ r₂ x } lemma list.sum_smul {l : list α} {x : β} : l.sum • x = (l.map (λ r, r • x)).sum := show (λ r, r • x) l.sum = (l.map (λ r, r • x)).sum, from (list.sum_hom _ _).symm lemma multiset.sum_smul {l : multiset α} {x : β} : l.sum • x = (l.map (λ r, r • x)).sum := show (λ r, r • x) l.sum = (l.map (λ r, r • x)).sum, from (multiset.sum_hom _ _).symm lemma finset.sum_smul {f : γ → α} {s : finset γ} {x : β} : s.sum f • x = s.sum (λ r, (f r) • x) := show (λ r, r • x) (s.sum f) = s.sum (λ r, (f r) • x), from (finset.sum_hom _ _).symm end semimodule section prio set_option default_priority 100 -- see Note [default priority] /-- A module is a generalization of vector spaces to a scalar ring. It consists of a scalar ring `α` and an additive group of "vectors" `β`, connected by a "scalar multiplication" operation `r • x : β` (where `r : α` and `x : β`) with some natural associativity and distributivity axioms similar to those on a ring. -/ class module (α : Type u) (β : Type v) [ring α] [add_comm_group β] extends semimodule α β end prio structure module.core (α β) [ring α] [add_comm_group β] extends has_scalar α β := (smul_add : ∀(r : α) (x y : β), r • (x + y) = r • x + r • y) (add_smul : ∀(r s : α) (x : β), (r + s) • x = r • x + s • x) (mul_smul : ∀(r s : α) (x : β), (r * s) • x = r • s • x) (one_smul : ∀x : β, (1 : α) • x = x) def module.of_core {α β} [ring α] [add_comm_group β] (M : module.core α β) : module α β := by letI := M.to_has_scalar; exact { zero_smul := λ x, have (0 : α) • x + (0 : α) • x = (0 : α) • x + 0, by rw ← M.add_smul; simp, add_left_cancel this, smul_zero := λ r, have r • (0:β) + r • 0 = r • 0 + 0, by rw ← M.smul_add; simp, add_left_cancel this, ..M } section module variables [ring α] [add_comm_group β] [module α β] (r s : α) (x y : β) @[simp] theorem neg_smul : -r • x = - (r • x) := eq_neg_of_add_eq_zero (by rw [← add_smul, add_left_neg, zero_smul]) variables (α) theorem neg_one_smul (x : β) : (-1 : α) • x = -x := by simp variables {α} @[simp] theorem smul_neg : r • (-x) = -(r • x) := by rw [← neg_one_smul α, ← mul_smul, mul_neg_one, neg_smul] theorem smul_sub (r : α) (x y : β) : r • (x - y) = r • x - r • y := by simp [smul_add, sub_eq_add_neg]; rw smul_neg theorem sub_smul (r s : α) (y : β) : (r - s) • y = r • y - s • y := by simp [add_smul, sub_eq_add_neg] end module instance semiring.to_semimodule [r : semiring α] : semimodule α α := { smul := (*), smul_add := mul_add, add_smul := add_mul, mul_smul := mul_assoc, one_smul := one_mul, zero_smul := zero_mul, smul_zero := mul_zero, ..r } @[simp] lemma smul_eq_mul [semiring α] {a a' : α} : a • a' = a * a' := rfl instance ring.to_module [r : ring α] : module α α := { ..semiring.to_semimodule } def is_ring_hom.to_module [ring α] [ring β] (f : α → β) [h : is_ring_hom f] : module α β := module.of_core { smul := λ r x, f r * x, smul_add := λ r x y, by unfold has_scalar.smul; rw [mul_add], add_smul := λ r s x, by unfold has_scalar.smul; rw [h.map_add, add_mul], mul_smul := λ r s x, by unfold has_scalar.smul; rw [h.map_mul, mul_assoc], one_smul := λ x, show f 1 * x = _, by rw [h.map_one, one_mul] } class is_linear_map (α : Type u) {β : Type v} {γ : Type w} [ring α] [add_comm_group β] [add_comm_group γ] [module α β] [module α γ] (f : β → γ) : Prop := (add : ∀x y, f (x + y) = f x + f y) (smul : ∀(c : α) x, f (c • x) = c • f x) structure linear_map (α : Type u) (β : Type v) (γ : Type w) [ring α] [add_comm_group β] [add_comm_group γ] [module α β] [module α γ] := (to_fun : β → γ) (add : ∀x y, to_fun (x + y) = to_fun x + to_fun y) (smul : ∀(c : α) x, to_fun (c • x) = c • to_fun x) infixr ` →ₗ `:25 := linear_map _ notation β ` →ₗ[`:25 α:25 `] `:0 γ:0 := linear_map α β γ namespace linear_map variables {rα : ring α} {gβ : add_comm_group β} {gγ : add_comm_group γ} {gδ : add_comm_group δ} variables {mβ : module α β} {mγ : module α γ} {mδ : module α δ} variables (f g : β →ₗ[α] γ) include α mβ mγ instance : has_coe_to_fun (β →ₗ[α] γ) := ⟨_, to_fun⟩ @[simp] lemma coe_mk (f : β → γ) (h₁ h₂) : ((linear_map.mk f h₁ h₂ : β →ₗ[α] γ) : β → γ) = f := rfl @[simp] lemma to_fun_eq_coe (f : β →ₗ[α] γ) : f.to_fun = ⇑f := rfl theorem is_linear : is_linear_map α f := {..f} @[ext] theorem ext {f g : β →ₗ[α] γ} (H : ∀ x, f x = g x) : f = g := by cases f; cases g; congr'; exact funext H theorem ext_iff {f g : β →ₗ[α] γ} : f = g ↔ ∀ x, f x = g x := ⟨by rintro rfl; simp, ext⟩ @[simp] lemma map_add (x y : β) : f (x + y) = f x + f y := f.add x y @[simp] lemma map_smul (c : α) (x : β) : f (c • x) = c • f x := f.smul c x @[simp] lemma map_zero : f 0 = 0 := by rw [← zero_smul α, map_smul f 0 0, zero_smul] instance : is_add_group_hom f := { map_add := map_add f } @[simp] lemma map_neg (x : β) : f (- x) = - f x := by rw [← neg_one_smul α, map_smul, neg_one_smul] @[simp] lemma map_sub (x y : β) : f (x - y) = f x - f y := by simp [map_neg, map_add, sub_eq_add_neg] @[simp] lemma map_sum {ι} {t : finset ι} {g : ι → β} : f (t.sum g) = t.sum (λi, f (g i)) := (t.sum_hom f).symm include mδ def comp (f : γ →ₗ[α] δ) (g : β →ₗ[α] γ) : β →ₗ[α] δ := ⟨f ∘ g, by simp, by simp⟩ @[simp] lemma comp_apply (f : γ →ₗ[α] δ) (g : β →ₗ[α] γ) (x : β) : f.comp g x = f (g x) := rfl omit mγ mδ variables [rα] [gβ] [mβ] def id : β →ₗ[α] β := ⟨id, by simp, by simp⟩ @[simp] lemma id_apply (x : β) : @id α β _ _ _ x = x := rfl end linear_map namespace is_linear_map variables [ring α] [add_comm_group β] [add_comm_group γ] variables [module α β] [module α γ] include α def mk' (f : β → γ) (H : is_linear_map α f) : β →ₗ γ := {to_fun := f, ..H} @[simp] theorem mk'_apply {f : β → γ} (H : is_linear_map α f) (x : β) : mk' f H x = f x := rfl lemma is_linear_map_neg : is_linear_map α (λ (z : β), -z) := is_linear_map.mk neg_add (λ x y, (smul_neg x y).symm) lemma is_linear_map_smul {α R : Type*} [add_comm_group α] [comm_ring R] [module R α] (c : R) : is_linear_map R (λ (z : α), c • z) := begin refine is_linear_map.mk (smul_add c) _, intros _ _, simp [smul_smul], ac_refl end --TODO: move lemma is_linear_map_smul' {α R : Type*} [add_comm_group α] [ring R] [module R α] (a : α) : is_linear_map R (λ (c : R), c • a) := begin refine is_linear_map.mk (λ x y, add_smul x y a) _, intros _ _, simp [smul_smul] end variables {f : β → γ} (lin : is_linear_map α f) include β γ lin lemma map_zero : f (0 : β) = (0 : γ) := by rw [← zero_smul α (0 : β), lin.smul, zero_smul] lemma map_add (x y : β) : f (x + y) = f x + f y := by rw [lin.add] lemma map_neg (x : β) : f (- x) = - f x := by rw [← neg_one_smul α, lin.smul, neg_one_smul] lemma map_sub (x y : β) : f (x - y) = f x - f y := by simp [lin.map_neg, lin.map_add, sub_eq_add_neg] end is_linear_map abbreviation module.End (R : Type u) (M : Type v) [comm_ring R] [add_comm_group M] [module R M] := M →ₗ[R] M /-- A submodule of a module is one which is closed under vector operations. This is a sufficient condition for the subset of vectors in the submodule to themselves form a module. -/ structure submodule (α : Type u) (β : Type v) [ring α] [add_comm_group β] [module α β] : Type v := (carrier : set β) (zero : (0:β) ∈ carrier) (add : ∀ {x y}, x ∈ carrier → y ∈ carrier → x + y ∈ carrier) (smul : ∀ (c:α) {x}, x ∈ carrier → c • x ∈ carrier) namespace submodule variables [ring α] [add_comm_group β] [add_comm_group γ] variables [module α β] [module α γ] variables (p p' : submodule α β) variables {r : α} {x y : β} instance : has_coe (submodule α β) (set β) := ⟨submodule.carrier⟩ instance : has_mem β (submodule α β) := ⟨λ x p, x ∈ (p : set β)⟩ @[simp] theorem mem_coe : x ∈ (p : set β) ↔ x ∈ p := iff.rfl theorem ext' {s t : submodule α β} (h : (s : set β) = t) : s = t := by cases s; cases t; congr' protected theorem ext'_iff {s t : submodule α β} : (s : set β) = t ↔ s = t := ⟨ext', λ h, h ▸ rfl⟩ @[ext] theorem ext {s t : submodule α β} (h : ∀ x, x ∈ s ↔ x ∈ t) : s = t := ext' $ set.ext h @[simp] lemma zero_mem : (0 : β) ∈ p := p.zero lemma add_mem (h₁ : x ∈ p) (h₂ : y ∈ p) : x + y ∈ p := p.add h₁ h₂ lemma smul_mem (r : α) (h : x ∈ p) : r • x ∈ p := p.smul r h lemma neg_mem (hx : x ∈ p) : -x ∈ p := by rw ← neg_one_smul α; exact p.smul_mem _ hx lemma sub_mem (hx : x ∈ p) (hy : y ∈ p) : x - y ∈ p := p.add_mem hx (p.neg_mem hy) lemma neg_mem_iff : -x ∈ p ↔ x ∈ p := ⟨λ h, by simpa using neg_mem p h, neg_mem p⟩ lemma add_mem_iff_left (h₁ : y ∈ p) : x + y ∈ p ↔ x ∈ p := ⟨λ h₂, by simpa using sub_mem _ h₂ h₁, λ h₂, add_mem _ h₂ h₁⟩ lemma add_mem_iff_right (h₁ : x ∈ p) : x + y ∈ p ↔ y ∈ p := ⟨λ h₂, by simpa using sub_mem _ h₂ h₁, add_mem _ h₁⟩ lemma sum_mem {ι : Type w} [decidable_eq ι] {t : finset ι} {f : ι → β} : (∀c∈t, f c ∈ p) → t.sum f ∈ p := finset.induction_on t (by simp [p.zero_mem]) (by simp [p.add_mem] {contextual := tt}) lemma smul_mem_iff' (u : units α) : (u:α) • x ∈ p ↔ x ∈ p := ⟨λ h, by simpa only [smul_smul, u.inv_mul, one_smul] using p.smul_mem ↑u⁻¹ h, p.smul_mem u⟩ instance : has_add p := ⟨λx y, ⟨x.1 + y.1, add_mem _ x.2 y.2⟩⟩ instance : has_zero p := ⟨⟨0, zero_mem _⟩⟩ instance : inhabited p := ⟨0⟩ instance : has_neg p := ⟨λx, ⟨-x.1, neg_mem _ x.2⟩⟩ instance : has_scalar α p := ⟨λ c x, ⟨c • x.1, smul_mem _ c x.2⟩⟩ @[simp, move_cast] lemma coe_add (x y : p) : (↑(x + y) : β) = ↑x + ↑y := rfl @[simp, elim_cast] lemma coe_zero : ((0 : p) : β) = 0 := rfl @[simp, move_cast] lemma coe_neg (x : p) : ((-x : p) : β) = -x := rfl @[simp, move_cast] lemma coe_smul (r : α) (x : p) : ((r • x : p) : β) = r • ↑x := rfl instance : add_comm_group p := by refine {add := (+), zero := 0, neg := has_neg.neg, ..}; { intros, apply set_coe.ext, simp [add_comm, add_left_comm] } instance submodule_is_add_subgroup : is_add_subgroup (p : set β) := { zero_mem := p.zero, add_mem := p.add, neg_mem := λ _, p.neg_mem } @[simp, move_cast] lemma coe_sub (x y : p) : (↑(x - y) : β) = ↑x - ↑y := by simp [sub_eq_add_neg] instance : module α p := by refine {smul := (•), ..}; { intros, apply set_coe.ext, simp [smul_add, add_smul, mul_smul] } protected def subtype : p →ₗ[α] β := by refine {to_fun := coe, ..}; simp [coe_smul] @[simp] theorem subtype_apply (x : p) : p.subtype x = x := rfl lemma subtype_eq_val (p : submodule α β) : ((submodule.subtype p) : p → β) = subtype.val := rfl end submodule @[reducible] def ideal (α : Type u) [comm_ring α] := submodule α α namespace ideal variables [comm_ring α] (I : ideal α) {a b : α} protected lemma zero_mem : (0 : α) ∈ I := I.zero_mem protected lemma add_mem : a ∈ I → b ∈ I → a + b ∈ I := I.add_mem lemma neg_mem_iff : -a ∈ I ↔ a ∈ I := I.neg_mem_iff lemma add_mem_iff_left : b ∈ I → (a + b ∈ I ↔ a ∈ I) := I.add_mem_iff_left lemma add_mem_iff_right : a ∈ I → (a + b ∈ I ↔ b ∈ I) := I.add_mem_iff_right protected lemma sub_mem : a ∈ I → b ∈ I → a - b ∈ I := I.sub_mem lemma mul_mem_left : b ∈ I → a * b ∈ I := I.smul_mem _ lemma mul_mem_right (h : a ∈ I) : a * b ∈ I := mul_comm b a ▸ I.mul_mem_left h end ideal library_note "vector space definition" "Vector spaces are defined as an `abbreviation` for modules, if the base ring is a field. (A previous definition made `vector_space` a structure defined to be `module`.) This has as advantage that vector spaces are completely transparant for type class inference, which means that all instances for modules are immediately picked up for vector spaces as well. A cosmetic disadvantage is that one can not extend vector spaces an sich, in definitions such as `normed_space`. The solution is to extend `module` instead." /-- A vector space is the same as a module, except the scalar ring is actually a field. (This adds commutativity of the multiplication and existence of inverses.) This is the traditional generalization of spaces like `ℝ^n`, which have a natural addition operation and a way to multiply them by real numbers, but no multiplication operation between vectors. -/ abbreviation vector_space (α : Type u) (β : Type v) [field α] [add_comm_group β] := module α β instance field.to_vector_space {α : Type*} [field α] : vector_space α α := { .. ring.to_module } /-- Subspace of a vector space. Defined to equal `submodule`. -/ @[reducible] def subspace (α : Type u) (β : Type v) [field α] [add_comm_group β] [vector_space α β] : Type v := submodule α β instance subspace.vector_space {α β} {f : field α} [add_comm_group β] [vector_space α β] (p : subspace α β) : vector_space α p := {..submodule.module p} namespace submodule variables {R:field α} [add_comm_group β] [add_comm_group γ] variables [vector_space α β] [vector_space α γ] variables (p p' : submodule α β) variables {r : α} {x y : β} include R set_option class.instance_max_depth 36 theorem smul_mem_iff (r0 : r ≠ 0) : r • x ∈ p ↔ x ∈ p := p.smul_mem_iff' (units.mk0 r r0) end submodule namespace add_comm_monoid open add_monoid variables {M : Type*} [add_comm_monoid M] instance : semimodule ℕ M := { smul := smul, smul_add := λ _ _ _, smul_add _ _ _, add_smul := λ _ _ _, add_smul _ _ _, mul_smul := λ _ _ _, mul_smul _ _ _, one_smul := one_smul, zero_smul := zero_smul, smul_zero := smul_zero } end add_comm_monoid namespace add_comm_group variables {M : Type*} [add_comm_group M] instance : module ℤ M := { smul := gsmul, smul_add := λ _ _ _, gsmul_add _ _ _, add_smul := λ _ _ _, add_gsmul _ _ _, mul_smul := λ _ _ _, gsmul_mul _ _ _, one_smul := one_gsmul, zero_smul := zero_gsmul, smul_zero := gsmul_zero } end add_comm_group lemma gsmul_eq_smul {M : Type*} [add_comm_group M] (n : ℤ) (x : M) : gsmul n x = n • x := rfl def is_add_group_hom.to_linear_map [add_comm_group α] [add_comm_group β] (f : α → β) [is_add_group_hom f] : α →ₗ[ℤ] β := { to_fun := f, add := is_add_hom.map_add f, smul := λ i x, int.induction_on i (by rw [zero_smul, zero_smul, is_add_group_hom.map_zero f]) (λ i ih, by rw [add_smul, add_smul, is_add_hom.map_add f, ih, one_smul, one_smul]) (λ i ih, by rw [sub_smul, sub_smul, is_add_group_hom.map_sub f, ih, one_smul, one_smul]) } lemma module.smul_eq_smul {R : Type*} [ring R] {β : Type*} [add_comm_group β] [module R β] (n : ℕ) (b : β) : n • b = (n : R) • b := begin induction n with n ih, { rw [nat.cast_zero, zero_smul, zero_smul] }, { change (n + 1) • b = (n + 1 : R) • b, rw [add_smul, add_smul, one_smul, ih, one_smul] } end lemma nat.smul_def {M : Type*} [add_comm_monoid M] (n : ℕ) (x : M) : n • x = add_monoid.smul n x := rfl namespace finset lemma sum_const' {α : Type*} (R : Type*) [ring R] {β : Type*} [add_comm_group β] [module R β] {s : finset α} (b : β) : finset.sum s (λ (a : α), b) = (finset.card s : R) • b := by rw [finset.sum_const, ← module.smul_eq_smul]; refl variables {M : Type*} [decidable_linear_ordered_cancel_comm_monoid M] {s : finset α} (f : α → M) theorem exists_card_smul_le_sum (hs : s.nonempty) : ∃ i ∈ s, s.card • f i ≤ s.sum f := exists_le_of_sum_le hs $ by rw [sum_const, ← nat.smul_def, smul_sum] theorem exists_card_smul_ge_sum (hs : s.nonempty) : ∃ i ∈ s, s.sum f ≤ s.card • f i := exists_le_of_sum_le hs $ by rw [sum_const, ← nat.smul_def, smul_sum] end finset
ec6d01b78e3a389d633800a6de51c8fa25422991
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/07_Induction_and_Recursion.org.21.lean
d1aaf5862f7da22206f5189a44ea93f4ab805cdc
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
471
lean
/- page 108 -/ import standard import data.list open nat bool list -- BEGIN definition is_not_zero (a : nat) : bool := match a with | zero := ff | succ _ := tt end -- We can use recursive equations and match variable {A : Type} variable p : A → bool definition filter : list A → list A | filter nil := nil | filter (a :: l) := match p a with | tt := a :: filter l | ff := filter l end example : filter is_not_zero [1, 0, 0, 3, 0] = [1, 3] := rfl -- END
45d4f5d7fcd239a4e092c581eacb8606b89f420b
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/group_theory/order_of_element.lean
2b148145624fc4c9526a45d155a9e3c30f5089c5
[ "Apache-2.0" ]
permissive
jumpy4/mathlib
d3829e75173012833e9f15ac16e481e17596de0f
af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13
refs/heads/master
1,693,508,842,818
1,636,203,271,000
1,636,203,271,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
28,707
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Julian Kuelshammer -/ import algebra.pointwise import group_theory.coset import dynamics.periodic_pts import algebra.iterate_hom /-! # Order of an element This file defines the order of an element of a finite group. For a finite group `G` the order of `x ∈ G` is the minimal `n ≥ 1` such that `x ^ n = 1`. ## Main definitions * `is_of_fin_order` is a predicate on an element `x` of a monoid `G` saying that `x` is of finite order. * `is_of_fin_add_order` is the additive analogue of `is_of_find_order`. * `order_of x` defines the order of an element `x` of a monoid `G`, by convention its value is `0` if `x` has infinite order. * `add_order_of` is the additive analogue of `order_of`. ## Tags order of an element -/ open function nat open_locale pointwise universes u v variables {G : Type u} {A : Type v} variables {x y : G} {a b : A} {n m : ℕ} section monoid_add_monoid variables [monoid G] [add_monoid A] section is_of_fin_order lemma is_periodic_pt_add_iff_nsmul_eq_zero (a : A) : is_periodic_pt ((+) a) n 0 ↔ n • a = 0 := by rw [is_periodic_pt, is_fixed_pt, add_left_iterate, add_zero] @[to_additive is_periodic_pt_add_iff_nsmul_eq_zero] lemma is_periodic_pt_mul_iff_pow_eq_one (x : G) : is_periodic_pt ((*) x) n 1 ↔ x ^ n = 1 := by rw [is_periodic_pt, is_fixed_pt, mul_left_iterate, mul_one] /-- `is_of_fin_add_order` is a predicate on an element `a` of an additive monoid to be of finite order, i.e. there exists `n ≥ 1` such that `n • a = 0`.-/ def is_of_fin_add_order (a : A) : Prop := (0 : A) ∈ periodic_pts ((+) a) /-- `is_of_fin_order` is a predicate on an element `x` of a monoid to be of finite order, i.e. there exists `n ≥ 1` such that `x ^ n = 1`.-/ @[to_additive is_of_fin_add_order] def is_of_fin_order (x : G) : Prop := (1 : G) ∈ periodic_pts ((*) x) lemma is_of_fin_add_order_of_mul_iff : is_of_fin_add_order (additive.of_mul x) ↔ is_of_fin_order x := iff.rfl lemma is_of_fin_order_of_add_iff : is_of_fin_order (multiplicative.of_add a) ↔ is_of_fin_add_order a := iff.rfl lemma is_of_fin_add_order_iff_nsmul_eq_zero (a : A) : is_of_fin_add_order a ↔ ∃ n, 0 < n ∧ n • a = 0 := by { convert iff.rfl, simp only [exists_prop, is_periodic_pt_add_iff_nsmul_eq_zero] } @[to_additive is_of_fin_add_order_iff_nsmul_eq_zero] lemma is_of_fin_order_iff_pow_eq_one (x : G) : is_of_fin_order x ↔ ∃ n, 0 < n ∧ x ^ n = 1 := by { convert iff.rfl, simp [is_periodic_pt_mul_iff_pow_eq_one] } end is_of_fin_order /-- `order_of x` is the order of the element `x`, i.e. the `n ≥ 1`, s.t. `x ^ n = 1` if it exists. Otherwise, i.e. if `x` is of infinite order, then `order_of x` is `0` by convention.-/ @[to_additive add_order_of "`add_order_of a` is the order of the element `a`, i.e. the `n ≥ 1`, s.t. `n • a = 0` if it exists. Otherwise, i.e. if `a` is of infinite order, then `add_order_of a` is `0` by convention."] noncomputable def order_of (x : G) : ℕ := minimal_period ((*) x) 1 @[to_additive] lemma commute.order_of_mul_dvd_lcm (h : commute x y) : order_of (x * y) ∣ nat.lcm (order_of x) (order_of y) := begin convert function.commute.minimal_period_of_comp_dvd_lcm h.function_commute_mul_left, rw [order_of, comp_mul_left], end @[simp] lemma add_order_of_of_mul_eq_order_of (x : G) : add_order_of (additive.of_mul x) = order_of x := rfl @[simp] lemma order_of_of_add_eq_add_order_of (a : A) : order_of (multiplicative.of_add a) = add_order_of a := rfl @[to_additive add_order_of_pos'] lemma order_of_pos' (h : is_of_fin_order x) : 0 < order_of x := minimal_period_pos_of_mem_periodic_pts h @[to_additive add_order_of_nsmul_eq_zero] lemma pow_order_of_eq_one (x : G) : x ^ order_of x = 1 := begin convert is_periodic_pt_minimal_period ((*) x) _, rw [order_of, mul_left_iterate, mul_one], end @[to_additive add_order_of_eq_zero] lemma order_of_eq_zero (h : ¬ is_of_fin_order x) : order_of x = 0 := by rwa [order_of, minimal_period, dif_neg] @[to_additive add_order_of_eq_zero_iff] lemma order_of_eq_zero_iff : order_of x = 0 ↔ ¬ is_of_fin_order x := ⟨λ h H, (order_of_pos' H).ne' h, order_of_eq_zero⟩ @[to_additive nsmul_ne_zero_of_lt_add_order_of'] lemma pow_eq_one_of_lt_order_of' (n0 : n ≠ 0) (h : n < order_of x) : x ^ n ≠ 1 := λ j, not_is_periodic_pt_of_pos_of_lt_minimal_period n0 h ((is_periodic_pt_mul_iff_pow_eq_one x).mpr j) @[to_additive add_order_of_le_of_nsmul_eq_zero] lemma order_of_le_of_pow_eq_one (hn : 0 < n) (h : x ^ n = 1) : order_of x ≤ n := is_periodic_pt.minimal_period_le hn (by rwa is_periodic_pt_mul_iff_pow_eq_one) @[simp, to_additive] lemma order_of_one : order_of (1 : G) = 1 := by rw [order_of, one_mul_eq_id, minimal_period_id] @[simp, to_additive add_monoid.order_of_eq_one_iff] lemma order_of_eq_one_iff : order_of x = 1 ↔ x = 1 := by rw [order_of, is_fixed_point_iff_minimal_period_eq_one, is_fixed_pt, mul_one] @[to_additive nsmul_eq_mod_add_order_of] lemma pow_eq_mod_order_of {n : ℕ} : x ^ n = x ^ (n % order_of x) := calc x ^ n = x ^ (n % order_of x + order_of x * (n / order_of x)) : by rw [nat.mod_add_div] ... = x ^ (n % order_of x) : by simp [pow_add, pow_mul, pow_order_of_eq_one] @[to_additive add_order_of_dvd_of_nsmul_eq_zero] lemma order_of_dvd_of_pow_eq_one (h : x ^ n = 1) : order_of x ∣ n := is_periodic_pt.minimal_period_dvd ((is_periodic_pt_mul_iff_pow_eq_one _).mpr h) @[to_additive add_order_of_dvd_iff_nsmul_eq_zero] lemma order_of_dvd_iff_pow_eq_one {n : ℕ} : order_of x ∣ n ↔ x ^ n = 1 := ⟨λ h, by rw [pow_eq_mod_order_of, nat.mod_eq_zero_of_dvd h, pow_zero], order_of_dvd_of_pow_eq_one⟩ @[to_additive exists_nsmul_eq_self_of_coprime] lemma exists_pow_eq_self_of_coprime (h : n.coprime (order_of x)) : ∃ m : ℕ, (x ^ n) ^ m = x := begin by_cases h0 : order_of x = 0, { rw [h0, coprime_zero_right] at h, exact ⟨1, by rw [h, pow_one, pow_one]⟩ }, by_cases h1 : order_of x = 1, { exact ⟨0, by rw [order_of_eq_one_iff.mp h1, one_pow, one_pow]⟩ }, obtain ⟨m, hm⟩ := exists_mul_mod_eq_one_of_coprime h (one_lt_iff_ne_zero_and_ne_one.mpr ⟨h0, h1⟩), exact ⟨m, by rw [←pow_mul, pow_eq_mod_order_of, hm, pow_one]⟩, end /-- If `x^n = 1`, but `x^(n/p) ≠ 1` for all prime factors `p` of `r`, then `x` has order `n` in `G`. -/ @[to_additive add_order_of_eq_of_nsmul_and_div_prime_nsmul] theorem order_of_eq_of_pow_and_pow_div_prime (hn : 0 < n) (hx : x^n = 1) (hd : ∀ p : ℕ, p.prime → p ∣ n → x^(n/p) ≠ 1) : order_of x = n := begin -- Let `a` be `n/(order_of x)`, and show `a = 1` cases exists_eq_mul_right_of_dvd (order_of_dvd_of_pow_eq_one hx) with a ha, suffices : a = 1, by simp [this, ha], -- Assume `a` is not one... by_contra, have a_min_fac_dvd_p_sub_one : a.min_fac ∣ n, { obtain ⟨b, hb⟩ : ∃ (b : ℕ), a = b * a.min_fac := exists_eq_mul_left_of_dvd a.min_fac_dvd, rw [hb, ←mul_assoc] at ha, exact dvd.intro_left (order_of x * b) ha.symm, }, -- Use the minimum prime factor of `a` as `p`. refine hd a.min_fac (nat.min_fac_prime h) a_min_fac_dvd_p_sub_one _, rw [←order_of_dvd_iff_pow_eq_one, nat.dvd_div_iff (a_min_fac_dvd_p_sub_one), ha, mul_comm, nat.mul_dvd_mul_iff_left (order_of_pos' _)], { exact nat.min_fac_dvd a, }, { rw is_of_fin_order_iff_pow_eq_one, exact Exists.intro n (id ⟨hn, hx⟩) }, end @[to_additive add_order_of_eq_add_order_of_iff] lemma order_of_eq_order_of_iff {H : Type*} [monoid H] {y : H} : order_of x = order_of y ↔ ∀ n : ℕ, x ^ n = 1 ↔ y ^ n = 1 := by simp_rw [← is_periodic_pt_mul_iff_pow_eq_one, ← minimal_period_eq_minimal_period_iff, order_of] @[to_additive add_order_of_injective] lemma order_of_injective {H : Type*} [monoid H] (f : G →* H) (hf : function.injective f) (x : G) : order_of (f x) = order_of x := by simp_rw [order_of_eq_order_of_iff, ←f.map_pow, ←f.map_one, hf.eq_iff, iff_self, forall_const] @[simp, norm_cast, to_additive] lemma order_of_submonoid {H : submonoid G} (y : H) : order_of (y : G) = order_of y := order_of_injective H.subtype subtype.coe_injective y @[to_additive order_of_add_units] lemma order_of_units {y : units G} : order_of (y : G) = order_of y := order_of_injective (units.coe_hom G) units.ext y variables (x) @[to_additive add_order_of_nsmul'] lemma order_of_pow' (h : n ≠ 0) : order_of (x ^ n) = order_of x / gcd (order_of x) n := begin convert minimal_period_iterate_eq_div_gcd h, simp only [order_of, mul_left_iterate], end variables (a) variable (n) @[to_additive add_order_of_nsmul''] lemma order_of_pow'' (h : is_of_fin_order x) : order_of (x ^ n) = order_of x / gcd (order_of x) n := begin convert minimal_period_iterate_eq_div_gcd' h, simp only [order_of, mul_left_iterate], end section p_prime variables {a x n} {p : ℕ} [hp : fact p.prime] include hp lemma add_order_of_eq_prime (hg : p • a = 0) (hg1 : a ≠ 0) : add_order_of a = p := minimal_period_eq_prime ((is_periodic_pt_add_iff_nsmul_eq_zero _).mpr hg) (by rwa [is_fixed_pt, add_zero]) @[to_additive add_order_of_eq_prime] lemma order_of_eq_prime (hg : x ^ p = 1) (hg1 : x ≠ 1) : order_of x = p := minimal_period_eq_prime ((is_periodic_pt_mul_iff_pow_eq_one _).mpr hg) (by rwa [is_fixed_pt, mul_one]) @[to_additive add_order_of_eq_prime_pow] lemma order_of_eq_prime_pow (hnot : ¬ x ^ p ^ n = 1) (hfin : x ^ p ^ (n + 1) = 1) : order_of x = p ^ (n + 1) := begin apply minimal_period_eq_prime_pow; rwa is_periodic_pt_mul_iff_pow_eq_one, end omit hp -- An example on how to determine the order of an element of a finite group. example : order_of (-1 : units ℤ) = 2 := begin haveI : fact (prime 2) := ⟨prime_two⟩, exact order_of_eq_prime (int.units_mul_self _) dec_trivial, end end p_prime end monoid_add_monoid section cancel_monoid variables [left_cancel_monoid G] (x) variables [add_left_cancel_monoid A] (a) @[to_additive nsmul_injective_aux] lemma pow_injective_aux (h : n ≤ m) (hm : m < order_of x) (eq : x ^ n = x ^ m) : n = m := by_contradiction $ assume ne : n ≠ m, have h₁ : m - n > 0, from nat.pos_of_ne_zero (by simp [tsub_eq_iff_eq_add_of_le h, ne.symm]), have h₂ : m = n + (m - n) := (add_tsub_cancel_of_le h).symm, have h₃ : x ^ (m - n) = 1, by { rw [h₂, pow_add] at eq, apply mul_left_cancel, convert eq.symm, exact mul_one (x ^ n) }, have le : order_of x ≤ m - n, from order_of_le_of_pow_eq_one h₁ h₃, have lt : m - n < order_of x, from (tsub_lt_iff_left h).mpr $ nat.lt_add_left _ _ _ hm, lt_irrefl _ (le.trans_lt lt) @[to_additive nsmul_injective_of_lt_add_order_of] lemma pow_injective_of_lt_order_of (hn : n < order_of x) (hm : m < order_of x) (eq : x ^ n = x ^ m) : n = m := (le_total n m).elim (assume h, pow_injective_aux x h hm eq) (assume h, (pow_injective_aux x h hn eq.symm).symm) end cancel_monoid section group variables [group G] [add_group A] {x a} {i : ℤ} @[to_additive add_order_of_dvd_iff_zsmul_eq_zero] lemma order_of_dvd_iff_zpow_eq_one : (order_of x : ℤ) ∣ i ↔ x ^ i = 1 := begin rcases int.eq_coe_or_neg i with ⟨i, rfl|rfl⟩, { rw [int.coe_nat_dvd, order_of_dvd_iff_pow_eq_one, zpow_coe_nat] }, { rw [dvd_neg, int.coe_nat_dvd, zpow_neg, inv_eq_one, zpow_coe_nat, order_of_dvd_iff_pow_eq_one] } end @[simp, norm_cast, to_additive] lemma order_of_subgroup {H : subgroup G} (y: H) : order_of (y : G) = order_of y := order_of_injective H.subtype subtype.coe_injective y @[to_additive zsmul_eq_mod_add_order_of] lemma zpow_eq_mod_order_of : x ^ i = x ^ (i % order_of x) := calc x ^ i = x ^ (i % order_of x + order_of x * (i / order_of x)) : by rw [int.mod_add_div] ... = x ^ (i % order_of x) : by simp [zpow_add, zpow_mul, pow_order_of_eq_one] set_option pp.all true @[to_additive nsmul_inj_iff_of_add_order_of_eq_zero] lemma pow_inj_iff_of_order_of_eq_zero (h : order_of x = 0) {n m : ℕ} : x ^ n = x ^ m ↔ n = m := begin by_cases hx : x = 1, { rw [←order_of_eq_one_iff, h] at hx, contradiction }, rw [order_of_eq_zero_iff, is_of_fin_order_iff_pow_eq_one] at h, push_neg at h, induction n with n IH generalizing m, { cases m, { simp }, { simpa [eq_comm] using h m.succ m.zero_lt_succ } }, { cases m, { simpa using h n.succ n.zero_lt_succ }, { simp [pow_succ, IH] } } end @[to_additive nsmul_inj_mod] lemma pow_inj_mod {n m : ℕ} : x ^ n = x ^ m ↔ n % order_of x = m % order_of x := begin cases (order_of x).zero_le.eq_or_lt with hx hx, { simp [pow_inj_iff_of_order_of_eq_zero, hx.symm] }, rw [pow_eq_mod_order_of, @pow_eq_mod_order_of _ _ _ m], exact ⟨pow_injective_of_lt_order_of _ (nat.mod_lt _ hx) (nat.mod_lt _ hx), λ h, congr_arg _ h⟩ end end group section fintype variables [fintype G] [fintype A] section finite_monoid variables [monoid G] [add_monoid A] open_locale big_operators @[to_additive sum_card_add_order_of_eq_card_nsmul_eq_zero] lemma sum_card_order_of_eq_card_pow_eq_one [decidable_eq G] (hn : 0 < n) : ∑ m in (finset.range n.succ).filter (∣ n), (finset.univ.filter (λ x : G, order_of x = m)).card = (finset.univ.filter (λ x : G, x ^ n = 1)).card := calc ∑ m in (finset.range n.succ).filter (∣ n), (finset.univ.filter (λ x : G, order_of x = m)).card = _ : (finset.card_bUnion (by { intros, apply finset.disjoint_filter.2, cc })).symm ... = _ : congr_arg finset.card (finset.ext (begin assume x, suffices : order_of x ≤ n ∧ order_of x ∣ n ↔ x ^ n = 1, { simpa [nat.lt_succ_iff], }, exact ⟨λ h, let ⟨m, hm⟩ := h.2 in by rw [hm, pow_mul, pow_order_of_eq_one, one_pow], λ h, ⟨order_of_le_of_pow_eq_one hn h, order_of_dvd_of_pow_eq_one h⟩⟩ end)) end finite_monoid section finite_cancel_monoid -- TODO: Of course everything also works for right_cancel_monoids. variables [left_cancel_monoid G] [add_left_cancel_monoid A] -- TODO: Use this to show that a finite left cancellative monoid is a group. @[to_additive exists_nsmul_eq_zero] lemma exists_pow_eq_one (x : G) : is_of_fin_order x := begin refine (is_of_fin_order_iff_pow_eq_one _).mpr _, obtain ⟨i, j, a_eq, ne⟩ : ∃(i j : ℕ), x ^ i = x ^ j ∧ i ≠ j := by simpa only [not_forall, exists_prop, injective] using (not_injective_infinite_fintype (λi:ℕ, x^i)), wlog h'' : j ≤ i, refine ⟨i - j, tsub_pos_of_lt (lt_of_le_of_ne h'' ne.symm), mul_right_injective (x^j) _⟩, rw [mul_one, ← pow_add, ← a_eq, add_tsub_cancel_of_le h''], end @[to_additive add_order_of_le_card_univ] lemma order_of_le_card_univ : order_of x ≤ fintype.card G := finset.le_card_of_inj_on_range ((^) x) (assume n _, finset.mem_univ _) (assume i hi j hj, pow_injective_of_lt_order_of x hi hj) /-- This is the same as `order_of_pos' but with one fewer explicit assumption since this is automatic in case of a finite cancellative monoid.-/ @[to_additive add_order_of_pos "This is the same as `add_order_of_pos' but with one fewer explicit assumption since this is automatic in case of a finite cancellative additive monoid."] lemma order_of_pos (x : G) : 0 < order_of x := order_of_pos' (exists_pow_eq_one x) open nat /-- This is the same as `order_of_pow'` and `order_of_pow''` but with one assumption less which is automatic in the case of a finite cancellative monoid.-/ @[to_additive add_order_of_nsmul "This is the same as `add_order_of_nsmul'` and `add_order_of_nsmul` but with one assumption less which is automatic in the case of a finite cancellative additive monoid."] lemma order_of_pow (x : G) : order_of (x ^ n) = order_of x / gcd (order_of x) n := order_of_pow'' _ _ (exists_pow_eq_one _) @[to_additive mem_multiples_iff_mem_range_add_order_of] lemma mem_powers_iff_mem_range_order_of [decidable_eq G] : y ∈ submonoid.powers x ↔ y ∈ (finset.range (order_of x)).image ((^) x : ℕ → G) := finset.mem_range_iff_mem_finset_range_of_mod_eq' (order_of_pos x) (assume i, pow_eq_mod_order_of.symm) @[to_additive decidable_multiples] noncomputable instance decidable_powers [decidable_eq G] : decidable_pred (∈ submonoid.powers x) := begin assume y, apply decidable_of_iff' (y ∈ (finset.range (order_of x)).image ((^) x)), exact mem_powers_iff_mem_range_order_of end /--The equivalence between `fin (order_of x)` and `submonoid.powers x`, sending `i` to `x ^ i`."-/ @[to_additive fin_equiv_multiples "The equivalence between `fin (add_order_of a)` and `add_submonoid.multiples a`, sending `i` to `i • a`."] noncomputable def fin_equiv_powers (x : G) : fin (order_of x) ≃ (submonoid.powers x : set G) := equiv.of_bijective (λ n, ⟨x ^ ↑n, ⟨n, rfl⟩⟩) ⟨λ ⟨i, hi⟩ ⟨j, hj⟩ ij, subtype.mk_eq_mk.2 (pow_injective_of_lt_order_of x hi hj (subtype.mk_eq_mk.1 ij)), λ ⟨_, i, rfl⟩, ⟨⟨i % order_of x, mod_lt i (order_of_pos x)⟩, subtype.eq pow_eq_mod_order_of.symm⟩⟩ @[simp, to_additive fin_equiv_multiples_apply] lemma fin_equiv_powers_apply {x : G} {n : fin (order_of x)} : fin_equiv_powers x n = ⟨x ^ ↑n, n, rfl⟩ := rfl @[simp, to_additive fin_equiv_multiples_symm_apply] lemma fin_equiv_powers_symm_apply (x : G) (n : ℕ) {hn : ∃ (m : ℕ), x ^ m = x ^ n} : ((fin_equiv_powers x).symm ⟨x ^ n, hn⟩) = ⟨n % order_of x, nat.mod_lt _ (order_of_pos x)⟩ := by rw [equiv.symm_apply_eq, fin_equiv_powers_apply, subtype.mk_eq_mk, pow_eq_mod_order_of, fin.coe_mk] /-- The equivalence between `submonoid.powers` of two elements `x, y` of the same order, mapping `x ^ i` to `y ^ i`. -/ @[to_additive multiples_equiv_multiples "The equivalence between `submonoid.multiples` of two elements `a, b` of the same additive order, mapping `i • a` to `i • b`."] noncomputable def powers_equiv_powers (h : order_of x = order_of y) : (submonoid.powers x : set G) ≃ (submonoid.powers y : set G) := (fin_equiv_powers x).symm.trans ((fin.cast h).to_equiv.trans (fin_equiv_powers y)) @[simp, to_additive multiples_equiv_multiples_apply] lemma powers_equiv_powers_apply (h : order_of x = order_of y) (n : ℕ) : powers_equiv_powers h ⟨x ^ n, n, rfl⟩ = ⟨y ^ n, n, rfl⟩ := begin rw [powers_equiv_powers, equiv.trans_apply, equiv.trans_apply, fin_equiv_powers_symm_apply, ← equiv.eq_symm_apply, fin_equiv_powers_symm_apply], simp [h] end @[to_additive add_order_of_eq_card_multiples] lemma order_eq_card_powers [decidable_eq G] : order_of x = fintype.card (submonoid.powers x : set G) := (fintype.card_fin (order_of x)).symm.trans (fintype.card_eq.2 ⟨fin_equiv_powers x⟩) end finite_cancel_monoid section finite_group variables [group G] [add_group A] @[to_additive] lemma exists_zpow_eq_one (x : G) : ∃ (i : ℤ) (H : i ≠ 0), x ^ (i : ℤ) = 1 := begin rcases exists_pow_eq_one x with ⟨w, hw1, hw2⟩, refine ⟨w, int.coe_nat_ne_zero.mpr (ne_of_gt hw1), _⟩, rw zpow_coe_nat, exact (is_periodic_pt_mul_iff_pow_eq_one _).mp hw2, end open subgroup @[to_additive mem_multiples_iff_mem_zmultiples] lemma mem_powers_iff_mem_zpowers : y ∈ submonoid.powers x ↔ y ∈ zpowers x := ⟨λ ⟨n, hn⟩, ⟨n, by simp * at *⟩, λ ⟨i, hi⟩, ⟨(i % order_of x).nat_abs, by rwa [← zpow_coe_nat, int.nat_abs_of_nonneg (int.mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 (order_of_pos x))), ← zpow_eq_mod_order_of]⟩⟩ @[to_additive multiples_eq_zmultiples] lemma powers_eq_zpowers (x : G) : (submonoid.powers x : set G) = zpowers x := set.ext $ λ x, mem_powers_iff_mem_zpowers @[to_additive mem_zmultiples_iff_mem_range_add_order_of] lemma mem_zpowers_iff_mem_range_order_of [decidable_eq G] : y ∈ subgroup.zpowers x ↔ y ∈ (finset.range (order_of x)).image ((^) x : ℕ → G) := by rw [← mem_powers_iff_mem_zpowers, mem_powers_iff_mem_range_order_of] @[to_additive decidable_zmultiples] noncomputable instance decidable_zpowers [decidable_eq G] : decidable_pred (∈ subgroup.zpowers x) := begin simp_rw ←set_like.mem_coe, rw ← powers_eq_zpowers, exact decidable_powers, end /-- The equivalence between `fin (order_of x)` and `subgroup.zpowers x`, sending `i` to `x ^ i`. -/ @[to_additive fin_equiv_zmultiples "The equivalence between `fin (add_order_of a)` and `subgroup.zmultiples a`, sending `i` to `i • a`."] noncomputable def fin_equiv_zpowers (x : G) : fin (order_of x) ≃ (subgroup.zpowers x : set G) := (fin_equiv_powers x).trans (equiv.set.of_eq (powers_eq_zpowers x)) @[simp, to_additive fin_equiv_zmultiples_apply] lemma fin_equiv_zpowers_apply {n : fin (order_of x)} : fin_equiv_zpowers x n = ⟨x ^ (n : ℕ), n, zpow_coe_nat x n⟩ := rfl @[simp, to_additive fin_equiv_zmultiples_symm_apply] lemma fin_equiv_zpowers_symm_apply (x : G) (n : ℕ) {hn : ∃ (m : ℤ), x ^ m = x ^ n} : ((fin_equiv_zpowers x).symm ⟨x ^ n, hn⟩) = ⟨n % order_of x, nat.mod_lt _ (order_of_pos x)⟩ := by { rw [fin_equiv_zpowers, equiv.symm_trans_apply, equiv.set.of_eq_symm_apply], exact fin_equiv_powers_symm_apply x n } /-- The equivalence between `subgroup.zpowers` of two elements `x, y` of the same order, mapping `x ^ i` to `y ^ i`. -/ @[to_additive zmultiples_equiv_zmultiples "The equivalence between `subgroup.zmultiples` of two elements `a, b` of the same additive order, mapping `i • a` to `i • b`."] noncomputable def zpowers_equiv_zpowers (h : order_of x = order_of y) : (subgroup.zpowers x : set G) ≃ (subgroup.zpowers y : set G) := (fin_equiv_zpowers x).symm.trans ((fin.cast h).to_equiv.trans (fin_equiv_zpowers y)) @[simp, to_additive zmultiples_equiv_zmultiples_apply] lemma zpowers_equiv_zpowers_apply (h : order_of x = order_of y) (n : ℕ) : zpowers_equiv_zpowers h ⟨x ^ n, n, zpow_coe_nat x n⟩ = ⟨y ^ n, n, zpow_coe_nat y n⟩ := begin rw [zpowers_equiv_zpowers, equiv.trans_apply, equiv.trans_apply, fin_equiv_zpowers_symm_apply, ← equiv.eq_symm_apply, fin_equiv_zpowers_symm_apply], simp [h] end @[to_additive add_order_eq_card_zmultiples] lemma order_eq_card_zpowers [decidable_eq G] : order_of x = fintype.card (subgroup.zpowers x : set G) := (fintype.card_fin (order_of x)).symm.trans (fintype.card_eq.2 ⟨fin_equiv_zpowers x⟩) open quotient_group /- TODO: use cardinal theory, introduce `card : set G → ℕ`, or setup decidability for cosets -/ @[to_additive add_order_of_dvd_card_univ] lemma order_of_dvd_card_univ : order_of x ∣ fintype.card G := begin classical, have ft_prod : fintype (quotient (zpowers x) × (zpowers x)), from fintype.of_equiv G group_equiv_quotient_times_subgroup, have ft_s : fintype (zpowers x), from @fintype.prod_right _ _ _ ft_prod _, have ft_cosets : fintype (quotient (zpowers x)), from @fintype.prod_left _ _ _ ft_prod ⟨⟨1, (zpowers x).one_mem⟩⟩, have eq₁ : fintype.card G = @fintype.card _ ft_cosets * @fintype.card _ ft_s, from calc fintype.card G = @fintype.card _ ft_prod : @fintype.card_congr _ _ _ ft_prod group_equiv_quotient_times_subgroup ... = @fintype.card _ (@prod.fintype _ _ ft_cosets ft_s) : congr_arg (@fintype.card _) $ subsingleton.elim _ _ ... = @fintype.card _ ft_cosets * @fintype.card _ ft_s : @fintype.card_prod _ _ ft_cosets ft_s, have eq₂ : order_of x = @fintype.card _ ft_s, from calc order_of x = _ : order_eq_card_zpowers ... = _ : congr_arg (@fintype.card _) $ subsingleton.elim _ _, exact dvd.intro (@fintype.card (quotient (subgroup.zpowers x)) ft_cosets) (by rw [eq₁, eq₂, mul_comm]) end @[simp, to_additive card_nsmul_eq_zero] lemma pow_card_eq_one : x ^ fintype.card G = 1 := let ⟨m, hm⟩ := @order_of_dvd_card_univ _ x _ _ in by simp [hm, pow_mul, pow_order_of_eq_one] @[to_additive nsmul_eq_mod_card] lemma pow_eq_mod_card (n : ℕ) : x ^ n = x ^ (n % fintype.card G) := by rw [pow_eq_mod_order_of, ←nat.mod_mod_of_dvd n order_of_dvd_card_univ, ← pow_eq_mod_order_of] @[to_additive] lemma zpow_eq_mod_card (n : ℤ) : x ^ n = x ^ (n % fintype.card G) := by rw [zpow_eq_mod_order_of, ← int.mod_mod_of_dvd n (int.coe_nat_dvd.2 order_of_dvd_card_univ), ← zpow_eq_mod_order_of] /-- If `gcd(|G|,n)=1` then the `n`th power map is a bijection -/ @[simps] def pow_coprime (h : nat.coprime (fintype.card G) n) : G ≃ G := { to_fun := λ g, g ^ n, inv_fun := λ g, g ^ (nat.gcd_b (fintype.card G) n), left_inv := λ g, by { have key : g ^ _ = g ^ _ := congr_arg (λ n : ℤ, g ^ n) (nat.gcd_eq_gcd_ab (fintype.card G) n), rwa [zpow_add, zpow_mul, zpow_mul, zpow_coe_nat, zpow_coe_nat, zpow_coe_nat, h.gcd_eq_one, pow_one, pow_card_eq_one, one_zpow, one_mul, eq_comm] at key }, right_inv := λ g, by { have key : g ^ _ = g ^ _ := congr_arg (λ n : ℤ, g ^ n) (nat.gcd_eq_gcd_ab (fintype.card G) n), rwa [zpow_add, zpow_mul, zpow_mul', zpow_coe_nat, zpow_coe_nat, zpow_coe_nat, h.gcd_eq_one, pow_one, pow_card_eq_one, one_zpow, one_mul, eq_comm] at key } } @[simp] lemma pow_coprime_one (h : nat.coprime (fintype.card G) n) : pow_coprime h 1 = 1 := one_pow n @[simp] lemma pow_coprime_inv (h : nat.coprime (fintype.card G) n) {g : G} : pow_coprime h g⁻¹ = (pow_coprime h g)⁻¹ := inv_pow g n lemma inf_eq_bot_of_coprime {G : Type*} [group G] {H K : subgroup G} [fintype H] [fintype K] (h : nat.coprime (fintype.card H) (fintype.card K)) : H ⊓ K = ⊥ := begin refine (H ⊓ K).eq_bot_iff_forall.mpr (λ x hx, _), rw [←order_of_eq_one_iff, ←nat.dvd_one, ←h.gcd_eq_one, nat.dvd_gcd_iff], exact ⟨(congr_arg (∣ fintype.card H) (order_of_subgroup ⟨x, hx.1⟩)).mpr order_of_dvd_card_univ, (congr_arg (∣ fintype.card K) (order_of_subgroup ⟨x, hx.2⟩)).mpr order_of_dvd_card_univ⟩, end variable (a) lemma image_range_add_order_of [decidable_eq A] : finset.image (λ i, i • a) (finset.range (add_order_of a)) = (add_subgroup.zmultiples a : set A).to_finset := by {ext x, rw [set.mem_to_finset, set_like.mem_coe, mem_zmultiples_iff_mem_range_add_order_of] } /-- TODO: Generalise to `submonoid.powers`.-/ @[to_additive image_range_add_order_of] lemma image_range_order_of [decidable_eq G] : finset.image (λ i, x ^ i) (finset.range (order_of x)) = (zpowers x : set G).to_finset := by { ext x, rw [set.mem_to_finset, set_like.mem_coe, mem_zpowers_iff_mem_range_order_of] } /-- TODO: Generalise to `finite_cancel_monoid`. -/ @[to_additive gcd_nsmul_card_eq_zero_iff] lemma pow_gcd_card_eq_one_iff : x ^ n = 1 ↔ x ^ (gcd n (fintype.card G)) = 1 := ⟨λ h, pow_gcd_eq_one _ h $ pow_card_eq_one, λ h, let ⟨m, hm⟩ := gcd_dvd_left n (fintype.card G) in by rw [hm, pow_mul, h, one_pow]⟩ end finite_group end fintype section pow_is_subgroup /-- A nonempty idempotent subset of a finite cancellative monoid is a submonoid -/ def submonoid_of_idempotent {M : Type*} [left_cancel_monoid M] [fintype M] (S : set M) (hS1 : S.nonempty) (hS2 : S * S = S) : submonoid M := have pow_mem : ∀ a : M, a ∈ S → ∀ n : ℕ, a ^ (n + 1) ∈ S := λ a ha, nat.rec (by rwa [zero_add, pow_one]) (λ n ih, (congr_arg2 (∈) (pow_succ a (n + 1)).symm hS2).mp (set.mul_mem_mul ha ih)), { carrier := S, one_mem' := by { obtain ⟨a, ha⟩ := hS1, rw [←pow_order_of_eq_one a, ← tsub_add_cancel_of_le (succ_le_of_lt (order_of_pos a))], exact pow_mem a ha (order_of a - 1) }, mul_mem' := λ a b ha hb, (congr_arg2 (∈) rfl hS2).mp (set.mul_mem_mul ha hb) } /-- A nonempty idempotent subset of a finite group is a subgroup -/ def subgroup_of_idempotent {G : Type*} [group G] [fintype G] (S : set G) (hS1 : S.nonempty) (hS2 : S * S = S) : subgroup G := { carrier := S, inv_mem' := λ a ha, by { rw [←one_mul a⁻¹, ←pow_one a, ←pow_order_of_eq_one a, ←pow_sub a (order_of_pos a)], exact (submonoid_of_idempotent S hS1 hS2).pow_mem ha (order_of a - 1) }, .. submonoid_of_idempotent S hS1 hS2 } /-- If `S` is a nonempty subset of a finite group `G`, then `S ^ |G|` is a subgroup -/ def pow_card_subgroup {G : Type*} [group G] [fintype G] (S : set G) (hS : S.nonempty) : subgroup G := have one_mem : (1 : G) ∈ (S ^ fintype.card G) := by { obtain ⟨a, ha⟩ := hS, rw ← pow_card_eq_one, exact set.pow_mem_pow ha (fintype.card G) }, subgroup_of_idempotent (S ^ (fintype.card G)) ⟨1, one_mem⟩ begin classical, refine (set.eq_of_subset_of_card_le (λ b hb, (congr_arg (∈ _) (one_mul b)).mp (set.mul_mem_mul one_mem hb)) (ge_of_eq _)).symm, change _ = fintype.card (_ * _ : set G), rw [←pow_add, group.card_pow_eq_card_pow_card_univ S (fintype.card G) le_rfl, group.card_pow_eq_card_pow_card_univ S (fintype.card G + fintype.card G) le_add_self], end end pow_is_subgroup
36560d4f5085b6ce58fe3905ed84a998f7dd65b0
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/preadditive/schur.lean
72adf4c71242d1bd33a2216c492676303a11cac7
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
1,811
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel, Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.simple import Mathlib.category_theory.preadditive.default import Mathlib.PostPort universes u v namespace Mathlib /-! # Schur's lemma We prove the part of Schur's Lemma that holds in any preadditive category with kernels, that any nonzero morphism between simple objects is an isomorphism. ## TODO If the category is enriched over finite dimensional vector spaces over an algebraically closed field, then we can further prove that `dim (X ⟶ Y) ≤ 1`. (Probably easiest to prove this for endomorphisms first: some polynomial `p` in `f : X ⟶ X` vanishes by finite dimensionality, that polynomial factors linearly, and at least one factor must be non-invertible, hence zero, so `f` is a scalar multiple of the identity. Then for any two nonzero `f g : X ⟶ Y`, observe `f ≫ g⁻¹` is a multiple of the identity.) -/ namespace category_theory /-- Schur's Lemma (for a general preadditive category), that a nonzero morphism between simple objects is an isomorphism. -/ def is_iso_of_hom_simple {C : Type u} [category C] [preadditive C] [limits.has_kernels C] {X : C} {Y : C} [simple X] [simple Y] {f : X ⟶ Y} (w : f ≠ 0) : is_iso f := is_iso_of_mono_of_nonzero w /-- As a corollary of Schur's lemma, any morphism between simple objects is (exclusively) either an isomorphism or zero. -/ def is_iso_equiv_nonzero {C : Type u} [category C] [preadditive C] [limits.has_kernels C] {X : C} {Y : C} [simple X] [simple Y] {f : X ⟶ Y} : is_iso f ≃ f ≠ 0 := equiv.mk sorry (fun (w : f ≠ 0) => is_iso_of_hom_simple w) sorry sorry
9fe781b2162ae681ccd0c9dd84104bd390b91ba6
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/ring_theory/witt_vector/frobenius_fraction_field.lean
e9cd65c73af4f49789074aab6002b93ed192c2a1
[ "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
11,970
lean
/- Copyright (c) 2022 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis, Heather Macbeth -/ import data.nat.cast.with_top import field_theory.is_alg_closed.basic import ring_theory.witt_vector.discrete_valuation_ring /-! # Solving equations about the Frobenius map on the field of fractions of `𝕎 k` > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. The goal of this file is to prove `witt_vector.exists_frobenius_solution_fraction_ring`, which says that for an algebraically closed field `k` of characteristic `p` and `a, b` in the field of fractions of Witt vectors over `k`, there is a solution `b` to the equation `φ b * a = p ^ m * b`, where `φ` is the Frobenius map. Most of this file builds up the equivalent theorem over `𝕎 k` directly, moving to the field of fractions at the end. See `witt_vector.frobenius_rotation` and its specification. The construction proceeds by recursively defining a sequence of coefficients as solutions to a polynomial equation in `k`. We must define these as generic polynomials using Witt vector API (`witt_vector.witt_mul`, `witt_polynomial`) to show that they satisfy the desired equation. Preliminary work is done in the dependency `ring_theory.witt_vector.mul_coeff` to isolate the `n+1`st coefficients of `x` and `y` in the `n+1`st coefficient of `x*y`. This construction is described in Dupuis, Lewis, and Macbeth, [Formalized functional analysis via semilinear maps][dupuis-lewis-macbeth2022]. We approximately follow an approach sketched on MathOverflow: <https://mathoverflow.net/questions/62468/about-frobenius-of-witt-vectors> The result is a dependency for the proof of `witt_vector.isocrystal_classification`, the classification of one-dimensional isocrystals over an algebraically closed field. -/ noncomputable theory namespace witt_vector variables (p : ℕ) [hp : fact p.prime] local notation `𝕎` := witt_vector p namespace recursion_main /-! ## The recursive case of the vector coefficients The first coefficient of our solution vector is easy to define below. In this section we focus on the recursive case. The goal is to turn `witt_poly_prod n` into a univariate polynomial whose variable represents the `n`th coefficient of `x` in `x * a`. -/ section comm_ring include hp variables {k : Type*} [comm_ring k] [char_p k p] open polynomial /-- The root of this polynomial determines the `n+1`st coefficient of our solution. -/ def succ_nth_defining_poly (n : ℕ) (a₁ a₂ : 𝕎 k) (bs : fin (n+1) → k) : polynomial k := X^p * C (a₁.coeff 0 ^ (p^(n+1))) - X * C (a₂.coeff 0 ^ (p^(n+1))) + C (a₁.coeff (n+1) * ((bs 0)^p)^(p^(n+1)) + nth_remainder p n (λ v, (bs v)^p) (truncate_fun (n+1) a₁) - a₂.coeff (n+1) * (bs 0)^p^(n+1) - nth_remainder p n bs (truncate_fun (n+1) a₂)) lemma succ_nth_defining_poly_degree [is_domain k] (n : ℕ) (a₁ a₂ : 𝕎 k) (bs : fin (n+1) → k) (ha₁ : a₁.coeff 0 ≠ 0) (ha₂ : a₂.coeff 0 ≠ 0) : (succ_nth_defining_poly p n a₁ a₂ bs).degree = p := begin have : (X ^ p * C (a₁.coeff 0 ^ p ^ (n+1))).degree = p, { rw [degree_mul, degree_C], { simp only [nat.cast_with_bot, add_zero, degree_X, degree_pow, nat.smul_one_eq_coe] }, { exact pow_ne_zero _ ha₁ } }, have : (X ^ p * C (a₁.coeff 0 ^ p ^ (n+1)) - X * C (a₂.coeff 0 ^ p ^ (n+1))).degree = p, { rw [degree_sub_eq_left_of_degree_lt, this], rw [this, degree_mul, degree_C, degree_X, add_zero], { exact_mod_cast hp.out.one_lt }, { exact pow_ne_zero _ ha₂ } }, rw [succ_nth_defining_poly, degree_add_eq_left_of_degree_lt, this], apply lt_of_le_of_lt (degree_C_le), rw [this], exact_mod_cast hp.out.pos end end comm_ring section is_alg_closed include hp variables {k : Type*} [field k] [char_p k p] [is_alg_closed k] lemma root_exists (n : ℕ) (a₁ a₂ : 𝕎 k) (bs : fin (n+1) → k) (ha₁ : a₁.coeff 0 ≠ 0) (ha₂ : a₂.coeff 0 ≠ 0) : ∃ b : k, (succ_nth_defining_poly p n a₁ a₂ bs).is_root b := is_alg_closed.exists_root _ $ by simp only [(succ_nth_defining_poly_degree p n a₁ a₂ bs ha₁ ha₂), hp.out.ne_zero, with_top.coe_eq_zero, ne.def, not_false_iff] /-- This is the `n+1`st coefficient of our solution, projected from `root_exists`. -/ def succ_nth_val (n : ℕ) (a₁ a₂ : 𝕎 k) (bs : fin (n+1) → k) (ha₁ : a₁.coeff 0 ≠ 0) (ha₂ : a₂.coeff 0 ≠ 0) : k := classical.some (root_exists p n a₁ a₂ bs ha₁ ha₂) lemma succ_nth_val_spec (n : ℕ) (a₁ a₂ : 𝕎 k) (bs : fin (n+1) → k) (ha₁ : a₁.coeff 0 ≠ 0) (ha₂ : a₂.coeff 0 ≠ 0) : (succ_nth_defining_poly p n a₁ a₂ bs).is_root (succ_nth_val p n a₁ a₂ bs ha₁ ha₂) := classical.some_spec (root_exists p n a₁ a₂ bs ha₁ ha₂) lemma succ_nth_val_spec' (n : ℕ) (a₁ a₂ : 𝕎 k) (bs : fin (n+1) → k) (ha₁ : a₁.coeff 0 ≠ 0) (ha₂ : a₂.coeff 0 ≠ 0) : (succ_nth_val p n a₁ a₂ bs ha₁ ha₂)^p * a₁.coeff 0 ^ (p^(n+1)) + a₁.coeff (n+1) * ((bs 0)^p)^(p^(n+1)) + nth_remainder p n (λ v, (bs v)^p) (truncate_fun (n+1) a₁) = (succ_nth_val p n a₁ a₂ bs ha₁ ha₂) * a₂.coeff 0 ^ (p^(n+1)) + a₂.coeff (n+1) * (bs 0)^(p^(n+1)) + nth_remainder p n bs (truncate_fun (n+1) a₂) := begin rw ← sub_eq_zero, have := succ_nth_val_spec p n a₁ a₂ bs ha₁ ha₂, simp only [polynomial.map_add, polynomial.eval_X, polynomial.map_pow, polynomial.eval_C, polynomial.eval_pow, succ_nth_defining_poly, polynomial.eval_mul, polynomial.eval_add, polynomial.eval_sub, polynomial.map_mul, polynomial.map_sub, polynomial.is_root.def] at this, convert this using 1, ring end end is_alg_closed end recursion_main namespace recursion_base include hp variables {k : Type*} [field k] [is_alg_closed k] lemma solution_pow (a₁ a₂ : 𝕎 k) : ∃ x : k, x^(p-1) = a₂.coeff 0 / a₁.coeff 0 := is_alg_closed.exists_pow_nat_eq _ $ by linarith [hp.out.one_lt, le_of_lt hp.out.one_lt] /-- The base case (0th coefficient) of our solution vector. -/ def solution (a₁ a₂ : 𝕎 k) : k := classical.some $ solution_pow p a₁ a₂ lemma solution_spec (a₁ a₂ : 𝕎 k) : (solution p a₁ a₂)^(p-1) = a₂.coeff 0 / a₁.coeff 0 := classical.some_spec $ solution_pow p a₁ a₂ lemma solution_nonzero {a₁ a₂ : 𝕎 k} (ha₁ : a₁.coeff 0 ≠ 0) (ha₂ : a₂.coeff 0 ≠ 0) : solution p a₁ a₂ ≠ 0 := begin intro h, have := solution_spec p a₁ a₂, rw [h, zero_pow] at this, { simpa [ha₁, ha₂] using _root_.div_eq_zero_iff.mp this.symm }, { linarith [hp.out.one_lt, le_of_lt hp.out.one_lt] } end lemma solution_spec' {a₁ : 𝕎 k} (ha₁ : a₁.coeff 0 ≠ 0) (a₂ : 𝕎 k) : (solution p a₁ a₂)^p * a₁.coeff 0 = (solution p a₁ a₂) * a₂.coeff 0 := begin have := solution_spec p a₁ a₂, cases nat.exists_eq_succ_of_ne_zero hp.out.ne_zero with q hq, have hq' : q = p - 1 := by simp only [hq, tsub_zero, nat.succ_sub_succ_eq_sub], conv_lhs {congr, congr, skip, rw hq}, rw [pow_succ', hq', this], field_simp [ha₁, mul_comm], end end recursion_base open recursion_main recursion_base section frobenius_rotation section is_alg_closed include hp variables {k : Type*} [field k] [char_p k p] [is_alg_closed k] /-- Recursively defines the sequence of coefficients for `witt_vector.frobenius_rotation`. -/ noncomputable def frobenius_rotation_coeff {a₁ a₂ : 𝕎 k} (ha₁ : a₁.coeff 0 ≠ 0) (ha₂ : a₂.coeff 0 ≠ 0) : ℕ → k | 0 := solution p a₁ a₂ | (n + 1) := succ_nth_val p n a₁ a₂ (λ i, frobenius_rotation_coeff i.val) ha₁ ha₂ using_well_founded { dec_tac := `[apply fin.is_lt] } /-- For nonzero `a₁` and `a₂`, `frobenius_rotation a₁ a₂` is a Witt vector that satisfies the equation `frobenius (frobenius_rotation a₁ a₂) * a₁ = (frobenius_rotation a₁ a₂) * a₂`. -/ def frobenius_rotation {a₁ a₂ : 𝕎 k} (ha₁ : a₁.coeff 0 ≠ 0) (ha₂ : a₂.coeff 0 ≠ 0) : 𝕎 k := witt_vector.mk p (frobenius_rotation_coeff p ha₁ ha₂) lemma frobenius_rotation_nonzero {a₁ a₂ : 𝕎 k} (ha₁ : a₁.coeff 0 ≠ 0) (ha₂ : a₂.coeff 0 ≠ 0) : frobenius_rotation p ha₁ ha₂ ≠ 0 := begin intro h, apply solution_nonzero p ha₁ ha₂, simpa [← h, frobenius_rotation, frobenius_rotation_coeff] using witt_vector.zero_coeff p k 0 end lemma frobenius_frobenius_rotation {a₁ a₂ : 𝕎 k} (ha₁ : a₁.coeff 0 ≠ 0) (ha₂ : a₂.coeff 0 ≠ 0) : frobenius (frobenius_rotation p ha₁ ha₂) * a₁ = (frobenius_rotation p ha₁ ha₂) * a₂ := begin ext n, induction n with n ih, { simp only [witt_vector.mul_coeff_zero, witt_vector.coeff_frobenius_char_p, frobenius_rotation, frobenius_rotation_coeff], apply solution_spec' _ ha₁ }, { simp only [nth_remainder_spec, witt_vector.coeff_frobenius_char_p, frobenius_rotation_coeff, frobenius_rotation, fin.val_eq_coe], have := succ_nth_val_spec' p n a₁ a₂ (λ (i : fin (n + 1)), frobenius_rotation_coeff p ha₁ ha₂ i.val) ha₁ ha₂, simp only [frobenius_rotation_coeff, fin.val_eq_coe, fin.val_zero] at this, convert this using 4, apply truncated_witt_vector.ext, intro i, simp only [fin.val_eq_coe, witt_vector.coeff_truncate_fun, witt_vector.coeff_frobenius_char_p], refl } end local notation `φ` := is_fraction_ring.field_equiv_of_ring_equiv (frobenius_equiv p k) lemma exists_frobenius_solution_fraction_ring_aux (m n : ℕ) (r' q' : 𝕎 k) (hr' : r'.coeff 0 ≠ 0) (hq' : q'.coeff 0 ≠ 0) (hq : ↑p ^ n * q' ∈ non_zero_divisors (𝕎 k)) : let b : 𝕎 k := frobenius_rotation p hr' hq' in is_fraction_ring.field_equiv_of_ring_equiv (frobenius_equiv p k) (algebra_map (𝕎 k) (fraction_ring (𝕎 k)) b) * localization.mk (↑p ^ m * r') ⟨↑p ^ n * q', hq⟩ = ↑p ^ (m - n : ℤ) * algebra_map (𝕎 k) (fraction_ring (𝕎 k)) b := begin intros b, have key : witt_vector.frobenius b * p ^ m * r' * p ^ n = p ^ m * b * (p ^ n * q'), { have H := congr_arg (λ x : 𝕎 k, x * p ^ m * p ^ n) (frobenius_frobenius_rotation p hr' hq'), dsimp at H, refine (eq.trans _ H).trans _; ring }, have hq'' : algebra_map (𝕎 k) (fraction_ring (𝕎 k)) q' ≠ 0, { have hq''' : q' ≠ 0 := λ h, hq' (by simp [h]), simpa only [ne.def, map_zero] using (is_fraction_ring.injective (𝕎 k) (fraction_ring (𝕎 k))).ne hq''' }, rw zpow_sub₀ (fraction_ring.p_nonzero p k), field_simp [fraction_ring.p_nonzero p k], simp only [is_fraction_ring.field_equiv_of_ring_equiv, is_localization.ring_equiv_of_ring_equiv_eq, ring_equiv.coe_of_bijective], convert congr_arg (λ x, algebra_map (𝕎 k) (fraction_ring (𝕎 k)) x) key using 1, { simp only [ring_hom.map_mul, ring_hom.map_pow, map_nat_cast, frobenius_equiv_apply], ring }, { simp only [ring_hom.map_mul, ring_hom.map_pow, map_nat_cast] } end lemma exists_frobenius_solution_fraction_ring {a : fraction_ring (𝕎 k)} (ha : a ≠ 0) : ∃ (b : fraction_ring (𝕎 k)) (hb : b ≠ 0) (m : ℤ), φ b * a = p ^ m * b := begin revert ha, refine localization.induction_on a _, rintros ⟨r, q, hq⟩ hrq, have hq0 : q ≠ 0 := mem_non_zero_divisors_iff_ne_zero.1 hq, have hr0 : r ≠ 0 := λ h, hrq (by simp [h]), obtain ⟨m, r', hr', rfl⟩ := exists_eq_pow_p_mul r hr0, obtain ⟨n, q', hq', rfl⟩ := exists_eq_pow_p_mul q hq0, let b := frobenius_rotation p hr' hq', refine ⟨algebra_map (𝕎 k) _ b, _, m - n, _⟩, { simpa only [map_zero] using (is_fraction_ring.injective (witt_vector p k) (fraction_ring (witt_vector p k))).ne (frobenius_rotation_nonzero p hr' hq')}, exact exists_frobenius_solution_fraction_ring_aux p m n r' q' hr' hq' hq, end end is_alg_closed end frobenius_rotation end witt_vector
696d61f7e163c13c2b85dc4a25c0497e1d0d67a6
46125763b4dbf50619e8846a1371029346f4c3db
/src/topology/metric_space/basic.lean
ad4e772fafe0caea1e64c02a2728692dd91df76d
[ "Apache-2.0" ]
permissive
thjread/mathlib
a9d97612cedc2c3101060737233df15abcdb9eb1
7cffe2520a5518bba19227a107078d83fa725ddc
refs/heads/master
1,615,637,696,376
1,583,953,063,000
1,583,953,063,000
246,680,271
0
0
Apache-2.0
1,583,960,875,000
1,583,960,875,000
null
UTF-8
Lean
false
false
66,301
lean
/- Copyright (c) 2015, 2017 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Metric spaces. Authors: Jeremy Avigad, Robert Y. Lewis, Johannes Hölzl, Mario Carneiro, Sébastien Gouëzel Many definitions and theorems expected on metric spaces are already introduced on uniform spaces and topological spaces. For example: open and closed sets, compactness, completeness, continuity and uniform continuity -/ import data.real.nnreal topology.metric_space.emetric_space topology.algebra.ordered open lattice set filter classical topological_space noncomputable theory open_locale uniformity open_locale topological_space universes u v w variables {α : Type u} {β : Type v} {γ : Type w} /-- Construct a uniform structure from a distance function and metric space axioms -/ def uniform_space_of_dist (dist : α → α → ℝ) (dist_self : ∀ x : α, dist x x = 0) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) : uniform_space α := uniform_space.of_core { uniformity := (⨅ ε>0, principal {p:α×α | dist p.1 p.2 < ε}), refl := le_infi $ assume ε, le_infi $ by simp [set.subset_def, id_rel, dist_self, (>)] {contextual := tt}, comp := le_infi $ assume ε, le_infi $ assume h, lift'_le (mem_infi_sets (ε / 2) $ mem_infi_sets (div_pos_of_pos_of_pos h two_pos) (subset.refl _)) $ have ∀ (a b c : α), dist a c < ε / 2 → dist c b < ε / 2 → dist a b < ε, from assume a b c hac hcb, calc dist a b ≤ dist a c + dist c b : dist_triangle _ _ _ ... < ε / 2 + ε / 2 : add_lt_add hac hcb ... = ε : by rw [div_add_div_same, add_self_div_two], by simpa [comp_rel], symm := tendsto_infi.2 $ assume ε, tendsto_infi.2 $ assume h, tendsto_infi' ε $ tendsto_infi' h $ tendsto_principal_principal.2 $ by simp [dist_comm] } /-- The distance function (given an ambient metric space on `α`), which returns a nonnegative real number `dist x y` given `x y : α`. -/ class has_dist (α : Type*) := (dist : α → α → ℝ) export has_dist (dist) section prio set_option default_priority 100 -- see Note [default priority] /-- Metric space Each metric space induces a canonical `uniform_space` and hence a canonical `topological_space`. This is enforced in the type class definition, by extending the `uniform_space` structure. When instantiating a `metric_space` structure, the uniformity fields are not necessary, they will be filled in by default. In the same way, each metric space induces an emetric space structure. It is included in the structure, but filled in by default. When one instantiates a metric space structure, for instance a product structure, this makes it possible to use a uniform structure and an edistance that are exactly the ones for the uniform spaces product and the emetric spaces products, thereby ensuring that everything in defeq in diamonds.-/ class metric_space (α : Type u) extends has_dist α : Type u := (dist_self : ∀ x : α, dist x x = 0) (eq_of_dist_eq_zero : ∀ {x y : α}, dist x y = 0 → x = y) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) (edist : α → α → ennreal := λx y, ennreal.of_real (dist x y)) (edist_dist : ∀ x y : α, edist x y = ennreal.of_real (dist x y) . control_laws_tac) (to_uniform_space : uniform_space α := uniform_space_of_dist dist dist_self dist_comm dist_triangle) (uniformity_dist : 𝓤 α = ⨅ ε>0, principal {p:α×α | dist p.1 p.2 < ε} . control_laws_tac) end prio variables [metric_space α] @[priority 100] -- see Note [lower instance priority] instance metric_space.to_uniform_space' : uniform_space α := metric_space.to_uniform_space α @[priority 200] -- see Note [lower instance priority] instance metric_space.to_has_edist : has_edist α := ⟨metric_space.edist⟩ @[simp] theorem dist_self (x : α) : dist x x = 0 := metric_space.dist_self x theorem eq_of_dist_eq_zero {x y : α} : dist x y = 0 → x = y := metric_space.eq_of_dist_eq_zero theorem dist_comm (x y : α) : dist x y = dist y x := metric_space.dist_comm x y theorem edist_dist (x y : α) : edist x y = ennreal.of_real (dist x y) := metric_space.edist_dist _ x y @[simp] theorem dist_eq_zero {x y : α} : dist x y = 0 ↔ x = y := iff.intro eq_of_dist_eq_zero (assume : x = y, this ▸ dist_self _) @[simp] theorem zero_eq_dist {x y : α} : 0 = dist x y ↔ x = y := by rw [eq_comm, dist_eq_zero] theorem dist_triangle (x y z : α) : dist x z ≤ dist x y + dist y z := metric_space.dist_triangle x y z theorem dist_triangle_left (x y z : α) : dist x y ≤ dist z x + dist z y := by rw dist_comm z; apply dist_triangle theorem dist_triangle_right (x y z : α) : dist x y ≤ dist x z + dist y z := by rw dist_comm y; apply dist_triangle lemma dist_triangle4 (x y z w : α) : dist x w ≤ dist x y + dist y z + dist z w := calc dist x w ≤ dist x z + dist z w : dist_triangle x z w ... ≤ (dist x y + dist y z) + dist z w : add_le_add_right (metric_space.dist_triangle x y z) _ lemma dist_triangle4_left (x₁ y₁ x₂ y₂ : α) : dist x₂ y₂ ≤ dist x₁ y₁ + (dist x₁ x₂ + dist y₁ y₂) := by rw [add_left_comm, dist_comm x₁, ← add_assoc]; apply dist_triangle4 lemma dist_triangle4_right (x₁ y₁ x₂ y₂ : α) : dist x₁ y₁ ≤ dist x₁ x₂ + dist y₁ y₂ + dist x₂ y₂ := by rw [add_right_comm, dist_comm y₁]; apply dist_triangle4 /-- The triangle (polygon) inequality for sequences of points; `finset.Ico` version. -/ lemma dist_le_Ico_sum_dist (f : ℕ → α) {m n} (h : m ≤ n) : dist (f m) (f n) ≤ (finset.Ico m n).sum (λ i, dist (f i) (f (i + 1))) := begin revert n, apply nat.le_induction, { simp only [finset.sum_empty, finset.Ico.self_eq_empty, dist_self] }, { assume n hn hrec, calc dist (f m) (f (n+1)) ≤ dist (f m) (f n) + dist _ _ : dist_triangle _ _ _ ... ≤ (finset.Ico m n).sum _ + _ : add_le_add hrec (le_refl _) ... = (finset.Ico m (n+1)).sum _ : by rw [finset.Ico.succ_top hn, finset.sum_insert, add_comm]; simp } end /-- The triangle (polygon) inequality for sequences of points; `finset.range` version. -/ lemma dist_le_range_sum_dist (f : ℕ → α) (n : ℕ) : dist (f 0) (f n) ≤ (finset.range n).sum (λ i, dist (f i) (f (i + 1))) := finset.Ico.zero_bot n ▸ dist_le_Ico_sum_dist f (nat.zero_le n) /-- A version of `dist_le_Ico_sum_dist` with each intermediate distance replaced with an upper estimate. -/ lemma dist_le_Ico_sum_of_dist_le {f : ℕ → α} {m n} (hmn : m ≤ n) {d : ℕ → ℝ} (hd : ∀ {k}, m ≤ k → k < n → dist (f k) (f (k + 1)) ≤ d k) : dist (f m) (f n) ≤ (finset.Ico m n).sum d := le_trans (dist_le_Ico_sum_dist f hmn) $ finset.sum_le_sum $ λ k hk, hd (finset.Ico.mem.1 hk).1 (finset.Ico.mem.1 hk).2 /-- A version of `dist_le_range_sum_dist` with each intermediate distance replaced with an upper estimate. -/ lemma dist_le_range_sum_of_dist_le {f : ℕ → α} (n : ℕ) {d : ℕ → ℝ} (hd : ∀ {k}, k < n → dist (f k) (f (k + 1)) ≤ d k) : dist (f 0) (f n) ≤ (finset.range n).sum d := finset.Ico.zero_bot n ▸ dist_le_Ico_sum_of_dist_le (zero_le n) (λ _ _, hd) theorem swap_dist : function.swap (@dist α _) = dist := by funext x y; exact dist_comm _ _ theorem abs_dist_sub_le (x y z : α) : abs (dist x z - dist y z) ≤ dist x y := abs_sub_le_iff.2 ⟨sub_le_iff_le_add.2 (dist_triangle _ _ _), sub_le_iff_le_add.2 (dist_triangle_left _ _ _)⟩ theorem dist_nonneg {x y : α} : 0 ≤ dist x y := have 2 * dist x y ≥ 0, from calc 2 * dist x y = dist x y + dist y x : by rw [dist_comm x y, two_mul] ... ≥ 0 : by rw ← dist_self x; apply dist_triangle, nonneg_of_mul_nonneg_left this two_pos @[simp] theorem dist_le_zero {x y : α} : dist x y ≤ 0 ↔ x = y := by simpa [le_antisymm_iff, dist_nonneg] using @dist_eq_zero _ _ x y @[simp] theorem dist_pos {x y : α} : 0 < dist x y ↔ x ≠ y := by simpa [-dist_le_zero] using not_congr (@dist_le_zero _ _ x y) @[simp] theorem abs_dist {a b : α} : abs (dist a b) = dist a b := abs_of_nonneg dist_nonneg theorem eq_of_forall_dist_le {x y : α} (h : ∀ε, ε > 0 → dist x y ≤ ε) : x = y := eq_of_dist_eq_zero (eq_of_le_of_forall_le_of_dense dist_nonneg h) /-- Distance as a nonnegative real number. -/ def nndist (a b : α) : nnreal := ⟨dist a b, dist_nonneg⟩ /--Express `nndist` in terms of `edist`-/ lemma nndist_edist (x y : α) : nndist x y = (edist x y).to_nnreal := by simp [nndist, edist_dist, nnreal.of_real, max_eq_left dist_nonneg, ennreal.of_real] /--Express `edist` in terms of `nndist`-/ lemma edist_nndist (x y : α) : edist x y = ↑(nndist x y) := by { rw [edist_dist, nndist, ennreal.of_real_eq_coe_nnreal] } /--In a metric space, the extended distance is always finite-/ lemma edist_ne_top (x y : α) : edist x y ≠ ⊤ := by rw [edist_dist x y]; apply ennreal.coe_ne_top /--In a metric space, the extended distance is always finite-/ lemma edist_lt_top {α : Type*} [metric_space α] (x y : α) : edist x y < ⊤ := ennreal.lt_top_iff_ne_top.2 (edist_ne_top x y) /--`nndist x x` vanishes-/ @[simp] lemma nndist_self (a : α) : nndist a a = 0 := (nnreal.coe_eq_zero _).1 (dist_self a) /--Express `dist` in terms of `nndist`-/ lemma dist_nndist (x y : α) : dist x y = ↑(nndist x y) := rfl /--Express `nndist` in terms of `dist`-/ lemma nndist_dist (x y : α) : nndist x y = nnreal.of_real (dist x y) := by rw [dist_nndist, nnreal.of_real_coe] /--Deduce the equality of points with the vanishing of the nonnegative distance-/ theorem eq_of_nndist_eq_zero {x y : α} : nndist x y = 0 → x = y := by simp only [nnreal.eq_iff.symm, (dist_nndist _ _).symm, imp_self, nnreal.coe_zero, dist_eq_zero] theorem nndist_comm (x y : α) : nndist x y = nndist y x := by simpa [nnreal.eq_iff.symm] using dist_comm x y /--Characterize the equality of points with the vanishing of the nonnegative distance-/ @[simp] theorem nndist_eq_zero {x y : α} : nndist x y = 0 ↔ x = y := by simp only [nnreal.eq_iff.symm, (dist_nndist _ _).symm, imp_self, nnreal.coe_zero, dist_eq_zero] @[simp] theorem zero_eq_nndist {x y : α} : 0 = nndist x y ↔ x = y := by simp only [nnreal.eq_iff.symm, (dist_nndist _ _).symm, imp_self, nnreal.coe_zero, zero_eq_dist] /--Triangle inequality for the nonnegative distance-/ theorem nndist_triangle (x y z : α) : nndist x z ≤ nndist x y + nndist y z := by simpa [nnreal.coe_le] using dist_triangle x y z theorem nndist_triangle_left (x y z : α) : nndist x y ≤ nndist z x + nndist z y := by simpa [nnreal.coe_le] using dist_triangle_left x y z theorem nndist_triangle_right (x y z : α) : nndist x y ≤ nndist x z + nndist y z := by simpa [nnreal.coe_le] using dist_triangle_right x y z /--Express `dist` in terms of `edist`-/ lemma dist_edist (x y : α) : dist x y = (edist x y).to_real := by rw [edist_dist, ennreal.to_real_of_real (dist_nonneg)] namespace metric /- instantiate metric space as a topology -/ variables {x y z : α} {ε ε₁ ε₂ : ℝ} {s : set α} /-- `ball x ε` is the set of all points `y` with `dist y x < ε` -/ def ball (x : α) (ε : ℝ) : set α := {y | dist y x < ε} @[simp] theorem mem_ball : y ∈ ball x ε ↔ dist y x < ε := iff.rfl theorem mem_ball' : y ∈ ball x ε ↔ dist x y < ε := by rw dist_comm; refl /-- `closed_ball x ε` is the set of all points `y` with `dist y x ≤ ε` -/ def closed_ball (x : α) (ε : ℝ) := {y | dist y x ≤ ε} @[simp] theorem mem_closed_ball : y ∈ closed_ball x ε ↔ dist y x ≤ ε := iff.rfl theorem ball_subset_closed_ball : ball x ε ⊆ closed_ball x ε := assume y (hy : _ < _), le_of_lt hy theorem pos_of_mem_ball (hy : y ∈ ball x ε) : ε > 0 := lt_of_le_of_lt dist_nonneg hy theorem mem_ball_self (h : ε > 0) : x ∈ ball x ε := show dist x x < ε, by rw dist_self; assumption theorem mem_closed_ball_self (h : ε ≥ 0) : x ∈ closed_ball x ε := show dist x x ≤ ε, by rw dist_self; assumption theorem mem_ball_comm : x ∈ ball y ε ↔ y ∈ ball x ε := by simp [dist_comm] theorem ball_subset_ball (h : ε₁ ≤ ε₂) : ball x ε₁ ⊆ ball x ε₂ := λ y (yx : _ < ε₁), lt_of_lt_of_le yx h theorem closed_ball_subset_closed_ball {α : Type u} [metric_space α] {ε₁ ε₂ : ℝ} {x : α} (h : ε₁ ≤ ε₂) : closed_ball x ε₁ ⊆ closed_ball x ε₂ := λ y (yx : _ ≤ ε₁), le_trans yx h theorem ball_disjoint (h : ε₁ + ε₂ ≤ dist x y) : ball x ε₁ ∩ ball y ε₂ = ∅ := eq_empty_iff_forall_not_mem.2 $ λ z ⟨h₁, h₂⟩, not_lt_of_le (dist_triangle_left x y z) (lt_of_lt_of_le (add_lt_add h₁ h₂) h) theorem ball_disjoint_same (h : ε ≤ dist x y / 2) : ball x ε ∩ ball y ε = ∅ := ball_disjoint $ by rwa [← two_mul, ← le_div_iff' two_pos] theorem ball_subset (h : dist x y ≤ ε₂ - ε₁) : ball x ε₁ ⊆ ball y ε₂ := λ z zx, by rw ← add_sub_cancel'_right ε₁ ε₂; exact lt_of_le_of_lt (dist_triangle z x y) (add_lt_add_of_lt_of_le zx h) theorem ball_half_subset (y) (h : y ∈ ball x (ε / 2)) : ball y (ε / 2) ⊆ ball x ε := ball_subset $ by rw sub_self_div_two; exact le_of_lt h theorem exists_ball_subset_ball (h : y ∈ ball x ε) : ∃ ε' > 0, ball y ε' ⊆ ball x ε := ⟨_, sub_pos.2 h, ball_subset $ by rw sub_sub_self⟩ theorem ball_eq_empty_iff_nonpos : ε ≤ 0 ↔ ball x ε = ∅ := (eq_empty_iff_forall_not_mem.trans ⟨λ h, le_of_not_gt $ λ ε0, h _ $ mem_ball_self ε0, λ ε0 y h, not_lt_of_le ε0 $ pos_of_mem_ball h⟩).symm theorem uniformity_basis_dist : (𝓤 α).has_basis (λ ε : ℝ, 0 < ε) (λ ε, {p:α×α | dist p.1 p.2 < ε}) := (metric_space.uniformity_dist α).symm ▸ has_basis_binfi_principal (λ r (hr : 0 < r) p (hp : 0 < p), ⟨min r p, lt_min hr hp, λ x (hx : dist _ _ < _), lt_of_lt_of_le hx (min_le_left r p), λ x (hx : dist _ _ < _), lt_of_lt_of_le hx (min_le_right r p)⟩) $ nonempty_Ioi /-- Given `f : β → ℝ`, if `f` sends `{i | p i}` to a set of positive numbers accumulating to zero, then `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`. For specific bases see `uniformity_basis_dist`, `uniformity_basis_dist_inv_nat_succ`, and `uniformity_basis_dist_inv_nat_pos`. -/ protected theorem mk_uniformity_basis {β : Type*} {p : β → Prop} {f : β → ℝ} (hf₀ : ∀ i, p i → 0 < f i) (hf : ∀ ⦃ε⦄, 0 < ε → ∃ i (hi : p i), f i ≤ ε) : (𝓤 α).has_basis p (λ i, {p:α×α | dist p.1 p.2 < f i}) := begin refine λ s, uniformity_basis_dist.mem_iff.trans _, split, { rintros ⟨ε, ε₀, hε⟩, obtain ⟨i, hi, H⟩ : ∃ i (hi : p i), f i ≤ ε, from hf ε₀, exact ⟨i, hi, λ x (hx : _ < _), hε $ lt_of_lt_of_le hx H⟩ }, { exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, H⟩ } end theorem uniformity_basis_dist_inv_nat_succ : (𝓤 α).has_basis (λ _, true) (λ n:ℕ, {p:α×α | dist p.1 p.2 < 1 / (↑n+1) }) := metric.mk_uniformity_basis (λ n _, div_pos zero_lt_one $ nat.cast_add_one_pos n) (λ ε ε0, (exists_nat_one_div_lt ε0).imp $ λ n hn, ⟨trivial, le_of_lt hn⟩) theorem uniformity_basis_dist_inv_nat_pos : (𝓤 α).has_basis (λ n:ℕ, 0<n) (λ n:ℕ, {p:α×α | dist p.1 p.2 < 1 / ↑n }) := metric.mk_uniformity_basis (λ n hn, div_pos zero_lt_one $ nat.cast_pos.2 hn) (λ ε ε0, let ⟨n, hn⟩ := exists_nat_one_div_lt ε0 in ⟨n+1, nat.succ_pos n, le_of_lt hn⟩) /-- Given `f : β → ℝ`, if `f` sends `{i | p i}` to a set of positive numbers accumulating to zero, then closed neighborhoods of the diagonal of sizes `{f i | p i}` form a basis of `𝓤 α`. Currently we have only one specific basis `uniformity_basis_dist_le` based on this constructor. More can be easily added if needed in the future. -/ protected theorem mk_uniformity_basis_le {β : Type*} {p : β → Prop} {f : β → ℝ} (hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x (hx : p x), f x ≤ ε) : (𝓤 α).has_basis p (λ x, {p:α×α | dist p.1 p.2 ≤ f x}) := begin refine λ s, uniformity_basis_dist.mem_iff.trans _, split, { rintros ⟨ε, ε₀, hε⟩, rcases dense ε₀ with ⟨ε', hε'⟩, rcases hf ε' hε'.1 with ⟨i, hi, H⟩, exact ⟨i, hi, λ x (hx : _ ≤ _), hε $ lt_of_le_of_lt (le_trans hx H) hε'.2⟩ }, { exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, λ x (hx : _ < _), H (le_of_lt hx)⟩ } end /-- Contant size closed neighborhoods of the diagonal form a basis of the uniformity filter. -/ theorem uniformity_basis_dist_le : (𝓤 α).has_basis (λ ε : ℝ, 0 < ε) (λ ε, {p:α×α | dist p.1 p.2 ≤ ε}) := metric.mk_uniformity_basis_le (λ _, id) (λ ε ε₀, ⟨ε, ε₀, le_refl ε⟩) theorem mem_uniformity_dist {s : set (α×α)} : s ∈ 𝓤 α ↔ (∃ε>0, ∀{a b:α}, dist a b < ε → (a, b) ∈ s) := uniformity_basis_dist.mem_uniformity_iff /-- A constant size neighborhood of the diagonal is an entourage. -/ theorem dist_mem_uniformity {ε:ℝ} (ε0 : 0 < ε) : {p:α×α | dist p.1 p.2 < ε} ∈ 𝓤 α := mem_uniformity_dist.2 ⟨ε, ε0, λ a b, id⟩ theorem uniform_continuous_iff [metric_space β] {f : α → β} : uniform_continuous f ↔ ∀ ε > 0, ∃ δ > 0, ∀{a b:α}, dist a b < δ → dist (f a) (f b) < ε := uniformity_basis_dist.uniform_continuous_iff uniformity_basis_dist theorem uniform_embedding_iff [metric_space β] {f : α → β} : uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧ ∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, dist (f a) (f b) < ε → dist a b < δ := uniform_embedding_def'.trans $ and_congr iff.rfl $ and_congr iff.rfl ⟨λ H δ δ0, let ⟨t, tu, ht⟩ := H _ (dist_mem_uniformity δ0), ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 tu in ⟨ε, ε0, λ a b h, ht _ _ (hε h)⟩, λ H s su, let ⟨δ, δ0, hδ⟩ := mem_uniformity_dist.1 su, ⟨ε, ε0, hε⟩ := H _ δ0 in ⟨_, dist_mem_uniformity ε0, λ a b h, hδ (hε h)⟩⟩ /-- A map between metric spaces is a uniform embedding if and only if the distance between `f x` and `f y` is controlled in terms of the distance between `x` and `y` and conversely. -/ theorem uniform_embedding_iff' [metric_space β] {f : α → β} : uniform_embedding f ↔ (∀ ε > 0, ∃ δ > 0, ∀ {a b : α}, dist a b < δ → dist (f a) (f b) < ε) ∧ (∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, dist (f a) (f b) < ε → dist a b < δ) := begin split, { assume h, exact ⟨uniform_continuous_iff.1 (uniform_embedding_iff.1 h).2.1, (uniform_embedding_iff.1 h).2.2⟩ }, { rintros ⟨h₁, h₂⟩, refine uniform_embedding_iff.2 ⟨_, uniform_continuous_iff.2 h₁, h₂⟩, assume x y hxy, have : dist x y ≤ 0, { refine le_of_forall_lt' (λδ δpos, _), rcases h₂ δ δpos with ⟨ε, εpos, hε⟩, have : dist (f x) (f y) < ε, by simpa [hxy], exact hε this }, simpa using this } end theorem totally_bounded_iff {s : set α} : totally_bounded s ↔ ∀ ε > 0, ∃t : set α, finite t ∧ s ⊆ ⋃y∈t, ball y ε := ⟨λ H ε ε0, H _ (dist_mem_uniformity ε0), λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 ru, ⟨t, ft, h⟩ := H ε ε0 in ⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩ /-- A metric space space is totally bounded if one can reconstruct up to any ε>0 any element of the space from finitely many data. -/ lemma totally_bounded_of_finite_discretization {α : Type u} [metric_space α] {s : set α} (H : ∀ε > (0 : ℝ), ∃ (β : Type u) [fintype β] (F : s → β), ∀x y, F x = F y → dist (x:α) y < ε) : totally_bounded s := begin cases s.eq_empty_or_nonempty with hs hs, { rw hs, exact totally_bounded_empty }, rcases hs with ⟨x0, hx0⟩, haveI : inhabited s := ⟨⟨x0, hx0⟩⟩, refine totally_bounded_iff.2 (λ ε ε0, _), rcases H ε ε0 with ⟨β, fβ, F, hF⟩, let Finv := function.inv_fun F, refine ⟨range (subtype.val ∘ Finv), finite_range _, λ x xs, _⟩, let x' := Finv (F ⟨x, xs⟩), have : F x' = F ⟨x, xs⟩ := function.inv_fun_eq ⟨⟨x, xs⟩, rfl⟩, simp only [set.mem_Union, set.mem_range], exact ⟨_, ⟨F ⟨x, xs⟩, rfl⟩, hF _ _ this.symm⟩ end protected lemma cauchy_iff {f : filter α} : cauchy f ↔ f ≠ ⊥ ∧ ∀ ε > 0, ∃ t ∈ f, ∀ x y ∈ t, dist x y < ε := uniformity_basis_dist.cauchy_iff theorem nhds_basis_ball : (𝓝 x).has_basis (λ ε:ℝ, 0 < ε) (ball x) := nhds_basis_uniformity uniformity_basis_dist theorem mem_nhds_iff : s ∈ 𝓝 x ↔ ∃ε>0, ball x ε ⊆ s := nhds_basis_ball.mem_iff theorem nhds_basis_closed_ball : (𝓝 x).has_basis (λ ε:ℝ, 0 < ε) (closed_ball x) := nhds_basis_uniformity uniformity_basis_dist_le theorem nhds_basis_ball_inv_nat_succ : (𝓝 x).has_basis (λ _, true) (λ n:ℕ, ball x (1 / (↑n+1))) := nhds_basis_uniformity uniformity_basis_dist_inv_nat_succ theorem nhds_basis_ball_inv_nat_pos : (𝓝 x).has_basis (λ n, 0<n) (λ n:ℕ, ball x (1 / ↑n)) := nhds_basis_uniformity uniformity_basis_dist_inv_nat_pos theorem is_open_iff : is_open s ↔ ∀x∈s, ∃ε>0, ball x ε ⊆ s := by simp only [is_open_iff_nhds, mem_nhds_iff, le_principal_iff] theorem is_open_ball : is_open (ball x ε) := is_open_iff.2 $ λ y, exists_ball_subset_ball theorem ball_mem_nhds (x : α) {ε : ℝ} (ε0 : 0 < ε) : ball x ε ∈ 𝓝 x := mem_nhds_sets is_open_ball (mem_ball_self ε0) theorem nhds_within_basis_ball {s : set α} : (nhds_within x s).has_basis (λ ε:ℝ, 0 < ε) (λ ε, ball x ε ∩ s) := nhds_within_has_basis nhds_basis_ball s @[nolint ge_or_gt] -- see Note [nolint_ge] theorem mem_nhds_within_iff {t : set α} : s ∈ nhds_within x t ↔ ∃ε>0, ball x ε ∩ t ⊆ s := nhds_within_basis_ball.mem_iff @[nolint ge_or_gt] -- see Note [nolint_ge] theorem tendsto_nhds_within_nhds_within [metric_space β] {t : set β} {f : α → β} {a b} : tendsto f (nhds_within a s) (nhds_within b t) ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → dist x a < δ → f x ∈ t ∧ dist (f x) b < ε := (nhds_within_basis_ball.tendsto_iff nhds_within_basis_ball).trans $ by simp only [inter_comm, mem_inter_iff, and_imp, mem_ball] @[nolint ge_or_gt] -- see Note [nolint_ge] theorem tendsto_nhds_within_nhds [metric_space β] {f : α → β} {a b} : tendsto f (nhds_within a s) (𝓝 b) ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → dist x a < δ → dist (f x) b < ε := by { rw [← nhds_within_univ, tendsto_nhds_within_nhds_within], simp only [mem_univ, true_and] } @[nolint ge_or_gt] -- see Note [nolint_ge] theorem tendsto_nhds_nhds [metric_space β] {f : α → β} {a b} : tendsto f (𝓝 a) (𝓝 b) ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, dist x a < δ → dist (f x) b < ε := nhds_basis_ball.tendsto_iff nhds_basis_ball @[nolint ge_or_gt] -- see Note [nolint_ge] theorem continuous_at_iff [metric_space β] {f : α → β} {a : α} : continuous_at f a ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, dist x a < δ → dist (f x) (f a) < ε := by rw [continuous_at, tendsto_nhds_nhds] theorem continuous_iff [metric_space β] {f : α → β} : continuous f ↔ ∀b (ε > 0), ∃ δ > 0, ∀a, dist a b < δ → dist (f a) (f b) < ε := continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds_nhds theorem tendsto_nhds {f : filter β} {u : β → α} {a : α} : tendsto u f (𝓝 a) ↔ ∀ ε > 0, ∀ᶠ x in f, dist (u x) a < ε := nhds_basis_ball.tendsto_right_iff theorem continuous_iff' [topological_space β] {f : β → α} : continuous f ↔ ∀a (ε > 0), ∀ᶠ x in 𝓝 a, dist (f x) (f a) < ε := continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds theorem tendsto_at_top [nonempty β] [semilattice_sup β] {u : β → α} {a : α} : tendsto u at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n≥N, dist (u n) a < ε := (at_top_basis.tendsto_iff nhds_basis_ball).trans $ by { simp only [exists_prop, true_and], refl } end metric open metric @[priority 100] -- see Note [lower instance priority] instance metric_space.to_separated : separated α := separated_def.2 $ λ x y h, eq_of_forall_dist_le $ λ ε ε0, le_of_lt (h _ (dist_mem_uniformity ε0)) /-Instantiate a metric space as an emetric space. Before we can state the instance, we need to show that the uniform structure coming from the edistance and the distance coincide. -/ /-- Expressing the uniformity in terms of `edist` -/ protected lemma metric.uniformity_basis_edist : (𝓤 α).has_basis (λ ε:ennreal, 0 < ε) (λ ε, {p | edist p.1 p.2 < ε}) := begin intro t, refine mem_uniformity_dist.trans ⟨_, _⟩; rintro ⟨ε, ε0, Hε⟩, { use [ennreal.of_real ε, ennreal.of_real_pos.2 ε0], rintros ⟨a, b⟩, simp only [edist_dist, ennreal.of_real_lt_of_real_iff ε0], exact Hε }, { rcases ennreal.lt_iff_exists_real_btwn.1 ε0 with ⟨ε', _, ε0', hε⟩, rw [ennreal.of_real_pos] at ε0', refine ⟨ε', ε0', λ a b h, Hε (lt_trans _ hε)⟩, rwa [edist_dist, ennreal.of_real_lt_of_real_iff ε0'] } end @[nolint ge_or_gt] -- see Note [nolint_ge] theorem metric.uniformity_edist : 𝓤 α = (⨅ ε>0, principal {p:α×α | edist p.1 p.2 < ε}) := metric.uniformity_basis_edist.eq_binfi /-- A metric space induces an emetric space -/ @[priority 100] -- see Note [lower instance priority] instance metric_space.to_emetric_space : emetric_space α := { edist := edist, edist_self := by simp [edist_dist], eq_of_edist_eq_zero := assume x y h, by simpa [edist_dist] using h, edist_comm := by simp only [edist_dist, dist_comm]; simp, edist_triangle := assume x y z, begin simp only [edist_dist, (ennreal.of_real_add _ _).symm, dist_nonneg], rw ennreal.of_real_le_of_real_iff _, { exact dist_triangle _ _ _ }, { simpa using add_le_add (dist_nonneg : 0 ≤ dist x y) dist_nonneg } end, uniformity_edist := metric.uniformity_edist, ..‹metric_space α› } /-- Balls defined using the distance or the edistance coincide -/ lemma metric.emetric_ball {x : α} {ε : ℝ} : emetric.ball x (ennreal.of_real ε) = ball x ε := begin ext y, simp only [emetric.mem_ball, mem_ball, edist_dist], exact ennreal.of_real_lt_of_real_iff_of_nonneg dist_nonneg end /-- Closed balls defined using the distance or the edistance coincide -/ lemma metric.emetric_closed_ball {x : α} {ε : ℝ} (h : 0 ≤ ε) : emetric.closed_ball x (ennreal.of_real ε) = closed_ball x ε := by ext y; simp [edist_dist]; rw ennreal.of_real_le_of_real_iff h def metric_space.replace_uniformity {α} [U : uniform_space α] (m : metric_space α) (H : @uniformity _ U = @uniformity _ (metric_space.to_uniform_space α)) : metric_space α := { dist := @dist _ m.to_has_dist, dist_self := dist_self, eq_of_dist_eq_zero := @eq_of_dist_eq_zero _ _, dist_comm := dist_comm, dist_triangle := dist_triangle, edist := edist, edist_dist := edist_dist, to_uniform_space := U, uniformity_dist := H.trans (metric_space.uniformity_dist α) } /-- One gets a metric space from an emetric space if the edistance is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the uniformity are defeq in the metric space and the emetric space. In this definition, the distance is given separately, to be able to prescribe some expression which is not defeq to the push-forward of the edistance to reals. -/ def emetric_space.to_metric_space_of_dist {α : Type u} [e : emetric_space α] (dist : α → α → ℝ) (edist_ne_top : ∀x y: α, edist x y ≠ ⊤) (h : ∀x y, dist x y = ennreal.to_real (edist x y)) : metric_space α := let m : metric_space α := { dist := dist, eq_of_dist_eq_zero := λx y hxy, by simpa [h, ennreal.to_real_eq_zero_iff, edist_ne_top x y] using hxy, dist_self := λx, by simp [h], dist_comm := λx y, by simp [h, emetric_space.edist_comm], dist_triangle := λx y z, begin simp only [h], rw [← ennreal.to_real_add (edist_ne_top _ _) (edist_ne_top _ _), ennreal.to_real_le_to_real (edist_ne_top _ _)], { exact edist_triangle _ _ _ }, { simp [ennreal.add_eq_top, edist_ne_top] } end, edist := λx y, edist x y, edist_dist := λx y, by simp [h, ennreal.of_real_to_real, edist_ne_top] } in m.replace_uniformity $ by { rw [uniformity_edist, metric.uniformity_edist], refl } /-- One gets a metric space from an emetric space if the edistance is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the uniformity are defeq in the metric space and the emetric space. -/ def emetric_space.to_metric_space {α : Type u} [e : emetric_space α] (h : ∀x y: α, edist x y ≠ ⊤) : metric_space α := emetric_space.to_metric_space_of_dist (λx y, ennreal.to_real (edist x y)) h (λx y, rfl) /-- A very useful criterion to show that a space is complete is to show that all sequences which satisfy a bound of the form `dist (u n) (u m) < B N` for all `n m ≥ N` are converging. This is often applied for `B N = 2^{-N}`, i.e., with a very fast convergence to `0`, which makes it possible to use arguments of converging series, while this is impossible to do in general for arbitrary Cauchy sequences. -/ theorem metric.complete_of_convergent_controlled_sequences (B : ℕ → real) (hB : ∀n, 0 < B n) (H : ∀u : ℕ → α, (∀N n m : ℕ, N ≤ n → N ≤ m → dist (u n) (u m) < B N) → ∃x, tendsto u at_top (𝓝 x)) : complete_space α := begin -- this follows from the same criterion in emetric spaces. We just need to translate -- the convergence assumption from `dist` to `edist` apply emetric.complete_of_convergent_controlled_sequences (λn, ennreal.of_real (B n)), { simp [hB] }, { assume u Hu, apply H, assume N n m hn hm, rw [← ennreal.of_real_lt_of_real_iff (hB N), ← edist_dist], exact Hu N n m hn hm } end theorem metric.complete_of_cauchy_seq_tendsto : (∀ u : ℕ → α, cauchy_seq u → ∃a, tendsto u at_top (𝓝 a)) → complete_space α := emetric.complete_of_cauchy_seq_tendsto section real /-- Instantiate the reals as a metric space. -/ instance real.metric_space : metric_space ℝ := { dist := λx y, abs (x - y), dist_self := by simp [abs_zero], eq_of_dist_eq_zero := by simp [sub_eq_zero], dist_comm := assume x y, abs_sub _ _, dist_triangle := assume x y z, abs_sub_le _ _ _ } theorem real.dist_eq (x y : ℝ) : dist x y = abs (x - y) := rfl theorem real.dist_0_eq_abs (x : ℝ) : dist x 0 = abs x := by simp [real.dist_eq] instance : order_topology ℝ := order_topology_of_nhds_abs $ λ x, begin simp only [show ∀ r, {b : ℝ | abs (x - b) < r} = ball x r, by simp [-sub_eq_add_neg, abs_sub, ball, real.dist_eq]], apply le_antisymm, { simp [le_infi_iff], exact λ ε ε0, mem_nhds_sets (is_open_ball) (mem_ball_self ε0) }, { intros s h, rcases mem_nhds_iff.1 h with ⟨ε, ε0, ss⟩, exact mem_infi_sets _ (mem_infi_sets ε0 (mem_principal_sets.2 ss)) }, end lemma closed_ball_Icc {x r : ℝ} : closed_ball x r = Icc (x-r) (x+r) := by ext y; rw [mem_closed_ball, dist_comm, real.dist_eq, abs_sub_le_iff, mem_Icc, ← sub_le_iff_le_add', sub_le] /-- Special case of the sandwich theorem; see `tendsto_of_tendsto_of_tendsto_of_le_of_le` and `tendsto_of_tendsto_of_tendsto_of_le_of_le'` for the general case. -/ lemma squeeze_zero {α} {f g : α → ℝ} {t₀ : filter α} (hf : ∀t, 0 ≤ f t) (hft : ∀t, f t ≤ g t) (g0 : tendsto g t₀ (𝓝 0)) : tendsto f t₀ (𝓝 0) := tendsto_of_tendsto_of_tendsto_of_le_of_le tendsto_const_nhds g0 hf hft theorem metric.uniformity_eq_comap_nhds_zero : 𝓤 α = comap (λp:α×α, dist p.1 p.2) (𝓝 (0 : ℝ)) := by { ext s, simp [mem_uniformity_dist, (nhds_basis_ball.comap _).mem_iff, subset_def, real.dist_0_eq_abs] } lemma cauchy_seq_iff_tendsto_dist_at_top_0 [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ tendsto (λ (n : β × β), dist (u n.1) (u n.2)) at_top (𝓝 0) := by rw [cauchy_seq_iff_tendsto, metric.uniformity_eq_comap_nhds_zero, tendsto_comap_iff, prod.map_def] end real section cauchy_seq variables [nonempty β] [semilattice_sup β] /-- In a metric space, Cauchy sequences are characterized by the fact that, eventually, the distance between its elements is arbitrarily small -/ theorem metric.cauchy_seq_iff {u : β → α} : cauchy_seq u ↔ ∀ε>0, ∃N, ∀m n≥N, dist (u m) (u n) < ε := uniformity_basis_dist.cauchy_seq_iff /-- A variation around the metric characterization of Cauchy sequences -/ theorem metric.cauchy_seq_iff' {u : β → α} : cauchy_seq u ↔ ∀ε>0, ∃N, ∀n≥N, dist (u n) (u N) < ε := uniformity_basis_dist.cauchy_seq_iff' /-- If the distance between `s n` and `s m`, `n, m ≥ N` is bounded above by `b N` and `b` converges to zero, then `s` is a Cauchy sequence. -/ lemma cauchy_seq_of_le_tendsto_0 {s : β → α} (b : β → ℝ) (h : ∀ n m N : β, N ≤ n → N ≤ m → dist (s n) (s m) ≤ b N) (h₀ : tendsto b at_top (nhds 0)) : cauchy_seq s := metric.cauchy_seq_iff.2 $ λ ε ε0, (metric.tendsto_at_top.1 h₀ ε ε0).imp $ λ N hN m n hm hn, calc dist (s m) (s n) ≤ b N : h m n N hm hn ... ≤ abs (b N) : le_abs_self _ ... = dist (b N) 0 : by rw real.dist_0_eq_abs; refl ... < ε : (hN _ (le_refl N)) /-- A Cauchy sequence on the natural numbers is bounded. -/ theorem cauchy_seq_bdd {u : ℕ → α} (hu : cauchy_seq u) : ∃ R > 0, ∀ m n, dist (u m) (u n) < R := begin rcases metric.cauchy_seq_iff'.1 hu 1 zero_lt_one with ⟨N, hN⟩, suffices : ∃ R > 0, ∀ n, dist (u n) (u N) < R, { rcases this with ⟨R, R0, H⟩, exact ⟨_, add_pos R0 R0, λ m n, lt_of_le_of_lt (dist_triangle_right _ _ _) (add_lt_add (H m) (H n))⟩ }, let R := finset.sup (finset.range N) (λ n, nndist (u n) (u N)), refine ⟨↑R + 1, add_pos_of_nonneg_of_pos R.2 zero_lt_one, λ n, _⟩, cases le_or_lt N n, { exact lt_of_lt_of_le (hN _ h) (le_add_of_nonneg_left R.2) }, { have : _ ≤ R := finset.le_sup (finset.mem_range.2 h), exact lt_of_le_of_lt this (lt_add_of_pos_right _ zero_lt_one) } end /-- Yet another metric characterization of Cauchy sequences on integers. This one is often the most efficient. -/ lemma cauchy_seq_iff_le_tendsto_0 {s : ℕ → α} : cauchy_seq s ↔ ∃ b : ℕ → ℝ, (∀ n, 0 ≤ b n) ∧ (∀ n m N : ℕ, N ≤ n → N ≤ m → dist (s n) (s m) ≤ b N) ∧ tendsto b at_top (𝓝 0) := ⟨λ hs, begin /- `s` is a Cauchy sequence. The sequence `b` will be constructed by taking the supremum of the distances between `s n` and `s m` for `n m ≥ N`. First, we prove that all these distances are bounded, as otherwise the Sup would not make sense. -/ let S := λ N, (λ(p : ℕ × ℕ), dist (s p.1) (s p.2)) '' {p | p.1 ≥ N ∧ p.2 ≥ N}, have hS : ∀ N, ∃ x, ∀ y ∈ S N, y ≤ x, { rcases cauchy_seq_bdd hs with ⟨R, R0, hR⟩, refine λ N, ⟨R, _⟩, rintro _ ⟨⟨m, n⟩, _, rfl⟩, exact le_of_lt (hR m n) }, have bdd : bdd_above (range (λ(p : ℕ × ℕ), dist (s p.1) (s p.2))), { rcases cauchy_seq_bdd hs with ⟨R, R0, hR⟩, use R, rintro _ ⟨⟨m, n⟩, rfl⟩, exact le_of_lt (hR m n) }, -- Prove that it bounds the distances of points in the Cauchy sequence have ub : ∀ m n N, N ≤ m → N ≤ n → dist (s m) (s n) ≤ real.Sup (S N) := λ m n N hm hn, real.le_Sup _ (hS N) ⟨⟨_, _⟩, ⟨hm, hn⟩, rfl⟩, have S0m : ∀ n, (0:ℝ) ∈ S n := λ n, ⟨⟨n, n⟩, ⟨le_refl _, le_refl _⟩, dist_self _⟩, have S0 := λ n, real.le_Sup _ (hS n) (S0m n), -- Prove that it tends to `0`, by using the Cauchy property of `s` refine ⟨λ N, real.Sup (S N), S0, ub, metric.tendsto_at_top.2 (λ ε ε0, _)⟩, refine (metric.cauchy_seq_iff.1 hs (ε/2) (half_pos ε0)).imp (λ N hN n hn, _), rw [real.dist_0_eq_abs, abs_of_nonneg (S0 n)], refine lt_of_le_of_lt (real.Sup_le_ub _ ⟨_, S0m _⟩ _) (half_lt_self ε0), rintro _ ⟨⟨m', n'⟩, ⟨hm', hn'⟩, rfl⟩, exact le_of_lt (hN _ _ (le_trans hn hm') (le_trans hn hn')) end, λ ⟨b, _, b_bound, b_lim⟩, cauchy_seq_of_le_tendsto_0 b b_bound b_lim⟩ end cauchy_seq def metric_space.induced {α β} (f : α → β) (hf : function.injective f) (m : metric_space β) : metric_space α := { dist := λ x y, dist (f x) (f y), dist_self := λ x, dist_self _, eq_of_dist_eq_zero := λ x y h, hf (dist_eq_zero.1 h), dist_comm := λ x y, dist_comm _ _, dist_triangle := λ x y z, dist_triangle _ _ _, edist := λ x y, edist (f x) (f y), edist_dist := λ x y, edist_dist _ _, to_uniform_space := uniform_space.comap f m.to_uniform_space, uniformity_dist := begin apply @uniformity_dist_of_mem_uniformity _ _ _ _ _ (λ x y, dist (f x) (f y)), refine λ s, mem_comap_sets.trans _, split; intro H, { rcases H with ⟨r, ru, rs⟩, rcases mem_uniformity_dist.1 ru with ⟨ε, ε0, hε⟩, refine ⟨ε, ε0, λ a b h, rs (hε _)⟩, exact h }, { rcases H with ⟨ε, ε0, hε⟩, exact ⟨_, dist_mem_uniformity ε0, λ ⟨a, b⟩, hε⟩ } end } instance subtype.metric_space {α : Type*} {p : α → Prop} [t : metric_space α] : metric_space (subtype p) := metric_space.induced subtype.val (λ x y, subtype.eq) t theorem subtype.dist_eq {p : α → Prop} (x y : subtype p) : dist x y = dist x.1 y.1 := rfl section nnreal instance : metric_space nnreal := by unfold nnreal; apply_instance lemma nnreal.dist_eq (a b : nnreal) : dist a b = abs ((a:ℝ) - b) := rfl lemma nnreal.nndist_eq (a b : nnreal) : nndist a b = max (a - b) (b - a) := begin wlog h : a ≤ b, { apply nnreal.coe_eq.1, rw [nnreal.sub_eq_zero h, max_eq_right (zero_le $ b - a), ← dist_nndist, nnreal.dist_eq, nnreal.coe_sub h, abs, neg_sub], apply max_eq_right, linarith [nnreal.coe_le.2 h] }, rwa [nndist_comm, max_comm] end end nnreal section prod instance prod.metric_space_max [metric_space β] : metric_space (α × β) := { dist := λ x y, max (dist x.1 y.1) (dist x.2 y.2), dist_self := λ x, by simp, eq_of_dist_eq_zero := λ x y h, begin cases max_le_iff.1 (le_of_eq h) with h₁ h₂, exact prod.ext_iff.2 ⟨dist_le_zero.1 h₁, dist_le_zero.1 h₂⟩ end, dist_comm := λ x y, by simp [dist_comm], dist_triangle := λ x y z, max_le (le_trans (dist_triangle _ _ _) (add_le_add (le_max_left _ _) (le_max_left _ _))) (le_trans (dist_triangle _ _ _) (add_le_add (le_max_right _ _) (le_max_right _ _))), edist := λ x y, max (edist x.1 y.1) (edist x.2 y.2), edist_dist := assume x y, begin have : monotone ennreal.of_real := assume x y h, ennreal.of_real_le_of_real h, rw [edist_dist, edist_dist, this.map_max.symm] end, uniformity_dist := begin refine uniformity_prod.trans _, simp only [uniformity_basis_dist.eq_binfi, comap_infi], rw ← infi_inf_eq, congr, funext, rw ← infi_inf_eq, congr, funext, simp [inf_principal, ext_iff, max_lt_iff] end, to_uniform_space := prod.uniform_space } lemma prod.dist_eq [metric_space β] {x y : α × β} : dist x y = max (dist x.1 y.1) (dist x.2 y.2) := rfl end prod theorem uniform_continuous_dist' : uniform_continuous (λp:α×α, dist p.1 p.2) := metric.uniform_continuous_iff.2 (λ ε ε0, ⟨ε/2, half_pos ε0, begin suffices, { intros p q h, cases p with p₁ p₂, cases q with q₁ q₂, cases max_lt_iff.1 h with h₁ h₂, clear h, dsimp at h₁ h₂ ⊢, rw real.dist_eq, refine abs_sub_lt_iff.2 ⟨_, _⟩, { revert p₁ p₂ q₁ q₂ h₁ h₂, exact this }, { apply this; rwa dist_comm } }, intros p₁ p₂ q₁ q₂ h₁ h₂, have := add_lt_add (abs_sub_lt_iff.1 (lt_of_le_of_lt (abs_dist_sub_le p₁ q₁ p₂) h₁)).1 (abs_sub_lt_iff.1 (lt_of_le_of_lt (abs_dist_sub_le p₂ q₂ q₁) h₂)).1, rwa [add_halves, dist_comm p₂, sub_add_sub_cancel, dist_comm q₂] at this end⟩) theorem uniform_continuous_dist [uniform_space β] {f g : β → α} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (λb, dist (f b) (g b)) := uniform_continuous_dist'.comp (hf.prod_mk hg) theorem continuous_dist' : continuous (λp:α×α, dist p.1 p.2) := uniform_continuous_dist'.continuous theorem continuous_dist [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : continuous (λb, dist (f b) (g b)) := continuous_dist'.comp (hf.prod_mk hg) theorem tendsto_dist {f g : β → α} {x : filter β} {a b : α} (hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) : tendsto (λx, dist (f x) (g x)) x (𝓝 (dist a b)) := have tendsto (λp:α×α, dist p.1 p.2) (𝓝 (a, b)) (𝓝 (dist a b)), from continuous_iff_continuous_at.mp continuous_dist' (a, b), tendsto.comp (by rw [nhds_prod_eq] at this; exact this) (hf.prod_mk hg) lemma nhds_comap_dist (a : α) : (𝓝 (0 : ℝ)).comap (λa', dist a' a) = 𝓝 a := by simp only [@nhds_eq_comap_uniformity α, metric.uniformity_eq_comap_nhds_zero, comap_comap_comp, (∘), dist_comm] lemma tendsto_iff_dist_tendsto_zero {f : β → α} {x : filter β} {a : α} : (tendsto f x (𝓝 a)) ↔ (tendsto (λb, dist (f b) a) x (𝓝 0)) := by rw [← nhds_comap_dist a, tendsto_comap_iff] lemma uniform_continuous_nndist' : uniform_continuous (λp:α×α, nndist p.1 p.2) := uniform_continuous_subtype_mk uniform_continuous_dist' _ lemma continuous_nndist' : continuous (λp:α×α, nndist p.1 p.2) := uniform_continuous_nndist'.continuous lemma continuous_nndist [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : continuous (λb, nndist (f b) (g b)) := continuous_nndist'.comp (hf.prod_mk hg) lemma tendsto_nndist' (a b :α) : tendsto (λp:α×α, nndist p.1 p.2) (filter.prod (𝓝 a) (𝓝 b)) (𝓝 (nndist a b)) := by rw [← nhds_prod_eq]; exact continuous_iff_continuous_at.1 continuous_nndist' _ namespace metric variables {x y z : α} {ε ε₁ ε₂ : ℝ} {s : set α} theorem is_closed_ball : is_closed (closed_ball x ε) := is_closed_le (continuous_dist continuous_id continuous_const) continuous_const /-- ε-characterization of the closure in metric spaces-/ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem mem_closure_iff {α : Type u} [metric_space α] {s : set α} {a : α} : a ∈ closure s ↔ ∀ε>0, ∃b ∈ s, dist a b < ε := (mem_closure_iff_nhds_basis nhds_basis_ball).trans $ by simp only [mem_ball, dist_comm] lemma mem_closure_range_iff {α : Type u} [metric_space α] {e : β → α} {a : α} : a ∈ closure (range e) ↔ ∀ε>0, ∃ k : β, dist a (e k) < ε := by simp only [mem_closure_iff, exists_range_iff] lemma mem_closure_range_iff_nat {α : Type u} [metric_space α] {e : β → α} {a : α} : a ∈ closure (range e) ↔ ∀n : ℕ, ∃ k : β, dist a (e k) < 1 / ((n : ℝ) + 1) := (mem_closure_iff_nhds_basis nhds_basis_ball_inv_nat_succ).trans $ by simp only [mem_ball, dist_comm, exists_range_iff, forall_const] theorem mem_of_closed' {α : Type u} [metric_space α] {s : set α} (hs : is_closed s) {a : α} : a ∈ s ↔ ∀ε>0, ∃b ∈ s, dist a b < ε := by simpa only [closure_eq_of_is_closed hs] using @mem_closure_iff _ _ s a end metric section pi open finset lattice variables {π : β → Type*} [fintype β] [∀b, metric_space (π b)] /-- A finite product of metric spaces is a metric space, with the sup distance. -/ instance metric_space_pi : metric_space (Πb, π b) := begin /- we construct the instance from the emetric space instance to avoid checking again that the uniformity is the same as the product uniformity, but we register nevertheless a nice formula for the distance -/ refine emetric_space.to_metric_space_of_dist (λf g, ((sup univ (λb, nndist (f b) (g b)) : nnreal) : ℝ)) _ _, show ∀ (x y : Π (b : β), π b), edist x y ≠ ⊤, { assume x y, rw ← lt_top_iff_ne_top, have : (⊥ : ennreal) < ⊤ := ennreal.coe_lt_top, simp [edist, this], assume b, rw lt_top_iff_ne_top, exact edist_ne_top (x b) (y b) }, show ∀ (x y : Π (b : β), π b), ↑(sup univ (λ (b : β), nndist (x b) (y b))) = ennreal.to_real (sup univ (λ (b : β), edist (x b) (y b))), { assume x y, have : sup univ (λ (b : β), edist (x b) (y b)) = ↑(sup univ (λ (b : β), nndist (x b) (y b))), { simp [edist_nndist], refine eq.symm (comp_sup_eq_sup_comp _ _ _), exact (assume x y h, ennreal.coe_le_coe.2 h), refl }, rw this, refl } end lemma dist_pi_def (f g : Πb, π b) : dist f g = (sup univ (λb, nndist (f b) (g b)) : nnreal) := rfl lemma dist_pi_lt_iff {f g : Πb, π b} {r : ℝ} (hr : 0 < r) : dist f g < r ↔ ∀b, dist (f b) (g b) < r := begin lift r to nnreal using le_of_lt hr, rw_mod_cast [dist_pi_def, finset.sup_lt_iff], { simp [nndist], refl }, { exact hr } end lemma dist_pi_le_iff {f g : Πb, π b} {r : ℝ} (hr : 0 ≤ r) : dist f g ≤ r ↔ ∀b, dist (f b) (g b) ≤ r := begin lift r to nnreal using hr, rw_mod_cast [dist_pi_def, finset.sup_le_iff], simp [nndist], refl end /-- An open ball in a product space is a product of open balls. The assumption `0 < r` is necessary for the case of the empty product. -/ lemma ball_pi (x : Πb, π b) {r : ℝ} (hr : 0 < r) : ball x r = { y | ∀b, y b ∈ ball (x b) r } := by { ext p, simp [dist_pi_lt_iff hr] } /-- A closed ball in a product space is a product of closed balls. The assumption `0 ≤ r` is necessary for the case of the empty product. -/ lemma closed_ball_pi (x : Πb, π b) {r : ℝ} (hr : 0 ≤ r) : closed_ball x r = { y | ∀b, y b ∈ closed_ball (x b) r } := by { ext p, simp [dist_pi_le_iff hr] } end pi section compact /-- Any compact set in a metric space can be covered by finitely many balls of a given positive radius -/ lemma finite_cover_balls_of_compact {α : Type u} [metric_space α] {s : set α} (hs : compact s) {e : ℝ} (he : 0 < e) : ∃t ⊆ s, finite t ∧ s ⊆ ⋃x∈t, ball x e := begin apply hs.elim_finite_subcover_image, { simp [is_open_ball] }, { intros x xs, simp, exact ⟨x, ⟨xs, by simpa⟩⟩ } end alias finite_cover_balls_of_compact ← compact.finite_cover_balls end compact section proper_space open metric /-- A metric space is proper if all closed balls are compact. -/ class proper_space (α : Type u) [metric_space α] : Prop := (compact_ball : ∀x:α, ∀r, compact (closed_ball x r)) /-- If all closed balls of large enough radius are compact, then the space is proper. Especially useful when the lower bound for the radius is 0. -/ lemma proper_space_of_compact_closed_ball_of_le (R : ℝ) (h : ∀x:α, ∀r, R ≤ r → compact (closed_ball x r)) : proper_space α := ⟨begin assume x r, by_cases hr : R ≤ r, { exact h x r hr }, { have : closed_ball x r = closed_ball x R ∩ closed_ball x r, { symmetry, apply inter_eq_self_of_subset_right, exact closed_ball_subset_closed_ball (le_of_lt (not_le.1 hr)) }, rw this, exact (h x R (le_refl _)).inter_right is_closed_ball } end⟩ /- A compact metric space is proper -/ @[priority 100] -- see Note [lower instance priority] instance proper_of_compact [compact_space α] : proper_space α := ⟨assume x r, compact_of_is_closed_subset compact_univ is_closed_ball (subset_univ _)⟩ /-- A proper space is locally compact -/ @[priority 100] -- see Note [lower instance priority] instance locally_compact_of_proper [proper_space α] : locally_compact_space α := begin apply locally_compact_of_compact_nhds, intros x, existsi closed_ball x 1, split, { apply mem_nhds_iff.2, existsi (1 : ℝ), simp, exact ⟨zero_lt_one, ball_subset_closed_ball⟩ }, { apply proper_space.compact_ball } end /-- A proper space is complete -/ @[priority 100] -- see Note [lower instance priority] instance complete_of_proper [proper_space α] : complete_space α := ⟨begin intros f hf, /- We want to show that the Cauchy filter `f` is converging. It suffices to find a closed ball (therefore compact by properness) where it is nontrivial. -/ have A : ∃ t ∈ f, ∀ x y ∈ t, dist x y < 1 := (metric.cauchy_iff.1 hf).2 1 zero_lt_one, rcases A with ⟨t, ⟨t_fset, ht⟩⟩, rcases nonempty_of_mem_sets hf.1 t_fset with ⟨x, xt⟩, have : t ⊆ closed_ball x 1 := by intros y yt; simp [dist_comm]; apply le_of_lt (ht x y xt yt), have : closed_ball x 1 ∈ f := f.sets_of_superset t_fset this, rcases (compact_iff_totally_bounded_complete.1 (proper_space.compact_ball x 1)).2 f hf (le_principal_iff.2 this) with ⟨y, _, hy⟩, exact ⟨y, hy⟩ end⟩ /-- A proper metric space is separable, and therefore second countable. Indeed, any ball is compact, and therefore admits a countable dense subset. Taking a countable union over the balls centered at a fixed point and with integer radius, one obtains a countable set which is dense in the whole space. -/ @[priority 100] -- see Note [lower instance priority] instance second_countable_of_proper [proper_space α] : second_countable_topology α := begin /- We show that the space admits a countable dense subset. The case where the space is empty is special, and trivial. -/ have A : (univ : set α) = ∅ → ∃(s : set α), countable s ∧ closure s = (univ : set α) := assume H, ⟨∅, ⟨by simp, by simp; exact H.symm⟩⟩, have B : (univ : set α).nonempty → ∃(s : set α), countable s ∧ closure s = (univ : set α) := begin /- When the space is not empty, we take a point `x` in the space, and then a countable set `T r` which is dense in the closed ball `closed_ball x r` for each `r`. Then the set `t = ⋃ T n` (where the union is over all integers `n`) is countable, as a countable union of countable sets, and dense in the space by construction. -/ rintros ⟨x, x_univ⟩, choose T a using show ∀ (r:ℝ), ∃ t ⊆ closed_ball x r, (countable (t : set α) ∧ closed_ball x r = closure t), from assume r, emetric.countable_closure_of_compact (proper_space.compact_ball _ _), let t := (⋃n:ℕ, T (n : ℝ)), have T₁ : countable t := by finish [countable_Union], have T₂ : closure t ⊆ univ := by simp, have T₃ : univ ⊆ closure t := begin intros y y_univ, rcases exists_nat_gt (dist y x) with ⟨n, n_large⟩, have h : y ∈ closed_ball x (n : ℝ) := by simp; apply le_of_lt n_large, have h' : closed_ball x (n : ℝ) = closure (T (n : ℝ)) := by finish, have : y ∈ closure (T (n : ℝ)) := by rwa h' at h, show y ∈ closure t, from mem_of_mem_of_subset this (by apply closure_mono; apply subset_Union (λ(n:ℕ), T (n:ℝ))), end, exact ⟨t, ⟨T₁, subset.antisymm T₂ T₃⟩⟩ end, haveI : separable_space α := ⟨(eq_empty_or_nonempty univ).elim A B⟩, apply emetric.second_countable_of_separable, end /-- A finite product of proper spaces is proper. -/ instance pi_proper_space {π : β → Type*} [fintype β] [∀b, metric_space (π b)] [h : ∀b, proper_space (π b)] : proper_space (Πb, π b) := begin refine proper_space_of_compact_closed_ball_of_le 0 (λx r hr, _), rw closed_ball_pi _ hr, apply compact_pi_infinite (λb, _), apply (h b).compact_ball end end proper_space namespace metric section second_countable open topological_space /-- A metric space is second countable if, for every ε > 0, there is a countable set which is ε-dense. -/ lemma second_countable_of_almost_dense_set (H : ∀ε > (0 : ℝ), ∃ s : set α, countable s ∧ (∀x, ∃y ∈ s, dist x y ≤ ε)) : second_countable_topology α := begin choose T T_dense using H, have I1 : ∀n:ℕ, (n:ℝ) + 1 > 0 := λn, lt_of_lt_of_le zero_lt_one (le_add_of_nonneg_left (nat.cast_nonneg _)), have I : ∀n:ℕ, (n+1 : ℝ)⁻¹ > 0 := λn, inv_pos'.2 (I1 n), let t := ⋃n:ℕ, T (n+1)⁻¹ (I n), have count_t : countable t := by finish [countable_Union], have clos_t : closure t = univ, { refine subset.antisymm (subset_univ _) (λx xuniv, mem_closure_iff.2 (λε εpos, _)), rcases exists_nat_gt ε⁻¹ with ⟨n, hn⟩, have : ε⁻¹ < n + 1 := lt_of_lt_of_le hn (le_add_of_nonneg_right zero_le_one), have nε : ((n:ℝ)+1)⁻¹ < ε := (inv_lt (I1 n) εpos).2 this, rcases (T_dense (n+1)⁻¹ (I n)).2 x with ⟨y, yT, Dxy⟩, have : y ∈ t := mem_of_mem_of_subset yT (by apply subset_Union (λ (n:ℕ), T (n+1)⁻¹ (I n))), exact ⟨y, this, lt_of_le_of_lt Dxy nε⟩ }, haveI : separable_space α := ⟨⟨t, ⟨count_t, clos_t⟩⟩⟩, exact emetric.second_countable_of_separable α end /-- A metric space space is second countable if one can reconstruct up to any ε>0 any element of the space from countably many data. -/ lemma second_countable_of_countable_discretization {α : Type u} [metric_space α] (H : ∀ε > (0 : ℝ), ∃ (β : Type u) [encodable β] (F : α → β), ∀x y, F x = F y → dist x y ≤ ε) : second_countable_topology α := begin cases (univ : set α).eq_empty_or_nonempty with hs hs, { haveI : compact_space α := ⟨by rw hs; exact compact_empty⟩, by apply_instance }, rcases hs with ⟨x0, hx0⟩, letI : inhabited α := ⟨x0⟩, refine second_countable_of_almost_dense_set (λε ε0, _), rcases H ε ε0 with ⟨β, fβ, F, hF⟩, let Finv := function.inv_fun F, refine ⟨range Finv, ⟨countable_range _, λx, _⟩⟩, let x' := Finv (F x), have : F x' = F x := function.inv_fun_eq ⟨x, rfl⟩, exact ⟨x', mem_range_self _, hF _ _ this.symm⟩ end end second_countable end metric lemma lebesgue_number_lemma_of_metric {s : set α} {ι} {c : ι → set α} (hs : compact s) (hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) : ∃ δ > 0, ∀ x ∈ s, ∃ i, ball x δ ⊆ c i := let ⟨n, en, hn⟩ := lebesgue_number_lemma hs hc₁ hc₂, ⟨δ, δ0, hδ⟩ := mem_uniformity_dist.1 en in ⟨δ, δ0, assume x hx, let ⟨i, hi⟩ := hn x hx in ⟨i, assume y hy, hi (hδ (mem_ball'.mp hy))⟩⟩ lemma lebesgue_number_lemma_of_metric_sUnion {s : set α} {c : set (set α)} (hs : compact s) (hc₁ : ∀ t ∈ c, is_open t) (hc₂ : s ⊆ ⋃₀ c) : ∃ δ > 0, ∀ x ∈ s, ∃ t ∈ c, ball x δ ⊆ t := by rw sUnion_eq_Union at hc₂; simpa using lebesgue_number_lemma_of_metric hs (by simpa) hc₂ namespace metric /-- Boundedness of a subset of a metric space. We formulate the definition to work even in the empty space. -/ def bounded (s : set α) : Prop := ∃C, ∀x y ∈ s, dist x y ≤ C section bounded variables {x : α} {s t : set α} {r : ℝ} @[simp] lemma bounded_empty : bounded (∅ : set α) := ⟨0, by simp⟩ lemma bounded_iff_mem_bounded : bounded s ↔ ∀ x ∈ s, bounded s := ⟨λ h _ _, h, λ H, s.eq_empty_or_nonempty.elim (λ hs, hs.symm ▸ bounded_empty) (λ ⟨x, hx⟩, H x hx)⟩ /-- Subsets of a bounded set are also bounded -/ lemma bounded.subset (incl : s ⊆ t) : bounded t → bounded s := Exists.imp $ λ C hC x y hx hy, hC x y (incl hx) (incl hy) /-- Closed balls are bounded -/ lemma bounded_closed_ball : bounded (closed_ball x r) := ⟨r + r, λ y z hy hz, begin simp only [mem_closed_ball] at *, calc dist y z ≤ dist y x + dist z x : dist_triangle_right _ _ _ ... ≤ r + r : add_le_add hy hz end⟩ /-- Open balls are bounded -/ lemma bounded_ball : bounded (ball x r) := bounded_closed_ball.subset ball_subset_closed_ball /-- Given a point, a bounded subset is included in some ball around this point -/ lemma bounded_iff_subset_ball (c : α) : bounded s ↔ ∃r, s ⊆ closed_ball c r := begin split; rintro ⟨C, hC⟩, { cases s.eq_empty_or_nonempty with h h, { subst s, exact ⟨0, by simp⟩ }, { rcases h with ⟨x, hx⟩, exact ⟨C + dist x c, λ y hy, calc dist y c ≤ dist y x + dist x c : dist_triangle _ _ _ ... ≤ C + dist x c : add_le_add_right (hC y x hy hx) _⟩ } }, { exact bounded_closed_ball.subset hC } end /-- The union of two bounded sets is bounded iff each of the sets is bounded -/ @[simp] lemma bounded_union : bounded (s ∪ t) ↔ bounded s ∧ bounded t := ⟨λh, ⟨h.subset (by simp), h.subset (by simp)⟩, begin rintro ⟨hs, ht⟩, refine bounded_iff_mem_bounded.2 (λ x _, _), rw bounded_iff_subset_ball x at hs ht ⊢, rcases hs with ⟨Cs, hCs⟩, rcases ht with ⟨Ct, hCt⟩, exact ⟨max Cs Ct, union_subset (subset.trans hCs $ closed_ball_subset_closed_ball $ le_max_left _ _) (subset.trans hCt $ closed_ball_subset_closed_ball $ le_max_right _ _)⟩, end⟩ /-- A finite union of bounded sets is bounded -/ lemma bounded_bUnion {I : set β} {s : β → set α} (H : finite I) : bounded (⋃i∈I, s i) ↔ ∀i ∈ I, bounded (s i) := finite.induction_on H (by simp) $ λ x I _ _ IH, by simp [or_imp_distrib, forall_and_distrib, IH] /-- A compact set is bounded -/ lemma bounded_of_compact {s : set α} (h : compact s) : bounded s := -- We cover the compact set by finitely many balls of radius 1, -- and then argue that a finite union of bounded sets is bounded let ⟨t, ht, fint, subs⟩ := finite_cover_balls_of_compact h zero_lt_one in bounded.subset subs $ (bounded_bUnion fint).2 $ λ i hi, bounded_ball alias bounded_of_compact ← compact.bounded /-- A finite set is bounded -/ lemma bounded_of_finite {s : set α} (h : finite s) : bounded s := h.compact.bounded /-- A singleton is bounded -/ lemma bounded_singleton {x : α} : bounded ({x} : set α) := bounded_of_finite $ finite_singleton _ /-- Characterization of the boundedness of the range of a function -/ lemma bounded_range_iff {f : β → α} : bounded (range f) ↔ ∃C, ∀x y, dist (f x) (f y) ≤ C := exists_congr $ λ C, ⟨ λ H x y, H _ _ ⟨x, rfl⟩ ⟨y, rfl⟩, by rintro H _ _ ⟨x, rfl⟩ ⟨y, rfl⟩; exact H x y⟩ /-- In a compact space, all sets are bounded -/ lemma bounded_of_compact_space [compact_space α] : bounded s := compact_univ.bounded.subset (subset_univ _) /-- The Heine–Borel theorem: In a proper space, a set is compact if and only if it is closed and bounded -/ lemma compact_iff_closed_bounded [proper_space α] : compact s ↔ is_closed s ∧ bounded s := ⟨λ h, ⟨closed_of_compact _ h, h.bounded⟩, begin rintro ⟨hc, hb⟩, cases s.eq_empty_or_nonempty with h h, {simp [h, compact_empty]}, rcases h with ⟨x, hx⟩, rcases (bounded_iff_subset_ball x).1 hb with ⟨r, hr⟩, exact compact_of_is_closed_subset (proper_space.compact_ball x r) hc hr end⟩ /-- The image of a proper space under an expanding onto map is proper. -/ lemma proper_image_of_proper [proper_space α] [metric_space β] (f : α → β) (f_cont : continuous f) (hf : range f = univ) (C : ℝ) (hC : ∀x y, dist x y ≤ C * dist (f x) (f y)) : proper_space β := begin apply proper_space_of_compact_closed_ball_of_le 0 (λx₀ r hr, _), let K := f ⁻¹' (closed_ball x₀ r), have A : is_closed K := continuous_iff_is_closed.1 f_cont (closed_ball x₀ r) (is_closed_ball), have B : bounded K := ⟨max C 0 * (r + r), λx y hx hy, calc dist x y ≤ C * dist (f x) (f y) : hC x y ... ≤ max C 0 * dist (f x) (f y) : mul_le_mul_of_nonneg_right (le_max_left _ _) (dist_nonneg) ... ≤ max C 0 * (dist (f x) x₀ + dist (f y) x₀) : mul_le_mul_of_nonneg_left (dist_triangle_right (f x) (f y) x₀) (le_max_right _ _) ... ≤ max C 0 * (r + r) : begin simp only [mem_closed_ball, mem_preimage] at hx hy, exact mul_le_mul_of_nonneg_left (add_le_add hx hy) (le_max_right _ _) end⟩, have : compact K := compact_iff_closed_bounded.2 ⟨A, B⟩, have C : compact (f '' K) := this.image f_cont, have : f '' K = closed_ball x₀ r, by { rw image_preimage_eq_of_subset, rw hf, exact subset_univ _ }, rwa this at C end end bounded section diam variables {s : set α} {x y z : α} /-- The diameter of a set in a metric space. To get controllable behavior even when the diameter should be infinite, we express it in terms of the emetric.diameter -/ def diam (s : set α) : ℝ := ennreal.to_real (emetric.diam s) /-- The diameter of a set is always nonnegative -/ lemma diam_nonneg : 0 ≤ diam s := ennreal.to_real_nonneg lemma diam_subsingleton (hs : s.subsingleton) : diam s = 0 := by simp only [diam, emetric.diam_subsingleton hs, ennreal.zero_to_real] /-- The empty set has zero diameter -/ @[simp] lemma diam_empty : diam (∅ : set α) = 0 := diam_subsingleton subsingleton_empty /-- A singleton has zero diameter -/ @[simp] lemma diam_singleton : diam ({x} : set α) = 0 := diam_subsingleton subsingleton_singleton -- Does not work as a simp-lemma, since {x, y} reduces to (insert y {x}) lemma diam_pair : diam ({x, y} : set α) = dist x y := by simp only [diam, emetric.diam_pair, dist_edist] -- Does not work as a simp-lemma, since {x, y} reduces to (insert z (insert y {x})) lemma diam_triple : metric.diam ({x, y, z} : set α) = max (dist x y) (max (dist y z) (dist x z)) := begin simp only [metric.diam, emetric.diam_triple, dist_edist], rw [ennreal.to_real_max, ennreal.to_real_max]; apply_rules [ne_of_lt, edist_lt_top, max_lt] end /-- If the distance between any two points in a set is bounded by some constant `C`, then `ennreal.of_real C` bounds the emetric diameter of this set. -/ lemma ediam_le_of_forall_dist_le {C : ℝ} (h : ∀ (x ∈ s) (y ∈ s), dist x y ≤ C) : emetric.diam s ≤ ennreal.of_real C := emetric.diam_le_of_forall_edist_le $ λ x hx y hy, (edist_dist x y).symm ▸ ennreal.of_real_le_of_real (h x hx y hy) /-- If the distance between any two points in a set is bounded by some non-negative constant, this constant bounds the diameter. -/ lemma diam_le_of_forall_dist_le {C : ℝ} (h₀ : 0 ≤ C) (h : ∀ (x ∈ s) (y ∈ s), dist x y ≤ C) : diam s ≤ C := ennreal.to_real_le_of_le_of_real h₀ (ediam_le_of_forall_dist_le h) /-- If the distance between any two points in a nonempty set is bounded by some constant, this constant bounds the diameter. -/ lemma diam_le_of_forall_dist_le_of_nonempty (hs : s.nonempty) {C : ℝ} (h : ∀ (x ∈ s) (y ∈ s), dist x y ≤ C) : diam s ≤ C := have h₀ : 0 ≤ C, from let ⟨x, hx⟩ := hs in le_trans dist_nonneg (h x hx x hx), diam_le_of_forall_dist_le h₀ h /-- The distance between two points in a set is controlled by the diameter of the set. -/ lemma dist_le_diam_of_mem' (h : emetric.diam s ≠ ⊤) (hx : x ∈ s) (hy : y ∈ s) : dist x y ≤ diam s := begin rw [diam, dist_edist], rw ennreal.to_real_le_to_real (edist_ne_top _ _) h, exact emetric.edist_le_diam_of_mem hx hy end /-- Characterize the boundedness of a set in terms of the finiteness of its emetric.diameter. -/ lemma bounded_iff_ediam_ne_top : bounded s ↔ emetric.diam s ≠ ⊤ := iff.intro (λ ⟨C, hC⟩, ne_top_of_le_ne_top ennreal.of_real_ne_top (ediam_le_of_forall_dist_le $ λ x hx y hy, hC x y hx hy)) (λ h, ⟨diam s, λ x y hx hy, dist_le_diam_of_mem' h hx hy⟩) lemma bounded.ediam_ne_top (h : bounded s) : emetric.diam s ≠ ⊤ := bounded_iff_ediam_ne_top.1 h /-- The distance between two points in a set is controlled by the diameter of the set. -/ lemma dist_le_diam_of_mem (h : bounded s) (hx : x ∈ s) (hy : y ∈ s) : dist x y ≤ diam s := dist_le_diam_of_mem' h.ediam_ne_top hx hy /-- An unbounded set has zero diameter. If you would prefer to get the value ∞, use `emetric.diam`. This lemma makes it possible to avoid side conditions in some situations -/ lemma diam_eq_zero_of_unbounded (h : ¬(bounded s)) : diam s = 0 := begin simp only [bounded_iff_ediam_ne_top, not_not, ne.def] at h, simp [diam, h] end /-- If `s ⊆ t`, then the diameter of `s` is bounded by that of `t`, provided `t` is bounded. -/ lemma diam_mono {s t : set α} (h : s ⊆ t) (ht : bounded t) : diam s ≤ diam t := begin unfold diam, rw ennreal.to_real_le_to_real (bounded.subset h ht).ediam_ne_top ht.ediam_ne_top, exact emetric.diam_mono h end /-- The diameter of a union is controlled by the sum of the diameters, and the distance between any two points in each of the sets. This lemma is true without any side condition, since it is obviously true if `s ∪ t` is unbounded. -/ lemma diam_union {t : set α} (xs : x ∈ s) (yt : y ∈ t) : diam (s ∪ t) ≤ diam s + dist x y + diam t := begin classical, by_cases H : bounded (s ∪ t), { have hs : bounded s, from H.subset (subset_union_left _ _), have ht : bounded t, from H.subset (subset_union_right _ _), rw [bounded_iff_ediam_ne_top] at H hs ht, rw [dist_edist, diam, diam, diam, ← ennreal.to_real_add, ← ennreal.to_real_add, ennreal.to_real_le_to_real]; repeat { apply ennreal.add_ne_top.2; split }; try { assumption }; try { apply edist_ne_top }, exact emetric.diam_union xs yt }, { rw [diam_eq_zero_of_unbounded H], apply_rules [add_nonneg, diam_nonneg, dist_nonneg] } end /-- If two sets intersect, the diameter of the union is bounded by the sum of the diameters. -/ lemma diam_union' {t : set α} (h : (s ∩ t).nonempty) : diam (s ∪ t) ≤ diam s + diam t := begin rcases h with ⟨x, ⟨xs, xt⟩⟩, simpa using diam_union xs xt end /-- The diameter of a closed ball of radius `r` is at most `2 r`. -/ lemma diam_closed_ball {r : ℝ} (h : r ≥ 0) : diam (closed_ball x r) ≤ 2 * r := diam_le_of_forall_dist_le (mul_nonneg (le_of_lt two_pos) h) $ λa ha b hb, calc dist a b ≤ dist a x + dist b x : dist_triangle_right _ _ _ ... ≤ r + r : add_le_add ha hb ... = 2 * r : by simp [mul_two, mul_comm] /-- The diameter of a ball of radius `r` is at most `2 r`. -/ lemma diam_ball {r : ℝ} (h : r ≥ 0) : diam (ball x r) ≤ 2 * r := le_trans (diam_mono ball_subset_closed_ball bounded_closed_ball) (diam_closed_ball h) end diam end metric
ba8abfae5e7f136a589d007b379b10428c5a2f7c
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/ring_theory/localization/away.lean
1ca217eb416a16e9070e79e688563d7c3b454e5e
[ "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
7,043
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, Anne Baanen -/ import ring_theory.adjoin_root import ring_theory.localization.basic /-! # Localizations away from an element ## Main definitions * `is_localization.away (x : R) S` expresses that `S` is a localization away from `x`, as an abbreviation of `is_localization (submonoid.powers x) S` ## Implementation notes See `src/ring_theory/localization/basic.lean` for a design overview. ## Tags localization, ring localization, commutative ring localization, characteristic predicate, commutative ring, field of fractions -/ section comm_semiring variables {R : Type*} [comm_semiring R] (M : submonoid R) {S : Type*} [comm_semiring S] variables [algebra R S] {P : Type*} [comm_semiring P] namespace is_localization section away variables (x : R) /-- Given `x : R`, the typeclass `is_localization.away x S` states that `S` is isomorphic to the localization of `R` at the submonoid generated by `x`. -/ abbreviation away (S : Type*) [comm_semiring S] [algebra R S] := is_localization (submonoid.powers x) S namespace away variables [is_localization.away x S] /-- Given `x : R` and a localization map `F : R →+* S` away from `x`, `inv_self` is `(F x)⁻¹`. -/ noncomputable def inv_self : S := mk' S (1 : R) ⟨x, submonoid.mem_powers _⟩ @[simp] lemma mul_inv_self : algebra_map R S x * inv_self x = 1 := by { convert is_localization.mk'_mul_mk'_eq_one _ 1, symmetry, apply is_localization.mk'_one } variables {g : R →+* P} /-- Given `x : R`, a localization map `F : R →+* S` away from `x`, and a map of `comm_semiring`s `g : R →+* P` such that `g x` is invertible, the homomorphism induced from `S` to `P` sending `z : S` to `g y * (g x)⁻ⁿ`, where `y : R, n : ℕ` are such that `z = F y * (F x)⁻ⁿ`. -/ noncomputable def lift (hg : is_unit (g x)) : S →+* P := is_localization.lift $ λ (y : submonoid.powers x), show is_unit (g y.1), begin obtain ⟨n, hn⟩ := y.2, rw [←hn, g.map_pow], exact is_unit.map (pow_monoid_hom n : P →* P) hg, end @[simp] lemma away_map.lift_eq (hg : is_unit (g x)) (a : R) : lift x hg ((algebra_map R S) a) = g a := lift_eq _ _ @[simp] lemma away_map.lift_comp (hg : is_unit (g x)) : (lift x hg).comp (algebra_map R S) = g := lift_comp _ /-- Given `x y : R` and localizations `S`, `P` away from `x` and `x * y` respectively, the homomorphism induced from `S` to `P`. -/ noncomputable def away_to_away_right (y : R) [algebra R P] [is_localization.away (x * y) P] : S →+* P := lift x $ show is_unit ((algebra_map R P) x), from is_unit_of_mul_eq_one ((algebra_map R P) x) (mk' P y ⟨x * y, submonoid.mem_powers _⟩) $ by rw [mul_mk'_eq_mk'_of_mul, mk'_self] variables (S) (Q : Type*) [comm_semiring Q] [algebra P Q] /-- Given a map `f : R →+* S` and an element `r : R`, we may construct a map `Rᵣ →+* Sᵣ`. -/ noncomputable def map (f : R →+* P) (r : R) [is_localization.away r S] [is_localization.away (f r) Q] : S →+* Q := is_localization.map Q f (show submonoid.powers r ≤ (submonoid.powers (f r)).comap f, by { rintros x ⟨n, rfl⟩, use n, simp }) end away end away variables [is_localization M S] section at_units variables (R) (S) (M) /-- The localization at a module of units is isomorphic to the ring -/ noncomputable def at_units (H : ∀ x : M, is_unit (x : R)) : R ≃ₐ[R] S := begin refine alg_equiv.of_bijective (algebra.of_id R S) ⟨_, _⟩, { intros x y hxy, obtain ⟨c, eq⟩ := (is_localization.eq_iff_exists M S).mp hxy, obtain ⟨u, hu⟩ := H c, rwa [← hu, units.mul_left_inj] at eq }, { intros y, obtain ⟨⟨x, s⟩, eq⟩ := is_localization.surj M y, obtain ⟨u, hu⟩ := H s, use x * u.inv, dsimp only [algebra.of_id, ring_hom.to_fun_eq_coe, alg_hom.coe_mk], rw [ring_hom.map_mul, ← eq, ← hu, mul_assoc, ← ring_hom.map_mul], simp } end /-- The localization away from a unit is isomorphic to the ring -/ noncomputable def at_unit (x : R) (e : is_unit x) [is_localization.away x S] : R ≃ₐ[R] S := begin apply at_units R (submonoid.powers x), rintros ⟨xn, n, hxn⟩, obtain ⟨u, hu⟩ := e, rw is_unit_iff_exists_inv, use u.inv ^ n, simp[← hxn, ← hu, ← mul_pow] end /-- The localization at one is isomorphic to the ring. -/ noncomputable def at_one [is_localization.away (1 : R) S] : R ≃ₐ[R] S := @at_unit R _ S _ _ (1 : R) is_unit_one _ lemma away_of_is_unit_of_bijective {R : Type*} (S : Type*) [comm_ring R] [comm_ring S] [algebra R S] {r : R} (hr : is_unit r) (H : function.bijective (algebra_map R S)) : is_localization.away r S := { map_units := by { rintros ⟨_, n, rfl⟩, exact (algebra_map R S).is_unit_map (hr.pow _) }, surj := λ z, by { obtain ⟨z', rfl⟩ := H.2 z, exact ⟨⟨z', 1⟩, by simp⟩ }, eq_iff_exists := λ x y, begin erw H.1.eq_iff, split, { rintro rfl, exact ⟨1, rfl⟩ }, { rintro ⟨⟨_, n, rfl⟩, e⟩, exact (hr.pow _).mul_left_inj.mp e } end } end at_units end is_localization namespace localization open is_localization variables {M} /-- Given a map `f : R →+* S` and an element `r : R`, such that `f r` is invertible, we may construct a map `Rᵣ →+* S`. -/ noncomputable abbreviation away_lift (f : R →+* P) (r : R) (hr : is_unit (f r)) : localization.away r →+* P := is_localization.away.lift r hr /-- Given a map `f : R →+* S` and an element `r : R`, we may construct a map `Rᵣ →+* Sᵣ`. -/ noncomputable abbreviation away_map (f : R →+* P) (r : R) : localization.away r →+* localization.away (f r) := is_localization.away.map _ _ f r end localization end comm_semiring open polynomial adjoin_root localization variables {R : Type*} [comm_ring R] local attribute [instance] is_localization.alg_hom_subsingleton adjoin_root.alg_hom_subsingleton /-- The `R`-`alg_equiv` between the localization of `R` away from `r` and `R` with an inverse of `r` adjoined. -/ noncomputable def localization.away_equiv_adjoin (r : R) : away r ≃ₐ[R] adjoin_root (C r * X - 1) := alg_equiv.of_alg_hom { commutes' := is_localization.away.away_map.lift_eq r (is_unit_of_mul_eq_one _ _ $ root_is_inv r), .. away_lift _ r _ } (lift_hom _ (is_localization.away.inv_self r) $ by simp only [map_sub, map_mul, aeval_C, aeval_X, is_localization.away.mul_inv_self, aeval_one, sub_self]) (subsingleton.elim _ _) (subsingleton.elim _ _) lemma is_localization.adjoin_inv (r : R) : is_localization.away r (adjoin_root $ C r * X - 1) := is_localization.is_localization_of_alg_equiv _ (localization.away_equiv_adjoin r) lemma is_localization.away.finite_presentation (r : R) {S} [comm_ring S] [algebra R S] [is_localization.away r S] : algebra.finite_presentation R S := (adjoin_root.finite_presentation _).equiv $ (localization.away_equiv_adjoin r).symm.trans $ is_localization.alg_equiv (submonoid.powers r) _ _
da5ac26b1f27cd0123a304436af85541a83f4eb4
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/ring_theory/algebra_tower.lean
13995f4ff684d88a3b7d37d947822047beb4ace0
[ "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
14,131
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.algebra.restrict_scalars import algebra.algebra.tower import algebra.invertible import linear_algebra.basis import ring_theory.adjoin.fg import ring_theory.polynomial.tower /-! # Towers of algebras We set up the basic theory of algebra towers. An algebra tower A/S/R is expressed by having instances of `algebra A S`, `algebra R S`, `algebra R A` and `is_scalar_tower R S A`, the later asserting the compatibility condition `(r • s) • a = r • (s • a)`. In `field_theory/tower.lean` we use this to prove the tower law for finite extensions, that if `R` and `S` are both fields, then `[A:R] = [A:S] [S:A]`. In this file we prepare the main lemma: if `{bi | i ∈ I}` is an `R`-basis of `S` and `{cj | j ∈ J}` is a `S`-basis of `A`, then `{bi cj | i ∈ I, j ∈ J}` is an `R`-basis of `A`. This statement does not require the base rings to be a field, so we also generalize the lemma to rings in this file. -/ open_locale pointwise universes u v w u₁ variables (R : Type u) (S : Type v) (A : Type w) (B : Type u₁) namespace is_scalar_tower section semiring variables [comm_semiring R] [comm_semiring S] [semiring A] [semiring B] variables [algebra R S] [algebra S A] [algebra S B] [algebra R A] [algebra R B] variables [is_scalar_tower R S A] [is_scalar_tower R S B] variables (R S A B) /-- Suppose that `R -> S -> A` is a tower of algebras. If an element `r : R` is invertible in `S`, then it is invertible in `A`. -/ def invertible.algebra_tower (r : R) [invertible (algebra_map R S r)] : invertible (algebra_map R A r) := invertible.copy (invertible.map (algebra_map S A : S →* A) (algebra_map R S r)) (algebra_map R A r) (by rw [ring_hom.coe_monoid_hom, is_scalar_tower.algebra_map_apply R S A]) /-- A natural number that is invertible when coerced to `R` is also invertible when coerced to any `R`-algebra. -/ def invertible_algebra_coe_nat (n : ℕ) [inv : invertible (n : R)] : invertible (n : A) := by { haveI : invertible (algebra_map ℕ R n) := inv, exact invertible.algebra_tower ℕ R A n } end semiring section comm_semiring variables [comm_semiring R] [comm_semiring A] [comm_semiring B] variables [algebra R A] [algebra A B] [algebra R B] [is_scalar_tower R A B] end comm_semiring end is_scalar_tower namespace algebra theorem adjoin_algebra_map' {R : Type u} {S : Type v} {A : Type w} [comm_semiring R] [comm_semiring S] [semiring A] [algebra R S] [algebra S A] (s : set S) : adjoin R (algebra_map S (restrict_scalars R S A) '' s) = (adjoin R s).map ((algebra.of_id S (restrict_scalars R S A)).restrict_scalars R) := le_antisymm (adjoin_le $ set.image_subset_iff.2 $ λ y hy, ⟨y, subset_adjoin hy, rfl⟩) (subalgebra.map_le.2 $ adjoin_le $ λ y hy, subset_adjoin ⟨y, hy, rfl⟩) theorem adjoin_algebra_map (R : Type u) (S : Type v) (A : Type w) [comm_semiring R] [comm_semiring S] [semiring A] [algebra R S] [algebra S A] [algebra R A] [is_scalar_tower R S A] (s : set S) : adjoin R (algebra_map S A '' s) = subalgebra.map (adjoin R s) (is_scalar_tower.to_alg_hom R S A) := le_antisymm (adjoin_le $ set.image_subset_iff.2 $ λ y hy, ⟨y, subset_adjoin hy, rfl⟩) (subalgebra.map_le.2 $ adjoin_le $ λ y hy, subset_adjoin ⟨y, hy, rfl⟩) lemma adjoin_restrict_scalars (C D E : Type*) [comm_semiring C] [comm_semiring D] [comm_semiring E] [algebra C D] [algebra C E] [algebra D E] [is_scalar_tower C D E] (S : set E) : (algebra.adjoin D S).restrict_scalars C = (algebra.adjoin ((⊤ : subalgebra C D).map (is_scalar_tower.to_alg_hom C D E)) S).restrict_scalars C := begin suffices : set.range (algebra_map D E) = set.range (algebra_map ((⊤ : subalgebra C D).map (is_scalar_tower.to_alg_hom C D E)) E), { ext x, change x ∈ subsemiring.closure (_ ∪ S) ↔ x ∈ subsemiring.closure (_ ∪ S), rw this }, ext x, split, { rintros ⟨y, hy⟩, exact ⟨⟨algebra_map D E y, ⟨y, ⟨algebra.mem_top, rfl⟩⟩⟩, hy⟩ }, { rintros ⟨⟨y, ⟨z, ⟨h0, h1⟩⟩⟩, h2⟩, exact ⟨z, eq.trans h1 h2⟩ }, end lemma adjoin_res_eq_adjoin_res (C D E F : Type*) [comm_semiring C] [comm_semiring D] [comm_semiring E] [comm_semiring F] [algebra C D] [algebra C E] [algebra C F] [algebra D F] [algebra E F] [is_scalar_tower C D F] [is_scalar_tower C E F] {S : set D} {T : set E} (hS : algebra.adjoin C S = ⊤) (hT : algebra.adjoin C T = ⊤) : (algebra.adjoin E (algebra_map D F '' S)).restrict_scalars C = (algebra.adjoin D (algebra_map E F '' T)).restrict_scalars C := by rw [adjoin_restrict_scalars C E, adjoin_restrict_scalars C D, ←hS, ←hT, ←algebra.adjoin_image, ←algebra.adjoin_image, ←alg_hom.coe_to_ring_hom, ←alg_hom.coe_to_ring_hom, is_scalar_tower.coe_to_alg_hom, is_scalar_tower.coe_to_alg_hom, ←adjoin_union_eq_adjoin_adjoin, ←adjoin_union_eq_adjoin_adjoin, set.union_comm] end algebra section open_locale classical lemma algebra.fg_trans' {R S A : Type*} [comm_semiring R] [comm_semiring S] [comm_semiring A] [algebra R S] [algebra S A] [algebra R A] [is_scalar_tower R S A] (hRS : (⊤ : subalgebra R S).fg) (hSA : (⊤ : subalgebra S A).fg) : (⊤ : subalgebra R A).fg := let ⟨s, hs⟩ := hRS, ⟨t, ht⟩ := hSA in ⟨s.image (algebra_map S A) ∪ t, by rw [finset.coe_union, finset.coe_image, algebra.adjoin_union_eq_adjoin_adjoin, algebra.adjoin_algebra_map, hs, algebra.map_top, is_scalar_tower.adjoin_range_to_alg_hom, ht, subalgebra.restrict_scalars_top]⟩ end section algebra_map_coeffs variables {R} (A) {ι M : Type*} [comm_semiring R] [semiring A] [add_comm_monoid M] variables [algebra R A] [module A M] [module R M] [is_scalar_tower R A M] variables (b : basis ι R M) (h : function.bijective (algebra_map R A)) /-- If `R` and `A` have a bijective `algebra_map R A` and act identically on `M`, then a basis for `M` as `R`-module is also a basis for `M` as `R'`-module. -/ @[simps] noncomputable def basis.algebra_map_coeffs : basis ι A M := b.map_coeffs (ring_equiv.of_bijective _ h) (λ c x, by simp) lemma basis.algebra_map_coeffs_apply (i : ι) : b.algebra_map_coeffs A h i = b i := b.map_coeffs_apply _ _ _ @[simp] lemma basis.coe_algebra_map_coeffs : (b.algebra_map_coeffs A h : ι → M) = b := b.coe_map_coeffs _ _ end algebra_map_coeffs section semiring open finsupp open_locale big_operators classical universes v₁ w₁ variables {R S A} variables [comm_semiring R] [semiring S] [add_comm_monoid A] variables [algebra R S] [module S A] [module R A] [is_scalar_tower R S A] theorem linear_independent_smul {ι : Type v₁} {b : ι → S} {ι' : Type w₁} {c : ι' → A} (hb : linear_independent R b) (hc : linear_independent S c) : linear_independent R (λ p : ι × ι', b p.1 • c p.2) := begin rw linear_independent_iff' at hb hc, rw linear_independent_iff'', rintros s g hg hsg ⟨i, k⟩, by_cases hik : (i, k) ∈ s, { have h1 : ∑ i in (s.image prod.fst).product (s.image prod.snd), g i • b i.1 • c i.2 = 0, { rw ← hsg, exact (finset.sum_subset finset.subset_product $ λ p _ hp, show g p • b p.1 • c p.2 = 0, by rw [hg p hp, zero_smul]).symm }, rw [finset.sum_product, finset.sum_comm] at h1, simp_rw [← smul_assoc, ← finset.sum_smul] at h1, exact hb _ _ (hc _ _ h1 k (finset.mem_image_of_mem _ hik)) i (finset.mem_image_of_mem _ hik) }, exact hg _ hik end /-- `basis.smul (b : basis ι R S) (c : basis ι S A)` is the `R`-basis on `A` where the `(i, j)`th basis vector is `b i • c j`. -/ noncomputable def basis.smul {ι : Type v₁} {ι' : Type w₁} (b : basis ι R S) (c : basis ι' S A) : basis (ι × ι') R A := basis.of_repr ((c.repr.restrict_scalars R) ≪≫ₗ ((finsupp.lcongr (equiv.refl _) b.repr) ≪≫ₗ ((finsupp_prod_lequiv R).symm ≪≫ₗ ((finsupp.lcongr (equiv.prod_comm ι' ι) (linear_equiv.refl _ _)))))) @[simp] theorem basis.smul_repr {ι : Type v₁} {ι' : Type w₁} (b : basis ι R S) (c : basis ι' S A) (x ij): (b.smul c).repr x ij = b.repr (c.repr x ij.2) ij.1 := by simp [basis.smul] theorem basis.smul_repr_mk {ι : Type v₁} {ι' : Type w₁} (b : basis ι R S) (c : basis ι' S A) (x i j): (b.smul c).repr x (i, j) = b.repr (c.repr x j) i := b.smul_repr c x (i, j) @[simp] theorem basis.smul_apply {ι : Type v₁} {ι' : Type w₁} (b : basis ι R S) (c : basis ι' S A) (ij) : (b.smul c) ij = b ij.1 • c ij.2 := begin obtain ⟨i, j⟩ := ij, rw basis.apply_eq_iff, ext ⟨i', j'⟩, rw [basis.smul_repr, linear_equiv.map_smul, basis.repr_self, finsupp.smul_apply, finsupp.single_apply], dsimp only, split_ifs with hi, { simp [hi, finsupp.single_apply] }, { simp [hi] }, end end semiring section ring variables {R S} variables [comm_ring R] [ring S] [algebra R S] lemma basis.algebra_map_injective {ι : Type*} [no_zero_divisors R] [nontrivial S] (b : basis ι R S) : function.injective (algebra_map R S) := have no_zero_smul_divisors R S := b.no_zero_smul_divisors, by exactI no_zero_smul_divisors.algebra_map_injective R S end ring section artin_tate variables (C : Type*) section semiring variables [comm_semiring A] [comm_semiring B] [semiring C] variables [algebra A B] [algebra B C] [algebra A C] [is_scalar_tower A B C] open finset submodule open_locale classical lemma exists_subalgebra_of_fg (hAC : (⊤ : subalgebra A C).fg) (hBC : (⊤ : submodule B C).fg) : ∃ B₀ : subalgebra A B, B₀.fg ∧ (⊤ : submodule B₀ C).fg := begin cases hAC with x hx, cases hBC with y hy, have := hy, simp_rw [eq_top_iff', mem_span_finset] at this, choose f hf, let s : finset B := (finset.product (x ∪ (y * y)) y).image (function.uncurry f), have hsx : ∀ (xi ∈ x) (yj ∈ y), f xi yj ∈ s := λ xi hxi yj hyj, show function.uncurry f (xi, yj) ∈ s, from mem_image_of_mem _ $ mem_product.2 ⟨mem_union_left _ hxi, hyj⟩, have hsy : ∀ (yi yj yk ∈ y), f (yi * yj) yk ∈ s := λ yi yj yk hyi hyj hyk, show function.uncurry f (yi * yj, yk) ∈ s, from mem_image_of_mem _ $ mem_product.2 ⟨mem_union_right _ $ finset.mul_mem_mul hyi hyj, hyk⟩, have hxy : ∀ xi ∈ x, xi ∈ span (algebra.adjoin A (↑s : set B)) (↑(insert 1 y : finset C) : set C) := λ xi hxi, hf xi ▸ sum_mem _ (λ yj hyj, smul_mem (span (algebra.adjoin A (↑s : set B)) (↑(insert 1 y : finset C) : set C)) ⟨f xi yj, algebra.subset_adjoin $ hsx xi hxi yj hyj⟩ (subset_span $ mem_insert_of_mem hyj)), have hyy : span (algebra.adjoin A (↑s : set B)) (↑(insert 1 y : finset C) : set C) * span (algebra.adjoin A (↑s : set B)) (↑(insert 1 y : finset C) : set C) ≤ span (algebra.adjoin A (↑s : set B)) (↑(insert 1 y : finset C) : set C), { rw [span_mul_span, span_le, coe_insert], rintros _ ⟨yi, yj, rfl | hyi, rfl | hyj, rfl⟩, { rw mul_one, exact subset_span (set.mem_insert _ _) }, { rw one_mul, exact subset_span (set.mem_insert_of_mem _ hyj) }, { rw mul_one, exact subset_span (set.mem_insert_of_mem _ hyi) }, { rw ← hf (yi * yj), exact set_like.mem_coe.2 (sum_mem _ $ λ yk hyk, smul_mem (span (algebra.adjoin A (↑s : set B)) (insert 1 ↑y : set C)) ⟨f (yi * yj) yk, algebra.subset_adjoin $ hsy yi yj yk hyi hyj hyk⟩ (subset_span $ set.mem_insert_of_mem _ hyk : yk ∈ _)) } }, refine ⟨algebra.adjoin A (↑s : set B), subalgebra.fg_adjoin_finset _, insert 1 y, _⟩, refine restrict_scalars_injective A _ _ _, rw [restrict_scalars_top, eq_top_iff, ← algebra.top_to_submodule, ← hx, algebra.adjoin_eq_span, span_le], refine λ r hr, submonoid.closure_induction hr (λ c hc, hxy c hc) (subset_span $ mem_insert_self _ _) (λ p q hp hq, hyy $ submodule.mul_mem_mul hp hq) end end semiring section ring variables [comm_ring A] [comm_ring B] [comm_ring C] variables [algebra A B] [algebra B C] [algebra A C] [is_scalar_tower A B C] /-- Artin--Tate lemma: if A ⊆ B ⊆ C is a chain of subrings of commutative rings, and A is noetherian, and C is algebra-finite over A, and C is module-finite over B, then B is algebra-finite over A. References: Atiyah--Macdonald Proposition 7.8; Stacks 00IS; Altman--Kleiman 16.17. -/ theorem fg_of_fg_of_fg [is_noetherian_ring A] (hAC : (⊤ : subalgebra A C).fg) (hBC : (⊤ : submodule B C).fg) (hBCi : function.injective (algebra_map B C)) : (⊤ : subalgebra A B).fg := let ⟨B₀, hAB₀, hB₀C⟩ := exists_subalgebra_of_fg A B C hAC hBC in algebra.fg_trans' (B₀.fg_top.2 hAB₀) $ subalgebra.fg_of_submodule_fg $ have is_noetherian_ring B₀, from is_noetherian_ring_of_fg hAB₀, have is_noetherian B₀ C, by exactI is_noetherian_of_fg_of_noetherian' hB₀C, by exactI fg_of_injective (is_scalar_tower.to_alg_hom B₀ B C).to_linear_map hBCi end ring end artin_tate section alg_hom_tower variables {A} {C D : Type*} [comm_semiring A] [comm_semiring C] [comm_semiring D] [algebra A C] [algebra A D] variables (f : C →ₐ[A] D) (B) [comm_semiring B] [algebra A B] [algebra B C] [is_scalar_tower A B C] /-- Restrict the domain of an `alg_hom`. -/ def alg_hom.restrict_domain : B →ₐ[A] D := f.comp (is_scalar_tower.to_alg_hom A B C) /-- Extend the scalars of an `alg_hom`. -/ def alg_hom.extend_scalars : @alg_hom B C D _ _ _ _ (f.restrict_domain B).to_ring_hom.to_algebra := { commutes' := λ _, rfl .. f } variables {B} /-- `alg_hom`s from the top of a tower are equivalent to a pair of `alg_hom`s. -/ def alg_hom_equiv_sigma : (C →ₐ[A] D) ≃ Σ (f : B →ₐ[A] D), @alg_hom B C D _ _ _ _ f.to_ring_hom.to_algebra := { to_fun := λ f, ⟨f.restrict_domain B, f.extend_scalars B⟩, inv_fun := λ fg, let alg := fg.1.to_ring_hom.to_algebra in by exactI fg.2.restrict_scalars A, left_inv := λ f, by { dsimp only, ext, refl }, right_inv := begin rintros ⟨⟨f, _, _, _, _, _⟩, g, _, _, _, _, hg⟩, have : f = λ x, g (algebra_map B C x) := by { ext, exact (hg x).symm }, subst this, refl, end } end alg_hom_tower
9a0fc613332f2dcba5838d70e4366541efc4ee1d
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/quotient.lean
3cd044c5b6bf8caa129009776098e1ab8fc7f02b
[ "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
2,223
lean
/- Copyright (c) 2021 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import tactic.basic /-! # Algebraic quotients > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > https://github.com/leanprover-community/mathlib4/pull/643 > Any changes to this file require a corresponding PR to mathlib4. This file defines notation for algebraic quotients, e.g. quotient groups `G ⧸ H`, quotient modules `M ⧸ N` and ideal quotients `R ⧸ I`. The actual quotient structures are defined in the following files: * quotient group: `src/group_theory/quotient_group.lean` * quotient module: `src/linear_algebra/quotient.lean` * quotient ring: `src/ring_theory/ideal/quotient.lean` ## Notations The following notation is introduced: * `G ⧸ H` stands for the quotient of the type `G` by some term `H` (for example, `H` can be a normal subgroup of `G`). To implement this notation for other quotients, you should provide a `has_quotient` instance. Note that since `G` can usually be inferred from `H`, `_ ⧸ H` can also be used, but this is less readable. ## Tags quotient, group quotient, quotient group, module quotient, quotient module, ring quotient, ideal quotient, quotient ring -/ universes u v /-- `has_quotient A B` is a notation typeclass that allows us to write `A ⧸ b` for `b : B`. This allows the usual notation for quotients of algebraic structures, such as groups, modules and rings. `A` is a parameter, despite being unused in the definition below, so it appears in the notation. -/ class has_quotient (A : out_param $ Type u) (B : Type v) := (quotient' : B → Type (max u v)) /-- `has_quotient.quotient A b` (with notation `A ⧸ b`) is the quotient of the type `A` by `b`. This differs from `has_quotient.quotient'` in that the `A` argument is explicit, which is necessary to make Lean show the notation in the goal state. -/ @[reducible, nolint has_nonempty_instance] -- Will be provided by e.g. `ideal.quotient.inhabited` def has_quotient.quotient (A : out_param $ Type u) {B : Type v} [has_quotient A B] (b : B) : Type (max u v) := has_quotient.quotient' b notation G ` ⧸ `:35 H:34 := has_quotient.quotient G H
845c4569af648a98d58a07236cab7b1169153cdf
130c49f47783503e462c16b2eff31933442be6ff
/stage0/src/Lean/Parser/Extension.lean
784a8e0d7121d9aa35dd7b6640bfd8fae19ba1f0
[ "Apache-2.0" ]
permissive
Hazel-Brown/lean4
8aa5860e282435ffc30dcdfccd34006c59d1d39c
79e6732fc6bbf5af831b76f310f9c488d44e7a16
refs/heads/master
1,689,218,208,951
1,629,736,869,000
1,629,736,896,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
26,212
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.ScopedEnvExtension import Lean.Parser.Basic import Lean.Parser.StrInterpolation import Lean.KeyedDeclsAttribute /-! Extensible parsing via attributes -/ namespace Lean namespace Parser builtin_initialize builtinTokenTable : IO.Ref TokenTable ← IO.mkRef {} /- Global table with all SyntaxNodeKind's -/ builtin_initialize builtinSyntaxNodeKindSetRef : IO.Ref SyntaxNodeKindSet ← IO.mkRef {} def registerBuiltinNodeKind (k : SyntaxNodeKind) : IO Unit := builtinSyntaxNodeKindSetRef.modify fun s => s.insert k builtin_initialize registerBuiltinNodeKind choiceKind registerBuiltinNodeKind identKind registerBuiltinNodeKind strLitKind registerBuiltinNodeKind numLitKind registerBuiltinNodeKind scientificLitKind registerBuiltinNodeKind charLitKind registerBuiltinNodeKind nameLitKind builtin_initialize builtinParserCategoriesRef : IO.Ref ParserCategories ← IO.mkRef {} private def throwParserCategoryAlreadyDefined {α} (catName : Name) : ExceptT String Id α := throw s!"parser category '{catName}' has already been defined" private def addParserCategoryCore (categories : ParserCategories) (catName : Name) (initial : ParserCategory) : Except String ParserCategories := if categories.contains catName then throwParserCategoryAlreadyDefined catName else pure $ categories.insert catName initial /-- All builtin parser categories are Pratt's parsers -/ private def addBuiltinParserCategory (catName : Name) (behavior : LeadingIdentBehavior) : IO Unit := do let categories ← builtinParserCategoriesRef.get let categories ← IO.ofExcept $ addParserCategoryCore categories catName { tables := {}, behavior := behavior} builtinParserCategoriesRef.set categories namespace ParserExtension inductive OLeanEntry where | token (val : Token) : OLeanEntry | kind (val : SyntaxNodeKind) : OLeanEntry | category (catName : Name) (behavior : LeadingIdentBehavior) | parser (catName : Name) (declName : Name) (prio : Nat) : OLeanEntry deriving Inhabited inductive Entry where | token (val : Token) : Entry | kind (val : SyntaxNodeKind) : Entry | category (catName : Name) (behavior : LeadingIdentBehavior) | parser (catName : Name) (declName : Name) (leading : Bool) (p : Parser) (prio : Nat) : Entry deriving Inhabited def Entry.toOLeanEntry : Entry → OLeanEntry | token v => OLeanEntry.token v | kind v => OLeanEntry.kind v | category c b => OLeanEntry.category c b | parser c d _ _ prio => OLeanEntry.parser c d prio structure State where tokens : TokenTable := {} kinds : SyntaxNodeKindSet := {} categories : ParserCategories := {} deriving Inhabited end ParserExtension open ParserExtension in abbrev ParserExtension := ScopedEnvExtension OLeanEntry Entry State private def ParserExtension.mkInitial : IO ParserExtension.State := do let tokens ← builtinTokenTable.get let kinds ← builtinSyntaxNodeKindSetRef.get let categories ← builtinParserCategoriesRef.get pure { tokens := tokens, kinds := kinds, categories := categories } private def addTokenConfig (tokens : TokenTable) (tk : Token) : Except String TokenTable := do if tk == "" then throw "invalid empty symbol" else match tokens.find? tk with | none => pure $ tokens.insert tk tk | some _ => pure tokens def throwUnknownParserCategory {α} (catName : Name) : ExceptT String Id α := throw s!"unknown parser category '{catName}'" abbrev getCategory (categories : ParserCategories) (catName : Name) : Option ParserCategory := categories.find? catName def addLeadingParser (categories : ParserCategories) (catName : Name) (parserName : Name) (p : Parser) (prio : Nat) : Except String ParserCategories := match getCategory categories catName with | none => throwUnknownParserCategory catName | some cat => let addTokens (tks : List Token) : Except String ParserCategories := let tks := tks.map $ fun tk => Name.mkSimple tk let tables := tks.eraseDups.foldl (fun (tables : PrattParsingTables) tk => { tables with leadingTable := tables.leadingTable.insert tk (p, prio) }) cat.tables pure $ categories.insert catName { cat with tables := tables } match p.info.firstTokens with | FirstTokens.tokens tks => addTokens tks | FirstTokens.optTokens tks => addTokens tks | _ => let tables := { cat.tables with leadingParsers := (p, prio) :: cat.tables.leadingParsers } pure $ categories.insert catName { cat with tables := tables } private def addTrailingParserAux (tables : PrattParsingTables) (p : TrailingParser) (prio : Nat) : PrattParsingTables := let addTokens (tks : List Token) : PrattParsingTables := let tks := tks.map fun tk => Name.mkSimple tk tks.eraseDups.foldl (fun (tables : PrattParsingTables) tk => { tables with trailingTable := tables.trailingTable.insert tk (p, prio) }) tables match p.info.firstTokens with | FirstTokens.tokens tks => addTokens tks | FirstTokens.optTokens tks => addTokens tks | _ => { tables with trailingParsers := (p, prio) :: tables.trailingParsers } def addTrailingParser (categories : ParserCategories) (catName : Name) (p : TrailingParser) (prio : Nat) : Except String ParserCategories := match getCategory categories catName with | none => throwUnknownParserCategory catName | some cat => pure $ categories.insert catName { cat with tables := addTrailingParserAux cat.tables p prio } def addParser (categories : ParserCategories) (catName : Name) (declName : Name) (leading : Bool) (p : Parser) (prio : Nat) : Except String ParserCategories := match leading, p with | true, p => addLeadingParser categories catName declName p prio | false, p => addTrailingParser categories catName p prio def addParserTokens (tokenTable : TokenTable) (info : ParserInfo) : Except String TokenTable := let newTokens := info.collectTokens [] newTokens.foldlM addTokenConfig tokenTable private def updateBuiltinTokens (info : ParserInfo) (declName : Name) : IO Unit := do let tokenTable ← builtinTokenTable.swap {} match addParserTokens tokenTable info with | Except.ok tokenTable => builtinTokenTable.set tokenTable | Except.error msg => throw (IO.userError s!"invalid builtin parser '{declName}', {msg}") def addBuiltinParser (catName : Name) (declName : Name) (leading : Bool) (p : Parser) (prio : Nat) : IO Unit := do let p := evalInsideQuot declName p let categories ← builtinParserCategoriesRef.get let categories ← IO.ofExcept $ addParser categories catName declName leading p prio builtinParserCategoriesRef.set categories builtinSyntaxNodeKindSetRef.modify p.info.collectKinds updateBuiltinTokens p.info declName def addBuiltinLeadingParser (catName : Name) (declName : Name) (p : Parser) (prio : Nat) : IO Unit := addBuiltinParser catName declName true p prio def addBuiltinTrailingParser (catName : Name) (declName : Name) (p : TrailingParser) (prio : Nat) : IO Unit := addBuiltinParser catName declName false p prio def ParserExtension.addEntryImpl (s : State) (e : Entry) : State := match e with | Entry.token tk => match addTokenConfig s.tokens tk with | Except.ok tokens => { s with tokens := tokens } | _ => unreachable! | Entry.kind k => { s with kinds := s.kinds.insert k } | Entry.category catName behavior => if s.categories.contains catName then s else { s with categories := s.categories.insert catName { tables := {}, behavior := behavior } } | Entry.parser catName declName leading parser prio => match addParser s.categories catName declName leading parser prio with | Except.ok categories => { s with categories := categories } | _ => unreachable! unsafe def mkParserOfConstantUnsafe (categories : ParserCategories) (constName : Name) (compileParserDescr : ParserDescr → ImportM Parser) : ImportM (Bool × Parser) := do let env := (← read).env let opts := (← read).opts match env.find? constName with | none => throw ↑s!"unknow constant '{constName}'" | some info => match info.type with | Expr.const `Lean.Parser.TrailingParser _ _ => let p ← IO.ofExcept $ env.evalConst Parser opts constName pure ⟨false, p⟩ | Expr.const `Lean.Parser.Parser _ _ => let p ← IO.ofExcept $ env.evalConst Parser opts constName pure ⟨true, p⟩ | Expr.const `Lean.ParserDescr _ _ => let d ← IO.ofExcept $ env.evalConst ParserDescr opts constName let p ← compileParserDescr d pure ⟨true, p⟩ | Expr.const `Lean.TrailingParserDescr _ _ => let d ← IO.ofExcept $ env.evalConst TrailingParserDescr opts constName let p ← compileParserDescr d pure ⟨false, p⟩ | _ => throw ↑s!"unexpected parser type at '{constName}' (`ParserDescr`, `TrailingParserDescr`, `Parser` or `TrailingParser` expected" @[implementedBy mkParserOfConstantUnsafe] constant mkParserOfConstantAux (categories : ParserCategories) (constName : Name) (compileParserDescr : ParserDescr → ImportM Parser) : ImportM (Bool × Parser) /- Parser aliases for making `ParserDescr` extensible -/ inductive AliasValue (α : Type) where | const (p : α) | unary (p : α → α) | binary (p : α → α → α) abbrev AliasTable (α) := NameMap (AliasValue α) def registerAliasCore {α} (mapRef : IO.Ref (AliasTable α)) (aliasName : Name) (value : AliasValue α) : IO Unit := do unless (← IO.initializing) do throw ↑"aliases can only be registered during initialization" if (← mapRef.get).contains aliasName then throw ↑s!"alias '{aliasName}' has already been declared" mapRef.modify (·.insert aliasName value) def getAlias {α} (mapRef : IO.Ref (AliasTable α)) (aliasName : Name) : IO (Option (AliasValue α)) := do return (← mapRef.get).find? aliasName def getConstAlias {α} (mapRef : IO.Ref (AliasTable α)) (aliasName : Name) : IO α := do match (← getAlias mapRef aliasName) with | some (AliasValue.const v) => pure v | some (AliasValue.unary _) => throw ↑s!"parser '{aliasName}' is not a constant, it takes one argument" | some (AliasValue.binary _) => throw ↑s!"parser '{aliasName}' is not a constant, it takes two arguments" | none => throw ↑s!"parser '{aliasName}' was not found" def getUnaryAlias {α} (mapRef : IO.Ref (AliasTable α)) (aliasName : Name) : IO (α → α) := do match (← getAlias mapRef aliasName) with | some (AliasValue.unary v) => pure v | some _ => throw ↑s!"parser '{aliasName}' does not take one argument" | none => throw ↑s!"parser '{aliasName}' was not found" def getBinaryAlias {α} (mapRef : IO.Ref (AliasTable α)) (aliasName : Name) : IO (α → α → α) := do match (← getAlias mapRef aliasName) with | some (AliasValue.binary v) => pure v | some _ => throw ↑s!"parser '{aliasName}' does not take two arguments" | none => throw ↑s!"parser '{aliasName}' was not found" abbrev ParserAliasValue := AliasValue Parser builtin_initialize parserAliasesRef : IO.Ref (NameMap ParserAliasValue) ← IO.mkRef {} -- Later, we define macro registerParserAlias! which registers a parser, formatter and parenthesizer def registerAlias (aliasName : Name) (p : ParserAliasValue) : IO Unit := do registerAliasCore parserAliasesRef aliasName p instance : Coe Parser ParserAliasValue := { coe := AliasValue.const } instance : Coe (Parser → Parser) ParserAliasValue := { coe := AliasValue.unary } instance : Coe (Parser → Parser → Parser) ParserAliasValue := { coe := AliasValue.binary } def isParserAlias (aliasName : Name) : IO Bool := do match (← getAlias parserAliasesRef aliasName) with | some _ => pure true | _ => pure false def ensureUnaryParserAlias (aliasName : Name) : IO Unit := discard $ getUnaryAlias parserAliasesRef aliasName def ensureBinaryParserAlias (aliasName : Name) : IO Unit := discard $ getBinaryAlias parserAliasesRef aliasName def ensureConstantParserAlias (aliasName : Name) : IO Unit := discard $ getConstAlias parserAliasesRef aliasName partial def compileParserDescr (categories : ParserCategories) (d : ParserDescr) : ImportM Parser := let rec visit : ParserDescr → ImportM Parser | ParserDescr.const n => getConstAlias parserAliasesRef n | ParserDescr.unary n d => return (← getUnaryAlias parserAliasesRef n) (← visit d) | ParserDescr.binary n d₁ d₂ => return (← getBinaryAlias parserAliasesRef n) (← visit d₁) (← visit d₂) | ParserDescr.node k prec d => return leadingNode k prec (← visit d) | ParserDescr.nodeWithAntiquot n k d => return nodeWithAntiquot n k (← visit d) (anonymous := true) | ParserDescr.sepBy p sep psep trail => return sepBy (← visit p) sep (← visit psep) trail | ParserDescr.sepBy1 p sep psep trail => return sepBy1 (← visit p) sep (← visit psep) trail | ParserDescr.trailingNode k prec lhsPrec d => return trailingNode k prec lhsPrec (← visit d) | ParserDescr.symbol tk => return symbol tk | ParserDescr.nonReservedSymbol tk includeIdent => return nonReservedSymbol tk includeIdent | ParserDescr.parser constName => do let (_, p) ← mkParserOfConstantAux categories constName visit; pure p | ParserDescr.cat catName prec => match getCategory categories catName with | some _ => pure $ categoryParser catName prec | none => IO.ofExcept $ throwUnknownParserCategory catName visit d def mkParserOfConstant (categories : ParserCategories) (constName : Name) : ImportM (Bool × Parser) := mkParserOfConstantAux categories constName (compileParserDescr categories) structure ParserAttributeHook where /- Called after a parser attribute is applied to a declaration. -/ postAdd (catName : Name) (declName : Name) (builtin : Bool) : AttrM Unit builtin_initialize parserAttributeHooks : IO.Ref (List ParserAttributeHook) ← IO.mkRef {} def registerParserAttributeHook (hook : ParserAttributeHook) : IO Unit := do parserAttributeHooks.modify fun hooks => hook::hooks def runParserAttributeHooks (catName : Name) (declName : Name) (builtin : Bool) : AttrM Unit := do let hooks ← parserAttributeHooks.get hooks.forM fun hook => hook.postAdd catName declName builtin builtin_initialize registerBuiltinAttribute { name := `runBuiltinParserAttributeHooks, descr := "explicitly run hooks normally activated by builtin parser attributes", add := fun decl stx persistent => do Attribute.Builtin.ensureNoArgs stx runParserAttributeHooks Name.anonymous decl (builtin := true) } builtin_initialize registerBuiltinAttribute { name := `runParserAttributeHooks, descr := "explicitly run hooks normally activated by parser attributes", add := fun decl stx persistent => do Attribute.Builtin.ensureNoArgs stx runParserAttributeHooks Name.anonymous decl (builtin := false) } private def ParserExtension.OLeanEntry.toEntry (s : State) : OLeanEntry → ImportM Entry | token tk => return Entry.token tk | kind k => return Entry.kind k | category c l => return Entry.category c l | parser catName declName prio => do let (leading, p) ← mkParserOfConstant s.categories declName Entry.parser catName declName leading p prio builtin_initialize parserExtension : ParserExtension ← registerScopedEnvExtension { name := `parserExt mkInitial := ParserExtension.mkInitial addEntry := ParserExtension.addEntryImpl toOLeanEntry := ParserExtension.Entry.toOLeanEntry ofOLeanEntry := ParserExtension.OLeanEntry.toEntry } def isParserCategory (env : Environment) (catName : Name) : Bool := (parserExtension.getState env).categories.contains catName def addParserCategory (env : Environment) (catName : Name) (behavior : LeadingIdentBehavior) : Except String Environment := do if isParserCategory env catName then throwParserCategoryAlreadyDefined catName else return parserExtension.addEntry env <| ParserExtension.Entry.category catName behavior def leadingIdentBehavior (env : Environment) (catName : Name) : LeadingIdentBehavior := match getCategory (parserExtension.getState env).categories catName with | none => LeadingIdentBehavior.default | some cat => cat.behavior def mkCategoryAntiquotParser (kind : Name) : Parser := mkAntiquot kind.toString none -- helper decl to work around inlining issue https://github.com/leanprover/lean4/commit/3f6de2af06dd9a25f62294129f64bc05a29ea912#r41340377 @[inline] private def mkCategoryAntiquotParserFn (kind : Name) : ParserFn := (mkCategoryAntiquotParser kind).fn def categoryParserFnImpl (catName : Name) : ParserFn := fun ctx s => let catName := if catName == `syntax then `stx else catName -- temporary Hack let categories := (parserExtension.getState ctx.env).categories match getCategory categories catName with | some cat => prattParser catName cat.tables cat.behavior (mkCategoryAntiquotParserFn catName) ctx s | none => s.mkUnexpectedError ("unknown parser category '" ++ toString catName ++ "'") builtin_initialize categoryParserFnRef.set categoryParserFnImpl def addToken (tk : Token) (kind : AttributeKind) : AttrM Unit := do -- Recall that `ParserExtension.addEntry` is pure, and assumes `addTokenConfig` does not fail. -- So, we must run it here to handle exception. discard <| ofExcept <| addTokenConfig (parserExtension.getState (← getEnv)).tokens tk parserExtension.add (ParserExtension.Entry.token tk) kind def addSyntaxNodeKind (env : Environment) (k : SyntaxNodeKind) : Environment := parserExtension.addEntry env <| ParserExtension.Entry.kind k def isValidSyntaxNodeKind (env : Environment) (k : SyntaxNodeKind) : Bool := let kinds := (parserExtension.getState env).kinds kinds.contains k def getSyntaxNodeKinds (env : Environment) : List SyntaxNodeKind := do let kinds := (parserExtension.getState env).kinds kinds.foldl (fun ks k _ => k::ks) [] def getTokenTable (env : Environment) : TokenTable := (parserExtension.getState env).tokens def mkInputContext (input : String) (fileName : String) : InputContext := { input := input, fileName := fileName, fileMap := input.toFileMap } def mkParserContext (ictx : InputContext) (pmctx : ParserModuleContext) : ParserContext := { prec := 0, toInputContext := ictx, toParserModuleContext := pmctx, tokens := getTokenTable pmctx.env } def mkParserState (input : String) : ParserState := { cache := initCacheForInput input } /- convenience function for testing -/ def runParserCategory (env : Environment) (catName : Name) (input : String) (fileName := "<input>") : Except String Syntax := let c := mkParserContext (mkInputContext input fileName) { env := env, options := {} } let s := mkParserState input let s := whitespace c s let s := categoryParserFnImpl catName c s if s.hasError then Except.error (s.toErrorMsg c) else if input.atEnd s.pos then Except.ok s.stxStack.back else Except.error ((s.mkError "end of input").toErrorMsg c) def declareBuiltinParser (env : Environment) (addFnName : Name) (catName : Name) (declName : Name) (prio : Nat) : IO Environment := let name := `_regBuiltinParser ++ declName let type := mkApp (mkConst `IO) (mkConst `Unit) let val := mkAppN (mkConst addFnName) #[toExpr catName, toExpr declName, mkConst declName, mkRawNatLit prio] let decl := Declaration.defnDecl { name := name, levelParams := [], type := type, value := val, hints := ReducibilityHints.opaque, safety := DefinitionSafety.safe } match env.addAndCompile {} decl with -- TODO: pretty print error | Except.error _ => throw (IO.userError ("failed to emit registration code for builtin parser '" ++ toString declName ++ "'")) | Except.ok env => IO.ofExcept (setBuiltinInitAttr env name) def declareLeadingBuiltinParser (env : Environment) (catName : Name) (declName : Name) (prio : Nat) : IO Environment := -- TODO: use CoreM? declareBuiltinParser env `Lean.Parser.addBuiltinLeadingParser catName declName prio def declareTrailingBuiltinParser (env : Environment) (catName : Name) (declName : Name) (prio : Nat) : IO Environment := -- TODO: use CoreM? declareBuiltinParser env `Lean.Parser.addBuiltinTrailingParser catName declName prio def getParserPriority (args : Syntax) : Except String Nat := match args.getNumArgs with | 0 => pure 0 | 1 => match (args.getArg 0).isNatLit? with | some prio => pure prio | none => throw "invalid parser attribute, numeral expected" | _ => throw "invalid parser attribute, no argument or numeral expected" private def BuiltinParserAttribute.add (attrName : Name) (catName : Name) (declName : Name) (stx : Syntax) (kind : AttributeKind) : AttrM Unit := do let prio ← Attribute.Builtin.getPrio stx unless kind == AttributeKind.global do throwError "invalid attribute '{attrName}', must be global" let decl ← getConstInfo declName let env ← getEnv match decl.type with | Expr.const `Lean.Parser.TrailingParser _ _ => do let env ← declareTrailingBuiltinParser env catName declName prio setEnv env | Expr.const `Lean.Parser.Parser _ _ => do let env ← declareLeadingBuiltinParser env catName declName prio setEnv env | _ => throwError "unexpected parser type at '{declName}' (`Parser` or `TrailingParser` expected)" runParserAttributeHooks catName declName (builtin := true) /- The parsing tables for builtin parsers are "stored" in the extracted source code. -/ def registerBuiltinParserAttribute (attrName : Name) (catName : Name) (behavior := LeadingIdentBehavior.default) : IO Unit := do addBuiltinParserCategory catName behavior registerBuiltinAttribute { name := attrName, descr := "Builtin parser", add := fun declName stx kind => liftM $ BuiltinParserAttribute.add attrName catName declName stx kind, applicationTime := AttributeApplicationTime.afterCompilation } private def ParserAttribute.add (attrName : Name) (catName : Name) (declName : Name) (stx : Syntax) (attrKind : AttributeKind) : AttrM Unit := do let prio ← Attribute.Builtin.getPrio stx let env ← getEnv let opts ← getOptions let categories := (parserExtension.getState env).categories let p ← mkParserOfConstant categories declName let leading := p.1 let parser := p.2 let tokens := parser.info.collectTokens [] tokens.forM fun token => do try addToken token attrKind catch | Exception.error ref msg => throwError "invalid parser '{declName}', {msg}" | ex => throw ex let kinds := parser.info.collectKinds {} kinds.forM fun kind _ => modifyEnv fun env => addSyntaxNodeKind env kind let entry := ParserExtension.Entry.parser catName declName leading parser prio match addParser categories catName declName leading parser prio with | Except.error ex => throwError ex | Except.ok _ => parserExtension.add entry attrKind runParserAttributeHooks catName declName (builtin := false) def mkParserAttributeImpl (attrName : Name) (catName : Name) : AttributeImpl where name := attrName descr := "parser" add declName stx attrKind := ParserAttribute.add attrName catName declName stx attrKind applicationTime := AttributeApplicationTime.afterCompilation /- A builtin parser attribute that can be extended by users. -/ def registerBuiltinDynamicParserAttribute (attrName : Name) (catName : Name) : IO Unit := do registerBuiltinAttribute (mkParserAttributeImpl attrName catName) builtin_initialize registerAttributeImplBuilder `parserAttr fun args => match args with | [DataValue.ofName attrName, DataValue.ofName catName] => pure $ mkParserAttributeImpl attrName catName | _ => throw "invalid parser attribute implementation builder arguments" def registerParserCategory (env : Environment) (attrName : Name) (catName : Name) (behavior := LeadingIdentBehavior.default) : IO Environment := do let env ← IO.ofExcept $ addParserCategory env catName behavior registerAttributeOfBuilder env `parserAttr [DataValue.ofName attrName, DataValue.ofName catName] -- declare `termParser` here since it is used everywhere via antiquotations builtin_initialize registerBuiltinParserAttribute `builtinTermParser `term builtin_initialize registerBuiltinDynamicParserAttribute `termParser `term -- declare `commandParser` to break cyclic dependency builtin_initialize registerBuiltinParserAttribute `builtinCommandParser `command builtin_initialize registerBuiltinDynamicParserAttribute `commandParser `command @[inline] def commandParser (rbp : Nat := 0) : Parser := categoryParser `command rbp def notFollowedByCategoryTokenFn (catName : Name) : ParserFn := fun ctx s => let categories := (parserExtension.getState ctx.env).categories match getCategory categories catName with | none => s.mkUnexpectedError s!"unknown parser category '{catName}'" | some cat => let (s, stx) := peekToken ctx s match stx with | Except.ok (Syntax.atom _ sym) => if ctx.quotDepth > 0 && sym == "$" then s else match cat.tables.leadingTable.find? (Name.mkSimple sym) with | some _ => s.mkUnexpectedError (toString catName) | _ => s | Except.ok _ => s | Except.error _ => s @[inline] def notFollowedByCategoryToken (catName : Name) : Parser := { fn := notFollowedByCategoryTokenFn catName } abbrev notFollowedByCommandToken : Parser := notFollowedByCategoryToken `command abbrev notFollowedByTermToken : Parser := notFollowedByCategoryToken `term end Parser end Lean
7f3497aa5f01445a25ee0e17342e38d946f33d01
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/graded_object.lean
80fe7b9126dc9cc7422c0fed9fdbea2debbcc93f
[ "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,819
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_power.lemmas import category_theory.pi.basic import category_theory.shift import category_theory.concrete_category.basic /-! # The category of graded objects For any type `β`, a `β`-graded object over some category `C` is just a function `β → C` into the objects of `C`. We put the "pointwise" category structure on these, as the non-dependent specialization of `category_theory.pi`. We describe the `comap` functors obtained by precomposing with functions `β → γ`. As a consequence a fixed element (e.g. `1`) in an additive group `β` provides a shift functor on `β`-graded objects When `C` has coproducts we construct the `total` functor `graded_object β C ⥤ C`, show that it is faithful, and deduce that when `C` is concrete so is `graded_object β C`. -/ open category_theory.pi open category_theory.limits namespace category_theory universes w v u /-- A type synonym for `β → C`, used for `β`-graded objects in a category `C`. -/ def graded_object (β : Type w) (C : Type u) : Type (max w u) := β → C -- Satisfying the inhabited linter... instance inhabited_graded_object (β : Type w) (C : Type u) [inhabited C] : inhabited (graded_object β C) := ⟨λ b, inhabited.default⟩ /-- A type synonym for `β → C`, used for `β`-graded objects in a category `C` with a shift functor given by translation by `s`. -/ @[nolint unused_arguments] -- `s` is here to distinguish type synonyms asking for different shifts abbreviation graded_object_with_shift {β : Type w} [add_comm_group β] (s : β) (C : Type u) : Type (max w u) := graded_object β C namespace graded_object variables {C : Type u} [category.{v} C] instance category_of_graded_objects (β : Type w) : category.{max w v} (graded_object β C) := category_theory.pi (λ _, C) /-- The projection of a graded object to its `i`-th component. -/ @[simps] def eval {β : Type w} (b : β) : graded_object β C ⥤ C := { obj := λ X, X b, map := λ X Y f, f b, } section variable (C) /-- The natural isomorphism comparing between pulling back along two propositionally equal functions. -/ @[simps] def comap_eq {β γ : Type w} {f g : β → γ} (h : f = g) : comap (λ _, C) f ≅ comap (λ _, C) g := { hom := { app := λ X b, eq_to_hom begin dsimp [comap], subst h, end }, inv := { app := λ X b, eq_to_hom begin dsimp [comap], subst h, end }, } lemma comap_eq_symm {β γ : Type w} {f g : β → γ} (h : f = g) : comap_eq C h.symm = (comap_eq C h).symm := by tidy lemma comap_eq_trans {β γ : Type w} {f g h : β → γ} (k : f = g) (l : g = h) : comap_eq C (k.trans l) = comap_eq C k ≪≫ comap_eq C l := begin ext X b, simp, end @[simp] lemma eq_to_hom_apply {β : Type w} {X Y : Π b : β, C} (h : X = Y) (b : β) : (eq_to_hom h : X ⟶ Y) b = eq_to_hom (by subst h) := by { subst h, refl } /-- The equivalence between β-graded objects and γ-graded objects, given an equivalence between β and γ. -/ @[simps] def comap_equiv {β γ : Type w} (e : β ≃ γ) : (graded_object β C) ≌ (graded_object γ C) := { functor := comap (λ _, C) (e.symm : γ → β), inverse := comap (λ _, C) (e : β → γ), counit_iso := (comap_comp (λ _, C) _ _).trans (comap_eq C (by { ext, simp } )), unit_iso := (comap_eq C (by { ext, simp } )).trans (comap_comp _ _ _).symm, functor_unit_iso_comp' := λ X, by { ext b, dsimp, simp, }, } -- See note [dsimp, simp]. end instance has_shift {β : Type*} [add_comm_group β] (s : β) : has_shift (graded_object_with_shift s C) ℤ := has_shift_mk _ _ { F := λ n, comap (λ _, C) $ λ (b : β), b + n • s, ε := (comap_id β (λ _, C)).symm ≪≫ (comap_eq C (by { ext, simp })), μ := λ m n, comap_comp _ _ _ ≪≫ comap_eq C (by { ext, simp [add_zsmul, add_comm] }), left_unitality := by { introv, ext, dsimp, simpa }, right_unitality := by { introv, ext, dsimp, simpa }, associativity := by { introv, ext, dsimp, simp } } @[simp] lemma shift_functor_obj_apply {β : Type*} [add_comm_group β] (s : β) (X : β → C) (t : β) (n : ℤ) : (shift_functor (graded_object_with_shift s C) n).obj X t = X (t + n • s) := rfl @[simp] lemma shift_functor_map_apply {β : Type*} [add_comm_group β] (s : β) {X Y : graded_object_with_shift s C} (f : X ⟶ Y) (t : β) (n : ℤ) : (shift_functor (graded_object_with_shift s C) n).map f t = f (t + n • s) := rfl instance has_zero_morphisms [has_zero_morphisms C] (β : Type w) : has_zero_morphisms.{max w v} (graded_object β C) := { has_zero := λ X Y, { zero := λ b, 0 } } @[simp] lemma zero_apply [has_zero_morphisms C] (β : Type w) (X Y : graded_object β C) (b : β) : (0 : X ⟶ Y) b = 0 := rfl section open_locale zero_object instance has_zero_object [has_zero_object C] [has_zero_morphisms C] (β : Type w) : has_zero_object.{max w v} (graded_object β C) := by { refine ⟨⟨λ b, 0, λ X, ⟨⟨⟨λ b, 0⟩, λ f, _⟩⟩, λ X, ⟨⟨⟨λ b, 0⟩, λ f, _⟩⟩⟩⟩; ext, } end end graded_object namespace graded_object -- The universes get a little hairy here, so we restrict the universe level for the grading to 0. -- Since we're typically interested in grading by ℤ or a finite group, this should be okay. -- If you're grading by things in higher universes, have fun! variables (β : Type) variables (C : Type u) [category.{v} C] variables [has_coproducts.{0} C] section local attribute [tidy] tactic.discrete_cases /-- The total object of a graded object is the coproduct of the graded components. -/ noncomputable def total : graded_object β C ⥤ C := { obj := λ X, ∐ (λ i : β, X i), map := λ X Y f, limits.sigma.map (λ i, f i) }. end variables [has_zero_morphisms C] /-- The `total` functor taking a graded object to the coproduct of its graded components is faithful. To prove this, we need to know that the coprojections into the coproduct are monomorphisms, which follows from the fact we have zero morphisms and decidable equality for the grading. -/ instance : faithful (total β C) := { map_injective' := λ X Y f g w, begin classical, ext i, replace w := sigma.ι (λ i : β, X i) i ≫= w, erw [colimit.ι_map, colimit.ι_map] at w, simp at *, exact mono.right_cancellation _ _ w, end } end graded_object namespace graded_object noncomputable theory variables (β : Type) variables (C : Type (u+1)) [large_category C] [concrete_category C] [has_coproducts.{0} C] [has_zero_morphisms C] instance : concrete_category (graded_object β C) := { forget := total β C ⋙ forget C } instance : has_forget₂ (graded_object β C) C := { forget₂ := total β C } end graded_object end category_theory
bd8b92f8f18799faa280750df9dd2e700a234697
9dc8cecdf3c4634764a18254e94d43da07142918
/src/measure_theory/function/uniform_integrable.lean
12a46e9d26327c9b3e1fb3b8ebbafc786c960b90
[ "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
48,623
lean
/- Copyright (c) 2022 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying -/ import measure_theory.function.convergence_in_measure /-! # Uniform integrability This file contains the definitions for uniform integrability (both in the measure theory sense as well as the probability theory sense). This file also contains the Vitali convergence theorem which estabishes a relation between uniform integrability, convergence in measure and Lp convergence. Uniform integrability plays a vital role in the theory of martingales most notably is used to fomulate the martingale convergence theorem. ## Main definitions * `measure_theory.unif_integrable`: uniform integrability in the measure theory sense. In particular, a sequence of functions `f` is uniformly integrable if for all `ε > 0`, there exists some `δ > 0` such that for all sets `s` of smaller measure than `δ`, the Lp-norm of `f i` restricted `s` is smaller than `ε` for all `i`. * `measure_theory.uniform_integrable`: uniform integrability in the probability theory sense. In particular, a sequence of measurable functions `f` is uniformly integrable in the probability theory sense if it is uniformly integrable in the measure theory sense and has uniformly bounded Lp-norm. # Main results * `measure_theory.unif_integrable_fintype`: a finite sequence of Lp functions is uniformly integrable. * `measure_theory.tendsto_Lp_of_tendsto_ae`: a sequence of Lp functions which is uniformly integrable converges in Lp if they converge almost everywhere. * `measure_theory.tendsto_in_measure_iff_tendsto_Lp`: Vitali convergence theorem: a sequence of Lp functions converges in Lp if and only if it is uniformly integrable and converges in measure. ## Tags uniform integrable, uniformly absolutely continuous integral, Vitali convergence theorem -/ noncomputable theory open_locale classical measure_theory nnreal ennreal topological_space big_operators namespace measure_theory open set filter topological_space variables {α β ι : Type*} {m : measurable_space α} {μ : measure α} [normed_add_comm_group β] /-- Uniform integrability in the measure theory sense. A sequence of functions `f` is said to be uniformly integrable if for all `ε > 0`, there exists some `δ > 0` such that for all sets `s` with measure less than `δ`, the Lp-norm of `f i` restricted on `s` is less than `ε`. Uniform integrablility is also known as uniformly absolutely continuous integrals. -/ def unif_integrable {m : measurable_space α} (f : ι → α → β) (p : ℝ≥0∞) (μ : measure α) : Prop := ∀ ⦃ε : ℝ⦄ (hε : 0 < ε), ∃ (δ : ℝ) (hδ : 0 < δ), ∀ i s, measurable_set s → μ s ≤ ennreal.of_real δ → snorm (s.indicator (f i)) p μ ≤ ennreal.of_real ε /-- In probability theory, a family of measurable functions is uniformly integrable if it is uniformly integrable in the measure theory sense and is uniformly bounded. -/ def uniform_integrable {m : measurable_space α} (f : ι → α → β) (p : ℝ≥0∞) (μ : measure α) : Prop := (∀ i, ae_strongly_measurable (f i) μ) ∧ unif_integrable f p μ ∧ ∃ C : ℝ≥0, ∀ i, snorm (f i) p μ ≤ C namespace uniform_integrable protected lemma ae_strongly_measurable {f : ι → α → β} {p : ℝ≥0∞} (hf : uniform_integrable f p μ) (i : ι) : ae_strongly_measurable (f i) μ := hf.1 i protected lemma unif_integrable {f : ι → α → β} {p : ℝ≥0∞} (hf : uniform_integrable f p μ) : unif_integrable f p μ := hf.2.1 protected lemma mem_ℒp {f : ι → α → β} {p : ℝ≥0∞} (hf : uniform_integrable f p μ) (i : ι) : mem_ℒp (f i) p μ := ⟨hf.1 i, let ⟨_, _, hC⟩ := hf.2 in lt_of_le_of_lt (hC i) ennreal.coe_lt_top⟩ end uniform_integrable section unif_integrable /-! ### `unif_integrable` This section deals with uniform integrability in the measure theory sense. -/ namespace unif_integrable variables {f g : ι → α → β} {p : ℝ≥0∞} protected lemma add (hf : unif_integrable f p μ) (hg : unif_integrable g p μ) (hp : 1 ≤ p) (hf_meas : ∀ i, ae_strongly_measurable (f i) μ) (hg_meas : ∀ i, ae_strongly_measurable (g i) μ) : unif_integrable (f + g) p μ := begin intros ε hε, have hε2 : 0 < ε / 2 := half_pos hε, obtain ⟨δ₁, hδ₁_pos, hfδ₁⟩ := hf hε2, obtain ⟨δ₂, hδ₂_pos, hgδ₂⟩ := hg hε2, refine ⟨min δ₁ δ₂, lt_min hδ₁_pos hδ₂_pos, λ i s hs hμs, _⟩, simp_rw [pi.add_apply, indicator_add'], refine (snorm_add_le ((hf_meas i).indicator hs) ((hg_meas i).indicator hs) hp).trans _, have hε_halves : ennreal.of_real ε = ennreal.of_real (ε / 2) + ennreal.of_real (ε / 2), by rw [← ennreal.of_real_add hε2.le hε2.le, add_halves], rw hε_halves, exact add_le_add (hfδ₁ i s hs (hμs.trans (ennreal.of_real_le_of_real (min_le_left _ _)))) (hgδ₂ i s hs (hμs.trans (ennreal.of_real_le_of_real (min_le_right _ _)))), end protected lemma neg (hf : unif_integrable f p μ) : unif_integrable (-f) p μ := by { simp_rw [unif_integrable, pi.neg_apply, indicator_neg', snorm_neg], exact hf, } protected lemma sub (hf : unif_integrable f p μ) (hg : unif_integrable g p μ) (hp : 1 ≤ p) (hf_meas : ∀ i, ae_strongly_measurable (f i) μ) (hg_meas : ∀ i, ae_strongly_measurable (g i) μ) : unif_integrable (f - g) p μ := by { rw sub_eq_add_neg, exact hf.add hg.neg hp hf_meas (λ i, (hg_meas i).neg), } protected lemma ae_eq (hf : unif_integrable f p μ) (hfg : ∀ n, f n =ᵐ[μ] g n) : unif_integrable g p μ := begin intros ε hε, obtain ⟨δ, hδ_pos, hfδ⟩ := hf hε, refine ⟨δ, hδ_pos, λ n s hs hμs, (le_of_eq $ snorm_congr_ae _).trans (hfδ n s hs hμs)⟩, filter_upwards [hfg n] with x hx, simp_rw [indicator_apply, hx], end end unif_integrable lemma unif_integrable_zero_meas [measurable_space α] {p : ℝ≥0∞} {f : ι → α → β} : unif_integrable f p (0 : measure α) := λ ε hε, ⟨1, one_pos, λ i s hs hμs, by simp⟩ lemma unif_integrable_congr_ae {p : ℝ≥0∞} {f g : ι → α → β} (hfg : ∀ n, f n =ᵐ[μ] g n) : unif_integrable f p μ ↔ unif_integrable g p μ := ⟨λ hf, hf.ae_eq hfg, λ hg, hg.ae_eq (λ n, (hfg n).symm)⟩ lemma tendsto_indicator_ge (f : α → β) (x : α): tendsto (λ M : ℕ, {x | (M : ℝ) ≤ ∥f x∥₊}.indicator f x) at_top (𝓝 0) := begin refine @tendsto_at_top_of_eventually_const _ _ _ _ _ _ _ (nat.ceil (∥f x∥₊ : ℝ) + 1) (λ n hn, _), rw indicator_of_not_mem, simp only [not_le, mem_set_of_eq], refine lt_of_le_of_lt (nat.le_ceil _) _, refine lt_of_lt_of_le (lt_add_one _) _, norm_cast, rwa [ge_iff_le, coe_nnnorm] at hn, end variables (μ) {p : ℝ≥0∞} section variables {f : α → β} /-- This lemma is weaker than `measure_theory.mem_ℒp.integral_indicator_norm_ge_nonneg_le` as the latter provides `0 ≤ M` and does not require the measurability of `f`. -/ lemma mem_ℒp.integral_indicator_norm_ge_le (hf : mem_ℒp f 1 μ) (hmeas : strongly_measurable f) {ε : ℝ} (hε : 0 < ε) : ∃ M : ℝ, ∫⁻ x, ∥{x | M ≤ ∥f x∥₊}.indicator f x∥₊ ∂μ ≤ ennreal.of_real ε := begin have htendsto : ∀ᵐ x ∂μ, tendsto (λ M : ℕ, {x | (M : ℝ) ≤ ∥f x∥₊}.indicator f x) at_top (𝓝 0) := univ_mem' (id $ λ x, tendsto_indicator_ge f x), have hmeas : ∀ M : ℕ, ae_strongly_measurable ({x | (M : ℝ) ≤ ∥f x∥₊}.indicator f) μ, { assume M, apply hf.1.indicator, apply strongly_measurable.measurable_set_le strongly_measurable_const hmeas.nnnorm.measurable.coe_nnreal_real.strongly_measurable }, have hbound : has_finite_integral (λ x, ∥f x∥) μ, { rw mem_ℒp_one_iff_integrable at hf, exact hf.norm.2 }, have := tendsto_lintegral_norm_of_dominated_convergence hmeas hbound _ htendsto, { rw ennreal.tendsto_at_top_zero at this, obtain ⟨M, hM⟩ := this (ennreal.of_real ε) (ennreal.of_real_pos.2 hε), simp only [true_and, ge_iff_le, zero_tsub, zero_le, sub_zero, zero_add, coe_nnnorm, mem_Icc] at hM, refine ⟨M, _⟩, convert hM M le_rfl, ext1 x, simp only [coe_nnnorm, ennreal.of_real_eq_coe_nnreal (norm_nonneg _)], refl }, { refine λ n, univ_mem' (id $ λ x, _), by_cases hx : (n : ℝ) ≤ ∥f x∥, { dsimp, rwa indicator_of_mem }, { dsimp, rw [indicator_of_not_mem, norm_zero], { exact norm_nonneg _ }, { assumption } } } end /-- This lemma is superceded by `measure_theory.mem_ℒp.integral_indicator_norm_ge_nonneg_le` which does not require measurability. -/ lemma mem_ℒp.integral_indicator_norm_ge_nonneg_le_of_meas (hf : mem_ℒp f 1 μ) (hmeas : strongly_measurable f) {ε : ℝ} (hε : 0 < ε) : ∃ M : ℝ, 0 ≤ M ∧ ∫⁻ x, ∥{x | M ≤ ∥f x∥₊}.indicator f x∥₊ ∂μ ≤ ennreal.of_real ε := let ⟨M, hM⟩ := hf.integral_indicator_norm_ge_le μ hmeas hε in ⟨max M 0, le_max_right _ _, by simpa⟩ lemma mem_ℒp.integral_indicator_norm_ge_nonneg_le (hf : mem_ℒp f 1 μ) {ε : ℝ} (hε : 0 < ε) : ∃ M : ℝ, 0 ≤ M ∧ ∫⁻ x, ∥{x | M ≤ ∥f x∥₊}.indicator f x∥₊ ∂μ ≤ ennreal.of_real ε := begin have hf_mk : mem_ℒp (hf.1.mk f) 1 μ := (mem_ℒp_congr_ae hf.1.ae_eq_mk).mp hf, obtain ⟨M, hM_pos, hfM⟩ := hf_mk.integral_indicator_norm_ge_nonneg_le_of_meas μ hf.1.strongly_measurable_mk hε, refine ⟨M, hM_pos, (le_of_eq _).trans hfM⟩, refine lintegral_congr_ae _, filter_upwards [hf.1.ae_eq_mk] with x hx, simp only [indicator_apply, coe_nnnorm, mem_set_of_eq, ennreal.coe_eq_coe, hx.symm], end lemma mem_ℒp.snorm_ess_sup_indicator_norm_ge_eq_zero (hf : mem_ℒp f ∞ μ) (hmeas : strongly_measurable f) : ∃ M : ℝ, snorm_ess_sup ({x | M ≤ ∥f x∥₊}.indicator f) μ = 0 := begin have hbdd : snorm_ess_sup f μ < ∞ := hf.snorm_lt_top, refine ⟨(snorm f ∞ μ + 1).to_real, _⟩, rw snorm_ess_sup_indicator_eq_snorm_ess_sup_restrict, have : μ.restrict {x : α | (snorm f ⊤ μ + 1).to_real ≤ ∥f x∥₊} = 0, { simp only [coe_nnnorm, snorm_exponent_top, measure.restrict_eq_zero], have : {x : α | (snorm_ess_sup f μ + 1).to_real ≤ ∥f x∥} ⊆ {x : α | snorm_ess_sup f μ < ∥f x∥₊}, { intros x hx, rw [mem_set_of_eq, ← ennreal.to_real_lt_to_real hbdd.ne ennreal.coe_lt_top.ne, ennreal.coe_to_real, coe_nnnorm], refine lt_of_lt_of_le _ hx, rw ennreal.to_real_lt_to_real hbdd.ne, { exact ennreal.lt_add_right hbdd.ne one_ne_zero }, { exact (ennreal.add_lt_top.2 ⟨hbdd, ennreal.one_lt_top⟩).ne } }, rw ← nonpos_iff_eq_zero, refine (measure_mono this).trans _, have hle := coe_nnnorm_ae_le_snorm_ess_sup f μ, simp_rw [ae_iff, not_le] at hle, exact nonpos_iff_eq_zero.2 hle }, rw [this, snorm_ess_sup_measure_zero], exact measurable_set_le measurable_const hmeas.nnnorm.measurable.subtype_coe, end /- This lemma is slightly weaker than `measure_theory.mem_ℒp.snorm_indicator_norm_ge_pos_le` as the latter provides `0 < M`. -/ lemma mem_ℒp.snorm_indicator_norm_ge_le (hf : mem_ℒp f p μ) (hmeas : strongly_measurable f) {ε : ℝ} (hε : 0 < ε) : ∃ M : ℝ, snorm ({x | M ≤ ∥f x∥₊}.indicator f) p μ ≤ ennreal.of_real ε := begin by_cases hp_ne_zero : p = 0, { refine ⟨1, hp_ne_zero.symm ▸ _⟩, simp [snorm_exponent_zero] }, by_cases hp_ne_top : p = ∞, { subst hp_ne_top, obtain ⟨M, hM⟩ := hf.snorm_ess_sup_indicator_norm_ge_eq_zero μ hmeas, refine ⟨M, _⟩, simp only [snorm_exponent_top, hM, zero_le] }, obtain ⟨M, hM', hM⟩ := @mem_ℒp.integral_indicator_norm_ge_nonneg_le _ _ _ μ _ (λ x, ∥f x∥^p.to_real) (hf.norm_rpow hp_ne_zero hp_ne_top) _ (real.rpow_pos_of_pos hε p.to_real), refine ⟨M ^(1 / p.to_real), _⟩, rw [snorm_eq_lintegral_rpow_nnnorm hp_ne_zero hp_ne_top, ← ennreal.rpow_one (ennreal.of_real ε)], conv_rhs { rw ← mul_one_div_cancel (ennreal.to_real_pos hp_ne_zero hp_ne_top).ne.symm }, rw [ennreal.rpow_mul, ennreal.rpow_le_rpow_iff (one_div_pos.2 $ ennreal.to_real_pos hp_ne_zero hp_ne_top), ennreal.of_real_rpow_of_pos hε], convert hM, ext1 x, rw [ennreal.coe_rpow_of_nonneg _ ennreal.to_real_nonneg, nnnorm_indicator_eq_indicator_nnnorm, nnnorm_indicator_eq_indicator_nnnorm], have hiff : M ^ (1 / p.to_real) ≤ ∥f x∥₊ ↔ M ≤ ∥∥f x∥ ^ p.to_real∥₊, { rw [coe_nnnorm, coe_nnnorm, real.norm_rpow_of_nonneg (norm_nonneg _), norm_norm, ← real.rpow_le_rpow_iff hM' (real.rpow_nonneg_of_nonneg (norm_nonneg _) _) (one_div_pos.2 $ ennreal.to_real_pos hp_ne_zero hp_ne_top), ← real.rpow_mul (norm_nonneg _), mul_one_div_cancel (ennreal.to_real_pos hp_ne_zero hp_ne_top).ne.symm, real.rpow_one] }, by_cases hx : x ∈ {x : α | M ^ (1 / p.to_real) ≤ ∥f x∥₊}, { rw [set.indicator_of_mem hx,set.indicator_of_mem, real.nnnorm_of_nonneg], refl, change _ ≤ _, rwa ← hiff }, { rw [set.indicator_of_not_mem hx, set.indicator_of_not_mem], { simp [(ennreal.to_real_pos hp_ne_zero hp_ne_top).ne.symm] }, { change ¬ _ ≤ _, rwa ← hiff } } end /-- This lemma implies that a single function is uniformly integrable (in the probability sense). -/ lemma mem_ℒp.snorm_indicator_norm_ge_pos_le (hf : mem_ℒp f p μ) (hmeas : strongly_measurable f) {ε : ℝ} (hε : 0 < ε) : ∃ M : ℝ, 0 < M ∧ snorm ({x | M ≤ ∥f x∥₊}.indicator f) p μ ≤ ennreal.of_real ε := begin obtain ⟨M, hM⟩ := hf.snorm_indicator_norm_ge_le μ hmeas hε, refine ⟨max M 1, lt_of_lt_of_le zero_lt_one (le_max_right _ _), le_trans (snorm_mono (λ x, _)) hM⟩, rw [norm_indicator_eq_indicator_norm, norm_indicator_eq_indicator_norm], refine indicator_le_indicator_of_subset (λ x hx, _) (λ x, norm_nonneg _) x, change max _ _ ≤ _ at hx, -- removing the `change` breaks the proof! exact (max_le_iff.1 hx).1, end end lemma snorm_indicator_le_of_bound {f : α → β} (hp_top : p ≠ ∞) {ε : ℝ} (hε : 0 < ε) {M : ℝ} (hf : ∀ x, ∥f x∥ < M) : ∃ (δ : ℝ) (hδ : 0 < δ), ∀ s, measurable_set s → μ s ≤ ennreal.of_real δ → snorm (s.indicator f) p μ ≤ ennreal.of_real ε := begin by_cases hM : M ≤ 0, { refine ⟨1, zero_lt_one, λ s hs hμ, _⟩, rw (_ : f = 0), { simp [hε.le] }, { ext x, rw [pi.zero_apply, ← norm_le_zero_iff], exact (lt_of_lt_of_le (hf x) hM).le } }, rw not_le at hM, refine ⟨(ε / M) ^ p.to_real, real.rpow_pos_of_pos (div_pos hε hM) _, λ s hs hμ, _⟩, by_cases hp : p = 0, { simp [hp] }, rw snorm_indicator_eq_snorm_restrict hs, have haebdd : ∀ᵐ x ∂μ.restrict s, ∥f x∥ ≤ M, { filter_upwards, exact (λ x, (hf x).le) }, refine le_trans (snorm_le_of_ae_bound haebdd) _, rw [measure.restrict_apply measurable_set.univ, univ_inter, ← ennreal.le_div_iff_mul_le (or.inl _) (or.inl ennreal.of_real_ne_top)], { rw [← one_div, ennreal.rpow_one_div_le_iff (ennreal.to_real_pos hp hp_top)], refine le_trans hμ _, rw [← ennreal.of_real_rpow_of_pos (div_pos hε hM), ennreal.rpow_le_rpow_iff (ennreal.to_real_pos hp hp_top), ennreal.of_real_div_of_pos hM], exact le_rfl }, { simpa only [ennreal.of_real_eq_zero, not_le, ne.def] }, end section variables {f : α → β} /-- Auxiliary lemma for `measure_theory.mem_ℒp.snorm_indicator_le`. -/ lemma mem_ℒp.snorm_indicator_le' (hp_one : 1 ≤ p) (hp_top : p ≠ ∞) (hf : mem_ℒp f p μ) (hmeas : strongly_measurable f) {ε : ℝ} (hε : 0 < ε) : ∃ (δ : ℝ) (hδ : 0 < δ), ∀ s, measurable_set s → μ s ≤ ennreal.of_real δ → snorm (s.indicator f) p μ ≤ 2 * ennreal.of_real ε := begin obtain ⟨M, hMpos, hM⟩ := hf.snorm_indicator_norm_ge_pos_le μ hmeas hε, obtain ⟨δ, hδpos, hδ⟩ := @snorm_indicator_le_of_bound _ _ _ μ _ _ ({x | ∥f x∥ < M}.indicator f) hp_top _ hε M _, { refine ⟨δ, hδpos, λ s hs hμs, _⟩, rw (_ : f = {x : α | M ≤ ∥f x∥₊}.indicator f + {x : α | ∥f x∥ < M}.indicator f), { rw snorm_indicator_eq_snorm_restrict hs, refine le_trans (snorm_add_le _ _ hp_one) _, { exact strongly_measurable.ae_strongly_measurable (hmeas.indicator (measurable_set_le measurable_const hmeas.nnnorm.measurable.subtype_coe)) }, { exact strongly_measurable.ae_strongly_measurable (hmeas.indicator (measurable_set_lt hmeas.nnnorm.measurable.subtype_coe measurable_const)) }, { rw two_mul, refine add_le_add (le_trans (snorm_mono_measure _ measure.restrict_le_self) hM) _, rw ← snorm_indicator_eq_snorm_restrict hs, exact hδ s hs hμs } }, { ext x, by_cases hx : M ≤ ∥f x∥, { rw [pi.add_apply, indicator_of_mem, indicator_of_not_mem, add_zero]; simpa }, { rw [pi.add_apply, indicator_of_not_mem, indicator_of_mem, zero_add]; simpa using hx } } }, { intros x, rw [norm_indicator_eq_indicator_norm, indicator_apply], split_ifs, exacts [h, hMpos] } end /-- This lemma is superceded by `measure_theory.mem_ℒp.snorm_indicator_le` which does not require measurability on `f`. -/ lemma mem_ℒp.snorm_indicator_le_of_meas (hp_one : 1 ≤ p) (hp_top : p ≠ ∞) (hf : mem_ℒp f p μ) (hmeas : strongly_measurable f) {ε : ℝ} (hε : 0 < ε) : ∃ (δ : ℝ) (hδ : 0 < δ), ∀ s, measurable_set s → μ s ≤ ennreal.of_real δ → snorm (s.indicator f) p μ ≤ ennreal.of_real ε := begin obtain ⟨δ, hδpos, hδ⟩ := hf.snorm_indicator_le' μ hp_one hp_top hmeas (half_pos hε), refine ⟨δ, hδpos, λ s hs hμs, le_trans (hδ s hs hμs) _⟩, rw [ennreal.of_real_div_of_pos zero_lt_two, (by norm_num : ennreal.of_real 2 = 2), ennreal.mul_div_cancel']; norm_num, end lemma mem_ℒp.snorm_indicator_le (hp_one : 1 ≤ p) (hp_top : p ≠ ∞) (hf : mem_ℒp f p μ) {ε : ℝ} (hε : 0 < ε) : ∃ (δ : ℝ) (hδ : 0 < δ), ∀ s, measurable_set s → μ s ≤ ennreal.of_real δ → snorm (s.indicator f) p μ ≤ ennreal.of_real ε := begin have hℒp := hf, obtain ⟨⟨f', hf', heq⟩, hnorm⟩ := hf, obtain ⟨δ, hδpos, hδ⟩ := (hℒp.ae_eq heq).snorm_indicator_le_of_meas μ hp_one hp_top hf' hε, refine ⟨δ, hδpos, λ s hs hμs, _⟩, convert hδ s hs hμs using 1, rw [snorm_indicator_eq_snorm_restrict hs, snorm_indicator_eq_snorm_restrict hs], refine snorm_congr_ae heq.restrict, end /-- A constant function is uniformly integrable. -/ lemma unif_integrable_const {g : α → β} (hp : 1 ≤ p) (hp_ne_top : p ≠ ∞) (hg : mem_ℒp g p μ) : unif_integrable (λ n : ι, g) p μ := begin intros ε hε, obtain ⟨δ, hδ_pos, hgδ⟩ := hg.snorm_indicator_le μ hp hp_ne_top hε, exact ⟨δ, hδ_pos, λ i, hgδ⟩, end /-- A single function is uniformly integrable. -/ lemma unif_integrable_subsingleton [subsingleton ι] (hp_one : 1 ≤ p) (hp_top : p ≠ ∞) {f : ι → α → β} (hf : ∀ i, mem_ℒp (f i) p μ) : unif_integrable f p μ := begin intros ε hε, by_cases hι : nonempty ι, { cases hι with i, obtain ⟨δ, hδpos, hδ⟩ := (hf i).snorm_indicator_le μ hp_one hp_top hε, refine ⟨δ, hδpos, λ j s hs hμs, _⟩, convert hδ s hs hμs }, { exact ⟨1, zero_lt_one, λ i, false.elim $ hι $ nonempty.intro i⟩ } end /-- This lemma is less general than `measure_theory.unif_integrable_fintype` which applies to all sequences indexed by a finite type. -/ lemma unif_integrable_fin (hp_one : 1 ≤ p) (hp_top : p ≠ ∞) {n : ℕ} {f : fin n → α → β} (hf : ∀ i, mem_ℒp (f i) p μ) : unif_integrable f p μ := begin revert f, induction n with n h, { exact (λ f hf, unif_integrable_subsingleton μ hp_one hp_top hf) }, intros f hfLp ε hε, set g : fin n → α → β := λ k, f k with hg, have hgLp : ∀ i, mem_ℒp (g i) p μ := λ i, hfLp i, obtain ⟨δ₁, hδ₁pos, hδ₁⟩ := h hgLp hε, obtain ⟨δ₂, hδ₂pos, hδ₂⟩ := (hfLp n).snorm_indicator_le μ hp_one hp_top hε, refine ⟨min δ₁ δ₂, lt_min hδ₁pos hδ₂pos, λ i s hs hμs, _⟩, by_cases hi : i.val < n, { rw (_ : f i = g ⟨i.val, hi⟩), { exact hδ₁ _ s hs (le_trans hμs $ ennreal.of_real_le_of_real $ min_le_left _ _) }, { rw hg, simp } }, { rw (_ : i = n), { exact hδ₂ _ hs (le_trans hμs $ ennreal.of_real_le_of_real $ min_le_right _ _) }, { have hi' := fin.is_lt i, rw nat.lt_succ_iff at hi', rw not_lt at hi, simp [← le_antisymm hi' hi] } } end /-- A finite sequence of Lp functions is uniformly integrable. -/ lemma unif_integrable_finite [finite ι] (hp_one : 1 ≤ p) (hp_top : p ≠ ∞) {f : ι → α → β} (hf : ∀ i, mem_ℒp (f i) p μ) : unif_integrable f p μ := begin obtain ⟨n, hn⟩ := finite.exists_equiv_fin ι, intros ε hε, set g : fin n → α → β := f ∘ hn.some.symm with hgeq, have hg : ∀ i, mem_ℒp (g i) p μ := λ _, hf _, obtain ⟨δ, hδpos, hδ⟩ := unif_integrable_fin μ hp_one hp_top hg hε, refine ⟨δ, hδpos, λ i s hs hμs, _⟩, specialize hδ (hn.some i) s hs hμs, simp_rw [hgeq, function.comp_app, equiv.symm_apply_apply] at hδ, assumption, end end lemma snorm_sub_le_of_dist_bdd {p : ℝ≥0∞} (hp' : p ≠ ∞) {s : set α} (hs : measurable_set[m] s) {f g : α → β} {c : ℝ} (hc : 0 ≤ c) (hf : ∀ x ∈ s, dist (f x) (g x) ≤ c) : snorm (s.indicator (f - g)) p μ ≤ ennreal.of_real c * μ s ^ (1 / p.to_real) := begin by_cases hp : p = 0, { simp [hp], }, have : ∀ x, ∥s.indicator (f - g) x∥ ≤ ∥s.indicator (λ x, c) x∥, { intro x, by_cases hx : x ∈ s, { rw [indicator_of_mem hx, indicator_of_mem hx, pi.sub_apply, ← dist_eq_norm, real.norm_eq_abs, abs_of_nonneg hc], exact hf x hx }, { simp [indicator_of_not_mem hx] } }, refine le_trans (snorm_mono this) _, rw snorm_indicator_const hs hp hp', refine ennreal.mul_le_mul (le_of_eq _) le_rfl, rw [← of_real_norm_eq_coe_nnnorm, real.norm_eq_abs, abs_of_nonneg hc], end /-- A sequence of uniformly integrable functions which converges μ-a.e. converges in Lp. -/ lemma tendsto_Lp_of_tendsto_ae_of_meas [is_finite_measure μ] (hp : 1 ≤ p) (hp' : p ≠ ∞) {f : ℕ → α → β} {g : α → β} (hf : ∀ n, strongly_measurable (f n)) (hg : strongly_measurable g) (hg' : mem_ℒp g p μ) (hui : unif_integrable f p μ) (hfg : ∀ᵐ x ∂μ, tendsto (λ n, f n x) at_top (𝓝 (g x))) : tendsto (λ n, snorm (f n - g) p μ) at_top (𝓝 0) := begin rw ennreal.tendsto_at_top_zero, intros ε hε, by_cases ε < ∞, swap, { rw [not_lt, top_le_iff] at h, exact ⟨0, λ n hn, by simp [h]⟩ }, by_cases hμ : μ = 0, { exact ⟨0, λ n hn, by simp [hμ]⟩ }, have hε' : 0 < ε.to_real / 3 := div_pos (ennreal.to_real_pos (gt_iff_lt.1 hε).ne.symm h.ne) (by norm_num), have hdivp : 0 ≤ 1 / p.to_real, { refine one_div_nonneg.2 _, rw [← ennreal.zero_to_real, ennreal.to_real_le_to_real ennreal.zero_ne_top hp'], exact le_trans ennreal.zero_lt_one.le hp }, have hpow : 0 < (measure_univ_nnreal μ) ^ (1 / p.to_real) := real.rpow_pos_of_pos (measure_univ_nnreal_pos hμ) _, obtain ⟨δ₁, hδ₁, hsnorm₁⟩ := hui hε', obtain ⟨δ₂, hδ₂, hsnorm₂⟩ := hg'.snorm_indicator_le μ hp hp' hε', obtain ⟨t, htm, ht₁, ht₂⟩ := tendsto_uniformly_on_of_ae_tendsto' hf hg hfg (lt_min hδ₁ hδ₂), rw metric.tendsto_uniformly_on_iff at ht₂, specialize ht₂ (ε.to_real / (3 * measure_univ_nnreal μ ^ (1 / p.to_real))) (div_pos (ennreal.to_real_pos (gt_iff_lt.1 hε).ne.symm h.ne) (mul_pos (by norm_num) hpow)), obtain ⟨N, hN⟩ := eventually_at_top.1 ht₂, clear ht₂, refine ⟨N, λ n hn, _⟩, rw [← t.indicator_self_add_compl (f n - g)], refine le_trans (snorm_add_le ((((hf n).sub hg).indicator htm).ae_strongly_measurable) (((hf n).sub hg).indicator htm.compl).ae_strongly_measurable hp) _, rw [sub_eq_add_neg, indicator_add' t, indicator_neg'], refine le_trans (add_le_add_right (snorm_add_le ((hf n).indicator htm).ae_strongly_measurable (hg.indicator htm).neg.ae_strongly_measurable hp) _) _, have hnf : snorm (t.indicator (f n)) p μ ≤ ennreal.of_real (ε.to_real / 3), { refine hsnorm₁ n t htm (le_trans ht₁ _), rw ennreal.of_real_le_of_real_iff hδ₁.le, exact min_le_left _ _ }, have hng : snorm (t.indicator g) p μ ≤ ennreal.of_real (ε.to_real / 3), { refine hsnorm₂ t htm (le_trans ht₁ _), rw ennreal.of_real_le_of_real_iff hδ₂.le, exact min_le_right _ _ }, have hlt : snorm (tᶜ.indicator (f n - g)) p μ ≤ ennreal.of_real (ε.to_real / 3), { specialize hN n hn, have := snorm_sub_le_of_dist_bdd μ hp' htm.compl _ (λ x hx, (dist_comm (g x) (f n x) ▸ (hN x hx).le : dist (f n x) (g x) ≤ ε.to_real / (3 * measure_univ_nnreal μ ^ (1 / p.to_real)))), refine le_trans this _, rw [div_mul_eq_div_mul_one_div, ← ennreal.of_real_to_real (measure_lt_top μ tᶜ).ne, ennreal.of_real_rpow_of_nonneg ennreal.to_real_nonneg hdivp, ← ennreal.of_real_mul, mul_assoc], { refine ennreal.of_real_le_of_real (mul_le_of_le_one_right hε'.le _), rw [mul_comm, mul_one_div, div_le_one], { refine real.rpow_le_rpow ennreal.to_real_nonneg (ennreal.to_real_le_of_le_of_real (measure_univ_nnreal_pos hμ).le _) hdivp, rw [ennreal.of_real_coe_nnreal, coe_measure_univ_nnreal], exact measure_mono (subset_univ _) }, { exact real.rpow_pos_of_pos (measure_univ_nnreal_pos hμ) _ } }, { refine mul_nonneg (hε').le (one_div_nonneg.2 hpow.le) }, { rw div_mul_eq_div_mul_one_div, exact mul_nonneg hε'.le (one_div_nonneg.2 hpow.le) } }, have : ennreal.of_real (ε.to_real / 3) = ε / 3, { rw [ennreal.of_real_div_of_pos (show (0 : ℝ) < 3, by norm_num), ennreal.of_real_to_real h.ne], simp }, rw this at hnf hng hlt, rw [snorm_neg, ← ennreal.add_thirds ε, ← sub_eq_add_neg], exact add_le_add_three hnf hng hlt end /-- A sequence of uniformly integrable functions which converges μ-a.e. converges in Lp. -/ lemma tendsto_Lp_of_tendsto_ae [is_finite_measure μ] (hp : 1 ≤ p) (hp' : p ≠ ∞) {f : ℕ → α → β} {g : α → β} (hf : ∀ n, ae_strongly_measurable (f n) μ) (hg : mem_ℒp g p μ) (hui : unif_integrable f p μ) (hfg : ∀ᵐ x ∂μ, tendsto (λ n, f n x) at_top (𝓝 (g x))) : tendsto (λ n, snorm (f n - g) p μ) at_top (𝓝 0) := begin suffices : tendsto (λ (n : ℕ), snorm ((hf n).mk (f n) - (hg.1.mk g)) p μ) at_top (𝓝 0), { convert this, exact funext (λ n, snorm_congr_ae ((hf n).ae_eq_mk.sub hg.1.ae_eq_mk)), }, refine tendsto_Lp_of_tendsto_ae_of_meas μ hp hp' (λ n, (hf n).strongly_measurable_mk) hg.1.strongly_measurable_mk (hg.ae_eq hg.1.ae_eq_mk) (hui.ae_eq (λ n, (hf n).ae_eq_mk)) _, have h_ae_forall_eq : ∀ᵐ x ∂μ, ∀ n, f n x = (hf n).mk (f n) x, { rw ae_all_iff, exact λ n, (hf n).ae_eq_mk, }, filter_upwards [hfg, h_ae_forall_eq, hg.1.ae_eq_mk] with x hx_tendsto hxf_eq hxg_eq, rw ← hxg_eq, convert hx_tendsto, ext1 n, exact (hxf_eq n).symm, end variables {f : ℕ → α → β} {g : α → β} lemma unif_integrable_of_tendsto_Lp_zero (hp : 1 ≤ p) (hp' : p ≠ ∞) (hf : ∀ n, mem_ℒp (f n) p μ) (hf_tendsto : tendsto (λ n, snorm (f n) p μ) at_top (𝓝 0)) : unif_integrable f p μ := begin intros ε hε, rw ennreal.tendsto_at_top_zero at hf_tendsto, obtain ⟨N, hN⟩ := hf_tendsto (ennreal.of_real ε) (by simpa), set F : fin N → α → β := λ n, f n, have hF : ∀ n, mem_ℒp (F n) p μ := λ n, hf n, obtain ⟨δ₁, hδpos₁, hδ₁⟩ := unif_integrable_fin μ hp hp' hF hε, refine ⟨δ₁, hδpos₁, λ n s hs hμs, _⟩, by_cases hn : n < N, { exact hδ₁ ⟨n, hn⟩ s hs hμs }, { exact (snorm_indicator_le _).trans (hN n (not_lt.1 hn)) }, end /-- Convergence in Lp implies uniform integrability. -/ lemma unif_integrable_of_tendsto_Lp (hp : 1 ≤ p) (hp' : p ≠ ∞) (hf : ∀ n, mem_ℒp (f n) p μ) (hg : mem_ℒp g p μ) (hfg : tendsto (λ n, snorm (f n - g) p μ) at_top (𝓝 0)) : unif_integrable f p μ := begin have : f = (λ n, g) + λ n, f n - g, by { ext1 n, simp, }, rw this, refine unif_integrable.add _ _ hp (λ _, hg.ae_strongly_measurable) (λ n, (hf n).1.sub hg.ae_strongly_measurable), { exact unif_integrable_const μ hp hp' hg, }, { exact unif_integrable_of_tendsto_Lp_zero μ hp hp' (λ n, (hf n).sub hg) hfg, }, end /-- Forward direction of Vitali's convergence theorem: if `f` is a sequence of uniformly integrable functions that converge in measure to some function `g` in a finite measure space, then `f` converge in Lp to `g`. -/ lemma tendsto_Lp_of_tendsto_in_measure [is_finite_measure μ] (hp : 1 ≤ p) (hp' : p ≠ ∞) (hf : ∀ n, ae_strongly_measurable (f n) μ) (hg : mem_ℒp g p μ) (hui : unif_integrable f p μ) (hfg : tendsto_in_measure μ f at_top g) : tendsto (λ n, snorm (f n - g) p μ) at_top (𝓝 0) := begin refine tendsto_of_subseq_tendsto (λ ns hns, _), obtain ⟨ms, hms, hms'⟩ := tendsto_in_measure.exists_seq_tendsto_ae (λ ε hε, (hfg ε hε).comp hns), exact ⟨ms, tendsto_Lp_of_tendsto_ae μ hp hp' (λ _, hf _) hg (λ ε hε, let ⟨δ, hδ, hδ'⟩ := hui hε in ⟨δ, hδ, λ i s hs hμs, hδ' _ s hs hμs⟩) hms'⟩, end /-- **Vitali's convergence theorem**: A sequence of functions `f` converges to `g` in Lp if and only if it is uniformly integrable and converges to `g` in measure. -/ lemma tendsto_in_measure_iff_tendsto_Lp [is_finite_measure μ] (hp : 1 ≤ p) (hp' : p ≠ ∞) (hf : ∀ n, mem_ℒp (f n) p μ) (hg : mem_ℒp g p μ) : tendsto_in_measure μ f at_top g ∧ unif_integrable f p μ ↔ tendsto (λ n, snorm (f n - g) p μ) at_top (𝓝 0) := ⟨λ h, tendsto_Lp_of_tendsto_in_measure μ hp hp' (λ n, (hf n).1) hg h.2 h.1, λ h, ⟨tendsto_in_measure_of_tendsto_snorm (lt_of_lt_of_le ennreal.zero_lt_one hp).ne.symm (λ n, (hf n).ae_strongly_measurable) hg.ae_strongly_measurable h, unif_integrable_of_tendsto_Lp μ hp hp' hf hg h⟩⟩ /-- This lemma is superceded by `unif_integrable_of` which do not require `C` to be positive. -/ lemma unif_integrable_of' (hp : 1 ≤ p) (hp' : p ≠ ∞) {f : ι → α → β} (hf : ∀ i, strongly_measurable (f i)) (h : ∀ ε : ℝ, 0 < ε → ∃ C : ℝ≥0, 0 < C ∧ ∀ i, snorm ({x | C ≤ ∥f i x∥₊}.indicator (f i)) p μ ≤ ennreal.of_real ε) : unif_integrable f p μ := begin have hpzero := (lt_of_lt_of_le ennreal.zero_lt_one hp).ne.symm, by_cases hμ : μ set.univ = 0, { rw measure.measure_univ_eq_zero at hμ, exact hμ.symm ▸ unif_integrable_zero_meas }, intros ε hε, obtain ⟨C, hCpos, hC⟩ := h (ε / 2) (half_pos hε), refine ⟨(ε / (2 * C)) ^ ennreal.to_real p, real.rpow_pos_of_pos (div_pos hε (mul_pos two_pos (nnreal.coe_pos.2 hCpos))) _, λ i s hs hμs, _⟩, by_cases hμs' : μ s = 0, { rw (snorm_eq_zero_iff ((hf i).indicator hs).ae_strongly_measurable hpzero).2 (indicator_meas_zero hμs'), norm_num }, calc snorm (indicator s (f i)) p μ ≤ snorm (indicator (s ∩ {x | C ≤ ∥f i x∥₊}) (f i)) p μ + snorm (indicator (s ∩ {x | ∥f i x∥₊ < C}) (f i)) p μ : begin refine le_trans (eq.le _) (snorm_add_le (strongly_measurable.ae_strongly_measurable ((hf i).indicator (hs.inter (strongly_measurable_const.measurable_set_le (hf i).nnnorm)))) (strongly_measurable.ae_strongly_measurable ((hf i).indicator (hs.inter ((hf i).nnnorm.measurable_set_lt strongly_measurable_const)))) hp), congr, change _ = λ x, (s ∩ {x : α | C ≤ ∥f i x∥₊}).indicator (f i) x + (s ∩ {x : α | ∥f i x∥₊ < C}).indicator (f i) x, rw ← set.indicator_union_of_disjoint, { congr, rw [← inter_union_distrib_left, (by { ext, simp [le_or_lt] } : {x : α | C ≤ ∥f i x∥₊} ∪ {x : α | ∥f i x∥₊ < C} = set.univ), inter_univ] }, { refine (disjoint.inf_right' _ _).inf_left' _, rintro x ⟨hx₁ : _ ≤ _, hx₂ : _ < _⟩, exact false.elim (hx₂.ne (eq_of_le_of_not_lt hx₁ (not_lt.2 hx₂.le)).symm) } end ... ≤ snorm (indicator ({x | C ≤ ∥f i x∥₊}) (f i)) p μ + C * μ s ^ (1 / ennreal.to_real p) : begin refine add_le_add (snorm_mono $ λ x, norm_indicator_le_of_subset (inter_subset_right _ _) _ _) _, rw ← indicator_indicator, rw snorm_indicator_eq_snorm_restrict, have : ∀ᵐ x ∂(μ.restrict s), ∥({x : α | ∥f i x∥₊ < C}).indicator (f i) x∥ ≤ C, { refine ae_of_all _ _, simp_rw norm_indicator_eq_indicator_norm, exact indicator_le' (λ x (hx : _ < _), hx.le) (λ _ _, nnreal.coe_nonneg _) }, refine le_trans (snorm_le_of_ae_bound this) _, rw [mul_comm, measure.restrict_apply' hs, univ_inter, ennreal.of_real_coe_nnreal, one_div], exacts [le_rfl, hs], end ... ≤ ennreal.of_real (ε / 2) + C * ennreal.of_real (ε / (2 * C)) : begin refine add_le_add (hC i) (mul_le_mul_left' _ _), rwa [ennreal.rpow_one_div_le_iff (ennreal.to_real_pos hpzero hp'), ennreal.of_real_rpow_of_pos (div_pos hε (mul_pos two_pos (nnreal.coe_pos.2 hCpos)))] end ... ≤ ennreal.of_real (ε / 2) + ennreal.of_real (ε / 2) : begin refine add_le_add_left _ _, rw [← ennreal.of_real_coe_nnreal, ← ennreal.of_real_mul (nnreal.coe_nonneg _), ← div_div, mul_div_cancel' _ (nnreal.coe_pos.2 hCpos).ne.symm], exact le_rfl, end ... ≤ ennreal.of_real ε : begin rw [← ennreal.of_real_add (half_pos hε).le (half_pos hε).le, add_halves], exact le_rfl, end end lemma unif_integrable_of (hp : 1 ≤ p) (hp' : p ≠ ∞) {f : ι → α → β} (hf : ∀ i, ae_strongly_measurable (f i) μ) (h : ∀ ε : ℝ, 0 < ε → ∃ C : ℝ≥0, ∀ i, snorm ({x | C ≤ ∥f i x∥₊}.indicator (f i)) p μ ≤ ennreal.of_real ε) : unif_integrable f p μ := begin set g : ι → α → β := λ i, (hf i).some, refine (unif_integrable_of' μ hp hp' (λ i, (Exists.some_spec $hf i).1) (λ ε hε, _)).ae_eq (λ i, (Exists.some_spec $ hf i).2.symm), obtain ⟨C, hC⟩ := h ε hε, have hCg : ∀ i, snorm ({x | C ≤ ∥g i x∥₊}.indicator (g i)) p μ ≤ ennreal.of_real ε, { intro i, refine le_trans (le_of_eq $ snorm_congr_ae _) (hC i), filter_upwards [(Exists.some_spec $ hf i).2] with x hx, by_cases hfx : x ∈ {x | C ≤ ∥f i x∥₊}, { rw [indicator_of_mem hfx, indicator_of_mem, hx], rwa [mem_set_of, hx] at hfx }, { rw [indicator_of_not_mem hfx, indicator_of_not_mem], rwa [mem_set_of, hx] at hfx } }, refine ⟨max C 1, lt_max_of_lt_right one_pos, λ i, le_trans (snorm_mono (λ x, _)) (hCg i)⟩, rw [norm_indicator_eq_indicator_norm, norm_indicator_eq_indicator_norm], exact indicator_le_indicator_of_subset (λ x hx, le_trans (le_max_left _ _) hx) (λ _, norm_nonneg _) _, end end unif_integrable section uniform_integrable /-! `uniform_integrable` In probability theory, uniform integrability normally refers to the condition that a sequence of function `(fₙ)` satisfies for all `ε > 0`, there exists some `C ≥ 0` such that `∫ x in {|fₙ| ≥ C}, fₙ x ∂μ ≤ ε` for all `n`. In this section, we will develope some API for `uniform_integrable` and prove that `uniform_integrable` is equivalent to this definition of uniform integrability. -/ variables {p : ℝ≥0∞} {f : ι → α → β} lemma uniform_integrable_zero_meas [measurable_space α] : uniform_integrable f p (0 : measure α) := ⟨λ n, ae_strongly_measurable_zero_measure _, unif_integrable_zero_meas, 0, λ i, snorm_measure_zero.le⟩ lemma uniform_integrable.ae_eq {g : ι → α → β} (hf : uniform_integrable f p μ) (hfg : ∀ n, f n =ᵐ[μ] g n) : uniform_integrable g p μ := begin obtain ⟨hfm, hunif, C, hC⟩ := hf, refine ⟨λ i, (hfm i).congr (hfg i), (unif_integrable_congr_ae hfg).1 hunif, C, λ i, _⟩, rw ← snorm_congr_ae (hfg i), exact hC i end lemma uniform_integrable_congr_ae {g : ι → α → β} (hfg : ∀ n, f n =ᵐ[μ] g n) : uniform_integrable f p μ ↔ uniform_integrable g p μ := ⟨λ h, h.ae_eq hfg, λ h, h.ae_eq (λ i, (hfg i).symm)⟩ /-- A finite sequence of Lp functions is uniformly integrable in the probability sense. -/ lemma uniform_integrable_finite [finite ι] (hp_one : 1 ≤ p) (hp_top : p ≠ ∞) (hf : ∀ i, mem_ℒp (f i) p μ) : uniform_integrable f p μ := begin casesI nonempty_fintype ι, refine ⟨λ n, (hf n).1, unif_integrable_finite μ hp_one hp_top hf, _⟩, by_cases hι : nonempty ι, { choose ae_meas hf using hf, set C := (finset.univ.image (λ i : ι, snorm (f i) p μ)).max' ⟨snorm (f hι.some) p μ, finset.mem_image.2 ⟨hι.some, finset.mem_univ _, rfl⟩⟩, refine ⟨C.to_nnreal, λ i, _⟩, rw ennreal.coe_to_nnreal, { exact finset.le_max' _ _ (finset.mem_image.2 ⟨i, finset.mem_univ _, rfl⟩) }, { refine ne_of_lt ((finset.max'_lt_iff _ _).2 (λ y hy, _)), rw finset.mem_image at hy, obtain ⟨i, -, rfl⟩ := hy, exact hf i } }, { exact ⟨0, λ i, false.elim $ hι $ nonempty.intro i⟩ } end /-- A single function is uniformly integrable in the probability sense. -/ lemma uniform_integrable_subsingleton [subsingleton ι] (hp_one : 1 ≤ p) (hp_top : p ≠ ∞) (hf : ∀ i, mem_ℒp (f i) p μ) : uniform_integrable f p μ := uniform_integrable_finite hp_one hp_top hf /-- A constant sequence of functions is uniformly integrable in the probability sense. -/ lemma uniform_integrable_const {g : α → β} (hp : 1 ≤ p) (hp_ne_top : p ≠ ∞) (hg : mem_ℒp g p μ) : uniform_integrable (λ n : ι, g) p μ := ⟨λ i, hg.1, unif_integrable_const μ hp hp_ne_top hg, ⟨(snorm g p μ).to_nnreal, λ i, le_of_eq (ennreal.coe_to_nnreal hg.2.ne).symm⟩⟩ /-- This lemma is superceded by `uniform_integrable_of` which only requires `ae_strongly_measurable`. -/ lemma uniform_integrable_of' [is_finite_measure μ] (hp : 1 ≤ p) (hp' : p ≠ ∞) (hf : ∀ i, strongly_measurable (f i)) (h : ∀ ε : ℝ, 0 < ε → ∃ C : ℝ≥0, ∀ i, snorm ({x | C ≤ ∥f i x∥₊}.indicator (f i)) p μ ≤ ennreal.of_real ε) : uniform_integrable f p μ := begin refine ⟨λ i, (hf i).ae_strongly_measurable, unif_integrable_of μ hp hp' (λ i, (hf i).ae_strongly_measurable) h, _⟩, obtain ⟨C, hC⟩ := h 1 one_pos, refine ⟨(C * (μ univ ^ (p.to_real⁻¹)) + 1 : ℝ≥0∞).to_nnreal, λ i, _⟩, calc snorm (f i) p μ ≤ snorm ({x : α | ∥f i x∥₊ < C}.indicator (f i)) p μ + snorm ({x : α | C ≤ ∥f i x∥₊}.indicator (f i)) p μ : begin refine le_trans (snorm_mono (λ x, _)) (snorm_add_le (strongly_measurable.ae_strongly_measurable ((hf i).indicator ((hf i).nnnorm.measurable_set_lt strongly_measurable_const))) (strongly_measurable.ae_strongly_measurable ((hf i).indicator (strongly_measurable_const.measurable_set_le (hf i).nnnorm))) hp), { rw [pi.add_apply, indicator_apply], split_ifs with hx, { rw [indicator_of_not_mem, add_zero], simpa using hx }, { rw [indicator_of_mem, zero_add], simpa using hx } } end ... ≤ C * μ univ ^ (p.to_real⁻¹) + 1 : begin have : ∀ᵐ x ∂μ, ∥{x : α | ∥f i x∥₊ < C}.indicator (f i) x∥₊ ≤ C, { refine eventually_of_forall _, simp_rw nnnorm_indicator_eq_indicator_nnnorm, exact indicator_le (λ x (hx : _ < _), hx.le) }, refine add_le_add (le_trans (snorm_le_of_ae_bound this) _) (ennreal.of_real_one ▸ (hC i)), rw [ennreal.of_real_coe_nnreal, mul_comm], exact le_rfl, end ... = (C * (μ univ ^ (p.to_real⁻¹)) + 1 : ℝ≥0∞).to_nnreal : begin rw ennreal.coe_to_nnreal, exact ennreal.add_ne_top.2 ⟨ennreal.mul_ne_top ennreal.coe_ne_top (ennreal.rpow_ne_top_of_nonneg (inv_nonneg.2 ennreal.to_real_nonneg) (measure_lt_top _ _).ne), ennreal.one_ne_top⟩, end end /-- A sequene of functions `(fₙ)` is uniformly integrable in the probability sense if for all `ε > 0`, there exists some `C` such that `∫ x in {|fₙ| ≥ C}, fₙ x ∂μ ≤ ε` for all `n`. -/ lemma uniform_integrable_of [is_finite_measure μ] (hp : 1 ≤ p) (hp' : p ≠ ∞) (hf : ∀ i, ae_strongly_measurable (f i) μ) (h : ∀ ε : ℝ, 0 < ε → ∃ C : ℝ≥0, ∀ i, snorm ({x | C ≤ ∥f i x∥₊}.indicator (f i)) p μ ≤ ennreal.of_real ε) : uniform_integrable f p μ := begin set g : ι → α → β := λ i, (hf i).some, have hgmeas : ∀ i, strongly_measurable (g i) := λ i, (Exists.some_spec $ hf i).1, have hgeq : ∀ i, g i =ᵐ[μ] f i := λ i, (Exists.some_spec $ hf i).2.symm, refine (uniform_integrable_of' hp hp' hgmeas $ λ ε hε, _).ae_eq hgeq, obtain ⟨C, hC⟩ := h ε hε, refine ⟨C, λ i, le_trans (le_of_eq $ snorm_congr_ae _) (hC i)⟩, filter_upwards [(Exists.some_spec $ hf i).2] with x hx, by_cases hfx : x ∈ {x | C ≤ ∥f i x∥₊}, { rw [indicator_of_mem hfx, indicator_of_mem, hx], rwa [mem_set_of, hx] at hfx }, { rw [indicator_of_not_mem hfx, indicator_of_not_mem], rwa [mem_set_of, hx] at hfx } end /-- This lemma is superceded by `uniform_integrable.spec` which does not require measurability. -/ lemma uniform_integrable.spec' (hp : p ≠ 0) (hp' : p ≠ ∞) (hf : ∀ i, strongly_measurable (f i)) (hfu : uniform_integrable f p μ) {ε : ℝ} (hε : 0 < ε) : ∃ C : ℝ≥0, ∀ i, snorm ({x | C ≤ ∥f i x∥₊}.indicator (f i)) p μ ≤ ennreal.of_real ε := begin obtain ⟨-, hfu, M, hM⟩ := hfu, obtain ⟨δ, hδpos, hδ⟩ := hfu hε, obtain ⟨C, hC⟩ : ∃ C : ℝ≥0, ∀ i, μ {x | C ≤ ∥f i x∥₊} ≤ ennreal.of_real δ, { by_contra hcon, push_neg at hcon, choose ℐ hℐ using hcon, lift δ to ℝ≥0 using hδpos.le, have : ∀ C : ℝ≥0, C • (δ : ℝ≥0∞) ^ (1 / p.to_real) ≤ snorm (f (ℐ C)) p μ, { intros C, calc C • (δ : ℝ≥0∞) ^ (1 / p.to_real) ≤ C • μ {x | C ≤ ∥f (ℐ C) x∥₊} ^ (1 / p.to_real): begin rw [ennreal.smul_def, ennreal.smul_def, smul_eq_mul, smul_eq_mul], simp_rw ennreal.of_real_coe_nnreal at hℐ, refine ennreal.mul_le_mul le_rfl (ennreal.rpow_le_rpow (hℐ C).le (one_div_nonneg.2 ennreal.to_real_nonneg)), end ... ≤ snorm ({x | C ≤ ∥f (ℐ C) x∥₊}.indicator (f (ℐ C))) p μ : begin refine snorm_indicator_ge_of_bdd_below hp hp' _ (measurable_set_le measurable_const (hf _).nnnorm.measurable) (eventually_of_forall $ λ x hx, _), rwa [nnnorm_indicator_eq_indicator_nnnorm, indicator_of_mem hx], end ... ≤ snorm (f (ℐ C)) p μ : snorm_indicator_le _ }, specialize this ((2 * (max M 1) * (δ⁻¹ ^ (1 / p.to_real)))), rw [ennreal.coe_rpow_of_nonneg _ (one_div_nonneg.2 ennreal.to_real_nonneg), ← ennreal.coe_smul, smul_eq_mul, mul_assoc, nnreal.inv_rpow, inv_mul_cancel (nnreal.rpow_pos (nnreal.coe_pos.1 hδpos)).ne.symm, mul_one, ennreal.coe_mul, ← nnreal.inv_rpow] at this, refine (lt_of_le_of_lt (le_trans (hM $ ℐ $ 2 * (max M 1) * (δ⁻¹ ^ (1 / p.to_real))) (le_max_left M 1)) (lt_of_lt_of_le _ this)).ne rfl, rw [← ennreal.coe_one, ← with_top.coe_max, ← ennreal.coe_mul, ennreal.coe_lt_coe], exact lt_two_mul_self (lt_max_of_lt_right one_pos) }, exact ⟨C, λ i, hδ i _ (measurable_set_le measurable_const (hf i).nnnorm.measurable) (hC i)⟩, end lemma uniform_integrable.spec (hp : p ≠ 0) (hp' : p ≠ ∞) (hfu : uniform_integrable f p μ) {ε : ℝ} (hε : 0 < ε) : ∃ C : ℝ≥0, ∀ i, snorm ({x | C ≤ ∥f i x∥₊}.indicator (f i)) p μ ≤ ennreal.of_real ε := begin set g : ι → α → β := λ i, (hfu.1 i).some, have hgmeas : ∀ i, strongly_measurable (g i) := λ i, (Exists.some_spec $ hfu.1 i).1, have hgunif : uniform_integrable g p μ := hfu.ae_eq (λ i, (Exists.some_spec $ hfu.1 i).2), obtain ⟨C, hC⟩ := hgunif.spec' hp hp' hgmeas hε, refine ⟨C, λ i, le_trans (le_of_eq $ snorm_congr_ae _) (hC i)⟩, filter_upwards [(Exists.some_spec $ hfu.1 i).2] with x hx, by_cases hfx : x ∈ {x | C ≤ ∥f i x∥₊}, { rw [indicator_of_mem hfx, indicator_of_mem, hx], rwa [mem_set_of, hx] at hfx }, { rw [indicator_of_not_mem hfx, indicator_of_not_mem], rwa [mem_set_of, hx] at hfx } end /-- The definition of uniform integrable in mathlib is equivalent to the definition commonly found in literature. -/ lemma uniform_integrable_iff [is_finite_measure μ] (hp : 1 ≤ p) (hp' : p ≠ ∞) : uniform_integrable f p μ ↔ (∀ i, ae_strongly_measurable (f i) μ) ∧ ∀ ε : ℝ, 0 < ε → ∃ C : ℝ≥0, ∀ i, snorm ({x | C ≤ ∥f i x∥₊}.indicator (f i)) p μ ≤ ennreal.of_real ε := ⟨λ h, ⟨h.1, λ ε, h.spec (lt_of_lt_of_le ennreal.zero_lt_one hp).ne.symm hp'⟩, λ h, uniform_integrable_of hp hp' h.1 h.2⟩ /-- The averaging of a uniformly integrable sequence is also uniformly integrable. -/ lemma uniform_integrable_average (hp : 1 ≤ p) {f : ℕ → α → ℝ} (hf : uniform_integrable f p μ) : uniform_integrable (λ n, (∑ i in finset.range n, f i) / n) p μ := begin obtain ⟨hf₁, hf₂, hf₃⟩ := hf, refine ⟨λ n, _, λ ε hε, _, _⟩, { simp_rw div_eq_mul_inv, exact (finset.ae_strongly_measurable_sum' _ (λ i _, hf₁ i)).mul (ae_strongly_measurable_const : ae_strongly_measurable (λ x, (↑n : ℝ)⁻¹) μ) }, { obtain ⟨δ, hδ₁, hδ₂⟩ := hf₂ hε, refine ⟨δ, hδ₁, λ n s hs hle, _⟩, simp_rw [div_eq_mul_inv, finset.sum_mul, set.indicator_finset_sum], refine le_trans (snorm_sum_le (λ i hi, ((hf₁ i).mul_const (↑n)⁻¹).indicator hs) hp) _, have : ∀ i, s.indicator (f i * (↑n)⁻¹) = (↑n : ℝ)⁻¹ • s.indicator (f i), { intro i, rw [mul_comm, (_ : (↑n)⁻¹ * f i = λ ω, (↑n : ℝ)⁻¹ • f i ω)], { rw set.indicator_const_smul s (↑n)⁻¹ (f i), refl }, { refl } }, simp_rw [this, snorm_const_smul, ← finset.mul_sum, nnnorm_inv, real.nnnorm_coe_nat], by_cases hn : (↑(↑n : ℝ≥0)⁻¹ : ℝ≥0∞) = 0, { simp only [hn, zero_mul, zero_le] }, refine le_trans _ (_ : ↑(↑n : ℝ≥0)⁻¹ * (n • ennreal.of_real ε) ≤ ennreal.of_real ε), { refine (ennreal.mul_le_mul_left hn ennreal.coe_ne_top).2 _, conv_rhs { rw ← finset.card_range n }, exact finset.sum_le_card_nsmul _ _ _ (λ i hi, hδ₂ _ _ hs hle) }, { simp only [ennreal.coe_eq_zero, inv_eq_zero, nat.cast_eq_zero] at hn, rw [nsmul_eq_mul, ← mul_assoc, ennreal.coe_inv, ennreal.coe_nat, ennreal.inv_mul_cancel _ (ennreal.nat_ne_top _), one_mul], { exact le_rfl }, all_goals { simpa only [ne.def, nat.cast_eq_zero] } } }, { obtain ⟨C, hC⟩ := hf₃, simp_rw [div_eq_mul_inv, finset.sum_mul], refine ⟨C, λ n, (snorm_sum_le (λ i hi, (hf₁ i).mul_const (↑n)⁻¹) hp).trans _⟩, have : ∀ i, (λ ω, f i ω * (↑n)⁻¹) = (↑n : ℝ)⁻¹ • λ ω, f i ω, { intro i, ext ω, simp only [mul_comm, pi.smul_apply, algebra.id.smul_eq_mul] }, simp_rw [this, snorm_const_smul, ← finset.mul_sum, nnnorm_inv, real.nnnorm_coe_nat], by_cases hn : (↑(↑n : ℝ≥0)⁻¹ : ℝ≥0∞) = 0, { simp only [hn, zero_mul, zero_le] }, refine le_trans _ (_ : ↑(↑n : ℝ≥0)⁻¹ * (n • C : ℝ≥0∞) ≤ C), { refine (ennreal.mul_le_mul_left hn ennreal.coe_ne_top).2 _, conv_rhs { rw ← finset.card_range n }, exact finset.sum_le_card_nsmul _ _ _ (λ i hi, hC i) }, { simp only [ennreal.coe_eq_zero, inv_eq_zero, nat.cast_eq_zero] at hn, rw [nsmul_eq_mul, ← mul_assoc, ennreal.coe_inv, ennreal.coe_nat, ennreal.inv_mul_cancel _ (ennreal.nat_ne_top _), one_mul], { exact le_rfl }, all_goals { simpa only [ne.def, nat.cast_eq_zero] } } } end end uniform_integrable end measure_theory
ead9f395f70377f2aee597621b356dba35e6a77f
63abd62053d479eae5abf4951554e1064a4c45b4
/test/norm_digits.lean
6a6ba62e59fd88bc862fa34845efc8b2bd0d30e2
[ "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
674
lean
import data.nat.digits example : nat.digits 0 0 = [] := by norm_digits example : nat.digits 1 0 = [] := by norm_digits example : nat.digits 2 0 = [] := by norm_digits example : nat.digits 10 0 = [] := by norm_digits example : nat.digits 0 1 = [1] := by norm_digits example : nat.digits 0 1000 = [1000] := by norm_digits example : nat.digits 1 10 = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] := by norm_digits example : nat.digits 2 65536 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1] := by norm_digits example : nat.digits 3 30000000 = [0, 1, 0, 1, 2, 0, 1, 1, 0, 0, 1, 1, 2, 0, 0, 2] := by norm_digits example : nat.digits 10 1234567 = [7, 6, 5, 4, 3, 2, 1] := by norm_digits
64abe6fce3452f56dca9dc136d1fa1bc3d6e100c
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/analysis/convex/exposed.lean
2d4650d67dedcae84d60ad1a8939c44edd308131
[ "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
8,889
lean
/- Copyright (c) 2021 Yaël Dillies, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Bhavik Mehta -/ import analysis.convex.extreme /-! # Exposed sets This file defines exposed sets and exposed points for sets in a real vector space. An exposed subset of `A` is a subset of `A` that is the set of all maximal points of a functional (a continuous linear map `E → ℝ`) over `A`. By convention, `∅` is an exposed subset of all sets. This allows for better functioriality of the definition (the intersection of two exposed subsets is exposed, faces of a polytope form a bounded lattice). This is an analytic notion of "being on the side of". It is stronger than being extreme (see `is_exposed.is_extreme`), but weaker (for exposed points) than being a vertex. An exposed set of `A` is sometimes called a "face of `A`", but we decided to reserve this terminology to the more specific notion of a face of a polytope (sometimes hopefully soon out on mathlib!). ## Main declarations * `is_exposed A B`: States that `B` is an exposed set of `A` (in the literature, `A` is often implicit). * `is_exposed.is_extreme`: An exposed set is also extreme. ## References See chapter 8 of [Barry Simon, *Convexity*][simon2011] ## TODO * define convex independence, intrinsic frontier/interior and prove the lemmas related to exposed sets and points. * generalise to Locally Convex Topological Vector Spaces™ More not-yet-PRed stuff is available on the branch `sperner_again`. -/ open_locale classical affine big_operators open set variables {E : Type*} [normed_group E] [normed_space ℝ E] {x : E} {A B C : set E} {X : finset E} {l : E →L[ℝ] ℝ} /-- A set `B` is exposed with respect to `A` iff it maximizes some functional over `A` (and contains all points maximizing it). Written `is_exposed A B`. -/ def is_exposed (A B : set E) : Prop := B.nonempty → ∃ l : E →L[ℝ] ℝ, B = {x ∈ A | ∀ y ∈ A, l y ≤ l x} /-- A useful way to build exposed sets from intersecting `A` with halfspaces (modelled by an inequality with a functional). -/ def continuous_linear_map.to_exposed (l : E →L[ℝ] ℝ) (A : set E) : set E := {x ∈ A | ∀ y ∈ A, l y ≤ l x} lemma continuous_linear_map.to_exposed.is_exposed : is_exposed A (l.to_exposed A) := λ h, ⟨l, rfl⟩ lemma is_exposed_empty : is_exposed A ∅ := λ ⟨x, hx⟩, by { exfalso, exact hx } namespace is_exposed protected lemma subset (hAB : is_exposed A B) : B ⊆ A := begin rintro x hx, obtain ⟨_, rfl⟩ := hAB ⟨x, hx⟩, exact hx.1, end @[refl] lemma refl (A : set E) : is_exposed A A := λ ⟨w, hw⟩, ⟨0, subset.antisymm (λ x hx, ⟨hx, λ y hy, by exact le_refl 0⟩) (λ x hx, hx.1)⟩ lemma antisymm (hB : is_exposed A B) (hA : is_exposed B A) : A = B := hA.subset.antisymm hB.subset /- `is_exposed` is *not* transitive: Consider a (topologically) open cube with vertices `A₀₀₀, ..., A₁₁₁` and add to it the triangle `A₀₀₀A₀₀₁A₀₁₀`. Then `A₀₀₁A₀₁₀` is an exposed subset of `A₀₀₀A₀₀₁A₀₁₀` which is an exposed subset of the cube, but `A₀₀₁A₀₁₀` is not itself an exposed subset of the cube. -/ protected lemma mono (hC : is_exposed A C) (hBA : B ⊆ A) (hCB : C ⊆ B) : is_exposed B C := begin rintro ⟨w, hw⟩, obtain ⟨l, rfl⟩ := hC ⟨w, hw⟩, exact ⟨l, subset.antisymm (λ x hx, ⟨hCB hx, λ y hy, hx.2 y (hBA hy)⟩) (λ x hx, ⟨hBA hx.1, λ y hy, (hw.2 y hy).trans (hx.2 w (hCB hw))⟩)⟩, end /-- If `B` is an exposed subset of `A`, then `B` is the intersection of `A` with some closed halfspace. The converse is *not* true. It would require that the corresponding open halfspace doesn't intersect `A`. -/ lemma eq_inter_halfspace (hAB : is_exposed A B) : ∃ l : E →L[ℝ] ℝ, ∃ a, B = {x ∈ A | a ≤ l x} := begin obtain hB | hB := B.eq_empty_or_nonempty, { refine ⟨0, 1, _⟩, rw [hB, eq_comm, eq_empty_iff_forall_not_mem], rintro x ⟨-, h⟩, rw continuous_linear_map.zero_apply at h, linarith }, obtain ⟨l, rfl⟩ := hAB hB, obtain ⟨w, hw⟩ := hB, exact ⟨l, l w, subset.antisymm (λ x hx, ⟨hx.1, hx.2 w hw.1⟩) (λ x hx, ⟨hx.1, λ y hy, (hw.2 y hy).trans hx.2⟩)⟩, end lemma inter (hB : is_exposed A B) (hC : is_exposed A C) : is_exposed A (B ∩ C) := begin rintro ⟨w, hwB, hwC⟩, obtain ⟨l₁, rfl⟩ := hB ⟨w, hwB⟩, obtain ⟨l₂, rfl⟩ := hC ⟨w, hwC⟩, refine ⟨l₁ + l₂, subset.antisymm _ _⟩, { rintro x ⟨⟨hxA, hxB⟩, ⟨-, hxC⟩⟩, exact ⟨hxA, λ z hz, add_le_add (hxB z hz) (hxC z hz)⟩ }, rintro x ⟨hxA, hx⟩, refine ⟨⟨hxA, λ y hy, _⟩, hxA, λ y hy, _⟩, { exact (add_le_add_iff_right (l₂ x)).1 ((add_le_add (hwB.2 y hy) (hwC.2 x hxA)).trans (hx w hwB.1)) }, { exact (add_le_add_iff_left (l₁ x)).1 (le_trans (add_le_add (hwB.2 x hxA) (hwC.2 y hy)) (hx w hwB.1)) } end lemma sInter {F : finset (set E)} (hF : F.nonempty) (hAF : ∀ B ∈ F, is_exposed A B) : is_exposed A (⋂₀ F) := begin revert hF F, refine finset.induction _ _, { rintro h, exfalso, exact empty_not_nonempty h }, rintro C F _ hF _ hCF, rw [finset.coe_insert, sInter_insert], obtain rfl | hFnemp := F.eq_empty_or_nonempty, { rw [finset.coe_empty, sInter_empty, inter_univ], exact hCF C (finset.mem_singleton_self C) }, exact (hCF C (finset.mem_insert_self C F)).inter (hF hFnemp (λ B hB, hCF B(finset.mem_insert_of_mem hB))), end lemma inter_left (hC : is_exposed A C) (hCB : C ⊆ B) : is_exposed (A ∩ B) C := begin rintro ⟨w, hw⟩, obtain ⟨l, rfl⟩ := hC ⟨w, hw⟩, exact ⟨l, subset.antisymm (λ x hx, ⟨⟨hx.1, hCB hx⟩, λ y hy, hx.2 y hy.1⟩) (λ x ⟨⟨hxC, _⟩, hx⟩, ⟨hxC, λ y hy, (hw.2 y hy).trans (hx w ⟨hC.subset hw, hCB hw⟩)⟩)⟩, end lemma inter_right (hC : is_exposed B C) (hCA : C ⊆ A) : is_exposed (A ∩ B) C := begin rw inter_comm, exact hC.inter_left hCA, end protected lemma is_extreme (hAB : is_exposed A B) : is_extreme A B := begin refine ⟨hAB.subset, λ x₁ x₂ hx₁A hx₂A x hxB hx, _⟩, obtain ⟨l, rfl⟩ := hAB ⟨x, hxB⟩, have hl : convex_on univ l := l.to_linear_map.convex_on convex_univ, have hlx₁ := hxB.2 x₁ hx₁A, have hlx₂ := hxB.2 x₂ hx₂A, refine ⟨⟨hx₁A, λ y hy, _⟩, ⟨hx₂A, λ y hy, _⟩⟩, { rw hlx₁.antisymm (hl.le_left_of_right_le (mem_univ _) (mem_univ _) hx hlx₂), exact hxB.2 y hy }, { rw hlx₂.antisymm (hl.le_right_of_left_le (mem_univ _) (mem_univ _) hx hlx₁), exact hxB.2 y hy } end protected lemma is_convex (hAB : is_exposed A B) (hA : convex A) : convex B := begin obtain rfl | hB := B.eq_empty_or_nonempty, { exact convex_empty }, obtain ⟨l, rfl⟩ := hAB hB, exact λ x₁ x₂ hx₁ hx₂ a b ha hb hab, ⟨hA hx₁.1 hx₂.1 ha hb hab, λ y hy, ((l.to_linear_map.concave_on convex_univ).concave_le _ ⟨mem_univ _, hx₁.2 y hy⟩ ⟨mem_univ _, hx₂.2 y hy⟩ ha hb hab).2⟩, end lemma is_closed (hAB : is_exposed A B) (hA : is_closed A) : is_closed B := begin obtain ⟨l, a, rfl⟩ := hAB.eq_inter_halfspace, exact hA.is_closed_le continuous_on_const l.continuous.continuous_on, end lemma is_compact (hAB : is_exposed A B) (hA : is_compact A) : is_compact B := compact_of_is_closed_subset hA (hAB.is_closed hA.is_closed) hAB.subset end is_exposed /-- A point is exposed with respect to `A` iff there exists an hyperplane whose intersection with `A` is exactly that point. -/ def set.exposed_points (A : set E) : set E := {x ∈ A | ∃ l : E →L[ℝ] ℝ, ∀ y ∈ A, l y ≤ l x ∧ (l x ≤ l y → y = x)} lemma exposed_point_def : x ∈ A.exposed_points ↔ x ∈ A ∧ ∃ l : E →L[ℝ] ℝ, ∀ y ∈ A, l y ≤ l x ∧ (l x ≤ l y → y = x) := iff.rfl /-- Exposed points exactly correspond to exposed singletons. -/ lemma mem_exposed_points_iff_exposed_singleton : x ∈ A.exposed_points ↔ is_exposed A {x} := begin use λ ⟨hxA, l, hl⟩ h, ⟨l, eq.symm $ eq_singleton_iff_unique_mem.2 ⟨⟨hxA, λ y hy, (hl y hy).1⟩, λ z hz, (hl z hz.1).2 (hz.2 x hxA)⟩⟩, rintro h, obtain ⟨l, hl⟩ := h ⟨x, mem_singleton _⟩, rw [eq_comm, eq_singleton_iff_unique_mem] at hl, exact ⟨hl.1.1, l, λ y hy, ⟨hl.1.2 y hy, λ hxy, hl.2 y ⟨hy, λ z hz, (hl.1.2 z hz).trans hxy⟩⟩⟩, end lemma exposed_points_subset : A.exposed_points ⊆ A := λ x hx, hx.1 lemma exposed_points_subset_extreme_points : A.exposed_points ⊆ A.extreme_points := λ x hx, mem_extreme_points_iff_extreme_singleton.2 (mem_exposed_points_iff_exposed_singleton.1 hx).is_extreme @[simp] lemma exposed_points_empty : (∅ : set E).exposed_points = ∅ := subset_empty_iff.1 exposed_points_subset
2c8c4e37ecda1247327c83b82a3ccdfda26ec176
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/run/cc_ac_bug.lean
386f8fb533c1fc47c48b57ff28234dffd89d4b0b
[ "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
110
lean
example (a b c : nat) (f : nat → nat → nat) : f (b * c) (c * b * a) = f (c * b) (a * c * b) := by ac_refl
36495f8133cdef4a26f281bd2578a3bbaa654672
92b50235facfbc08dfe7f334827d47281471333b
/library/logic/instances.lean
e9ac41a61f10eee562e4e4f67dd845bec4a379d0
[ "Apache-2.0" ]
permissive
htzh/lean
24f6ed7510ab637379ec31af406d12584d31792c
d70c79f4e30aafecdfc4a60b5d3512199200ab6e
refs/heads/master
1,607,677,731,270
1,437,089,952,000
1,437,089,952,000
37,078,816
0
0
null
1,433,780,956,000
1,433,780,955,000
null
UTF-8
Lean
false
false
3,767
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad Class instances for iff and eq. -/ import logic.connectives algebra.relation namespace relation /- logical equivalence relations -/ theorem is_equivalence_eq [instance] (T : Type) : relation.is_equivalence (@eq T) := relation.is_equivalence.mk (@eq.refl T) (@eq.symm T) (@eq.trans T) theorem is_equivalence_iff [instance] : relation.is_equivalence iff := relation.is_equivalence.mk @iff.refl @iff.symm @iff.trans /- congruences for logic operations -/ theorem is_congruence_not : is_congruence iff iff not := is_congruence.mk (take a b, assume H : a ↔ b, iff.intro (assume H1 : ¬a, assume H2 : b, H1 (iff.elim_right H H2)) (assume H1 : ¬b, assume H2 : a, H1 (iff.elim_left H H2))) theorem is_congruence_and : is_congruence2 iff iff iff and := is_congruence2.mk (take a1 b1 a2 b2, assume H1 : a1 ↔ b1, assume H2 : a2 ↔ b2, iff.intro (assume H3 : a1 ∧ a2, and_of_and_of_imp_of_imp H3 (iff.elim_left H1) (iff.elim_left H2)) (assume H3 : b1 ∧ b2, and_of_and_of_imp_of_imp H3 (iff.elim_right H1) (iff.elim_right H2))) theorem is_congruence_or : is_congruence2 iff iff iff or := is_congruence2.mk (take a1 b1 a2 b2, assume H1 : a1 ↔ b1, assume H2 : a2 ↔ b2, iff.intro (assume H3 : a1 ∨ a2, or_of_or_of_imp_of_imp H3 (iff.elim_left H1) (iff.elim_left H2)) (assume H3 : b1 ∨ b2, or_of_or_of_imp_of_imp H3 (iff.elim_right H1) (iff.elim_right H2))) theorem is_congruence_imp : is_congruence2 iff iff iff imp := is_congruence2.mk (take a1 b1 a2 b2, assume H1 : a1 ↔ b1, assume H2 : a2 ↔ b2, iff.intro (assume H3 : a1 → a2, assume Hb1 : b1, iff.elim_left H2 (H3 ((iff.elim_right H1) Hb1))) (assume H3 : b1 → b2, assume Ha1 : a1, iff.elim_right H2 (H3 ((iff.elim_left H1) Ha1)))) theorem is_congruence_iff : is_congruence2 iff iff iff iff := is_congruence2.mk (take a1 b1 a2 b2, assume H1 : a1 ↔ b1, assume H2 : a2 ↔ b2, iff.intro (assume H3 : a1 ↔ a2, iff.trans (iff.symm H1) (iff.trans H3 H2)) (assume H3 : b1 ↔ b2, iff.trans H1 (iff.trans H3 (iff.symm H2)))) definition is_congruence_not_compose [instance] := is_congruence.compose is_congruence_not definition is_congruence_and_compose [instance] := is_congruence.compose21 is_congruence_and definition is_congruence_or_compose [instance] := is_congruence.compose21 is_congruence_or definition is_congruence_implies_compose [instance] := is_congruence.compose21 is_congruence_imp definition is_congruence_iff_compose [instance] := is_congruence.compose21 is_congruence_iff /- a general substitution operation with respect to an arbitrary congruence -/ namespace general_subst theorem subst {T : Type} (R : T → T → Prop) ⦃P : T → Prop⦄ [C : is_congruence R iff P] {a b : T} (H : R a b) (H1 : P a) : P b := iff.elim_left (is_congruence.app C H) H1 end general_subst /- iff can be coerced to implication -/ definition mp_like_iff [instance] : relation.mp_like iff := relation.mp_like.mk (λa b (H : a ↔ b), iff.elim_left H) /- support for calculations with iff -/ namespace iff theorem subst {P : Prop → Prop} [C : is_congruence iff iff P] {a b : Prop} (H : a ↔ b) (H1 : P a) : P b := @general_subst.subst Prop iff P C a b H H1 end iff attribute iff.subst [subst] namespace iff_ops notation H ⁻¹ := iff.symm H notation H1 ⬝ H2 := iff.trans H1 H2 notation H1 ▸ H2 := iff.subst H1 H2 definition refl := iff.refl definition symm := @iff.symm definition trans := @iff.trans definition subst := @iff.subst definition mp := @iff.mp end iff_ops end relation
69551b544997a1285ae83cc2142a1b82baa84f81
63abd62053d479eae5abf4951554e1064a4c45b4
/src/category_theory/pi/basic.lean
e0dfb43d1a61a504cfb4db17c2daf1b0a272f1e2
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
4,369
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Scott Morrison -/ import category_theory.natural_isomorphism import category_theory.eq_to_hom /-! # Categories of indexed families of objects. We define the pointwise category structure on indexed families of objects in a category (and also the dependent generalization). -/ namespace category_theory universes w₀ w₁ w₂ v₁ v₂ u₁ u₂ variables {I : Type w₀} (C : I → Type u₁) [Π i, category.{v₁} (C i)] /-- `pi C` gives the cartesian product of an indexed family of categories. -/ instance pi : category.{max w₀ v₁} (Π i, C i) := { hom := λ X Y, Π i, X i ⟶ Y i, id := λ X i, 𝟙 (X i), comp := λ X Y Z f g i, f i ≫ g i } /-- This provides some assistance to typeclass search in a common situation, which otherwise fails. (Without this `category_theory.pi.has_limit_of_has_limit_comp_eval` fails.) -/ abbreviation pi' {I : Type v₁} (C : I → Type u₁) [Π i, category.{v₁} (C i)] : category.{v₁} (Π i, C i) := category_theory.pi C attribute [instance] pi' namespace pi @[simp] lemma id_apply (X : Π i, C i) (i) : (𝟙 X : Π i, X i ⟶ X i) i = 𝟙 (X i) := rfl @[simp] lemma comp_apply {X Y Z : Π i, C i} (f : X ⟶ Y) (g : Y ⟶ Z) (i) : (f ≫ g : Π i, X i ⟶ Z i) i = f i ≫ g i := rfl /-- The evaluation functor at `i : I`, sending an `I`-indexed family of objects to the object over `i`. -/ @[simps] def eval (i : I) : (Π i, C i) ⥤ C i := { obj := λ f, f i, map := λ f g α, α i, } section variables {J : Type w₁} /-- Pull back an `I`-indexed family of objects to an `J`-indexed family, along a function `J → I`. -/ @[simps] def comap (h : J → I) : (Π i, C i) ⥤ (Π j, C (h j)) := { obj := λ f i, f (h i), map := λ f g α i, α (h i), } variables (I) /-- The natural isomorphism between pulling back a grading along the identity function, and the identity functor. -/ @[simps] def comap_id : comap C (id : I → I) ≅ 𝟭 (Π i, C i) := { hom := { app := λ X, 𝟙 X }, inv := { app := λ X, 𝟙 X } }. variables {I} variables {K : Type w₂} /-- The natural isomorphism comparing between pulling back along two successive functions, and pulling back along their composition -/ @[simps] def comap_comp (f : K → J) (g : J → I) : comap C g ⋙ comap (C ∘ g) f ≅ comap C (g ∘ f) := { hom := { app := λ X b, 𝟙 (X (g (f b))) }, inv := { app := λ X b, 𝟙 (X (g (f b))) } } /-- The natural isomorphism between pulling back then evaluating, and just evaluating. -/ @[simps {rhs_md := semireducible}] def comap_eval_iso_eval (h : J → I) (j : J) : comap C h ⋙ eval (C ∘ h) j ≅ eval C (h j) := nat_iso.of_components (λ f, iso.refl _) (by tidy) end section variables {J : Type w₀} {D : J → Type u₁} [Π j, category.{v₁} (D j)] instance sum_elim_category : Π (s : I ⊕ J), category.{v₁} (sum.elim C D s) | (sum.inl i) := by { dsimp, apply_instance, } | (sum.inr j) := by { dsimp, apply_instance, } /-- The bifunctor combining an `I`-indexed family of objects with a `J`-indexed family of objects to obtain an `I ⊕ J`-indexed family of objects. -/ @[simps] def sum : (Π i, C i) ⥤ (Π j, D j) ⥤ (Π s : I ⊕ J, sum.elim C D s) := { obj := λ f, { obj := λ g s, sum.rec f g s, map := λ g g' α s, sum.rec (λ i, 𝟙 (f i)) α s }, map := λ f f' α, { app := λ g s, sum.rec α (λ j, 𝟙 (g j)) s, }} end end pi namespace functor variables {C} variables {D : I → Type u₁} [∀ i, category.{v₁} (D i)] /-- Assemble an `I`-indexed family of functors into a functor between the pi types. -/ @[simps] def pi (F : Π i, C i ⥤ D i) : (Π i, C i) ⥤ (Π i, D i) := { obj := λ f i, (F i).obj (f i), map := λ f g α i, (F i).map (α i) } -- One could add some natural isomorphisms showing -- how `functor.pi` commutes with `pi.eval` and `pi.comap`. end functor namespace nat_trans variables {C} variables {D : I → Type u₁} [∀ i, category.{v₁} (D i)] variables {F G : Π i, C i ⥤ D i} /-- Assemble an `I`-indexed family of natural transformations into a single natural transformation. -/ @[simps] def pi (α : Π i, F i ⟶ G i) : functor.pi F ⟶ functor.pi G := { app := λ f i, (α i).app (f i), } end nat_trans end category_theory
125edf360b471b68737e2540ef3f70752fcc787c
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/eq1.lean
5d3f426e6f0e0c86746e03b15563d379f35d1ab7
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
82
lean
import Int. variable i : Int check i = 0 set_option pp::coercion true check i = 0
620fd98f0ac879130a707c706e224a6e3d56e78d
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/analysis/calculus/implicit.lean
622726d32387ca0a5c62000ec597907cebdc56ef
[ "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
20,211
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import analysis.calculus.inverse import analysis.normed_space.complemented /-! # Implicit function theorem We prove three versions of the implicit function theorem. First we define a structure `implicit_function_data` that holds arguments for the most general version of the implicit function theorem, see `implicit_function_data.implicit_function` and `implicit_function_data.to_implicit_function`. This version allows a user to choose a specific implicit function but provides only a little convenience over the inverse function theorem. Then we define `implicit_function_of_complemented`: implicit function defined by `f (g z y) = z`, where `f : E → F` is a function strictly differentiable at `a` such that its derivative `f'` is surjective and has a `complemented` kernel. Finally, if the codomain of `f` is a finite dimensional space, then we can automatically prove that the kernel of `f'` is complemented, hence the only assumptions are `has_strict_fderiv_at` and `f'.range = ⊤`. This version is named `implicit_function`. ## TODO * Add a version for a function `f : E × F → G` such that $$\frac{\partial f}{\partial y}$$ is invertible. * Add a version for `f : 𝕜 × 𝕜 → 𝕜` proving `has_strict_deriv_at` and `deriv φ = ...`. * Prove that in a real vector space the implicit function has the same smoothness as the original one. * If the original function is differentiable in a neighborhood, then the implicit function is differentiable in a neighborhood as well. Current setup only proves differentiability at one point for the implicit function constructed in this file (as opposed to an unspecified implicit function). One of the ways to overcome this difficulty is to use uniqueness of the implicit function in the general version of the theorem. Another way is to prove that *any* implicit function satisfying some predicate is strictly differentiable. ## Tags implicit function, inverse function -/ noncomputable theory open_locale topological_space open filter open continuous_linear_map (fst snd smul_right ker_prod) open continuous_linear_equiv (of_bijective) /-! ### General version Consider two functions `f : E → F` and `g : E → G` and a point `a` such that * both functions are strictly differentiable at `a`; * the derivatives are surjective; * the kernels of the derivatives are complementary subspaces of `E`. Note that the map `x ↦ (f x, g x)` has a bijective derivative, hence it is a local homeomorphism between `E` and `F × G`. We use this fact to define a function `φ : F → G → E` (see `implicit_function_data.implicit_function`) such that for `(y, z)` close enough to `(f a, g a)` we have `f (φ y z) = y` and `g (φ y z) = z`. We also prove a formula for $$\frac{\partial\varphi}{\partial z}.$$ Though this statement is almost symmetric with respect to `F`, `G`, we interpret it in the following way. Consider a family of surfaces `{x | f x = y}`, `y ∈ 𝓝 (f a)`. Each of these surfaces is parametrized by `φ y`. There are many ways to choose a (differentiable) function `φ` such that `f (φ y z) = y` but the extra condition `g (φ y z) = z` allows a user to select one of these functions. If we imagine that the level surfaces `f = const` form a local horizontal foliation, then the choice of `g` fixes a transverse foliation `g = const`, and `φ` is the inverse function of the projection of `{x | f x = y}` along this transverse foliation. This version of the theorem is used to prove the other versions and can be used if a user needs to have a complete control over the choice of the implicit function. -/ /-- Data for the general version of the implicit function theorem. It holds two functions `f : E → F` and `g : E → G` (named `left_fun` and `right_fun`) and a point `a` (named `pt`) such that * both functions are strictly differentiable at `a`; * the derivatives are surjective; * the kernels of the derivatives are complementary subspaces of `E`. -/ @[nolint has_nonempty_instance] structure implicit_function_data (𝕜 : Type*) [nontrivially_normed_field 𝕜] (E : Type*) [normed_add_comm_group E] [normed_space 𝕜 E] [complete_space E] (F : Type*) [normed_add_comm_group F] [normed_space 𝕜 F] [complete_space F] (G : Type*) [normed_add_comm_group G] [normed_space 𝕜 G] [complete_space G] := (left_fun : E → F) (left_deriv : E →L[𝕜] F) (right_fun : E → G) (right_deriv : E →L[𝕜] G) (pt : E) (left_has_deriv : has_strict_fderiv_at left_fun left_deriv pt) (right_has_deriv : has_strict_fderiv_at right_fun right_deriv pt) (left_range : left_deriv.range = ⊤) (right_range : right_deriv.range = ⊤) (is_compl_ker : is_compl left_deriv.ker right_deriv.ker) namespace implicit_function_data variables {𝕜 : Type*} [nontrivially_normed_field 𝕜] {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] [complete_space E] {F : Type*} [normed_add_comm_group F] [normed_space 𝕜 F] [complete_space F] {G : Type*} [normed_add_comm_group G] [normed_space 𝕜 G] [complete_space G] (φ : implicit_function_data 𝕜 E F G) /-- The function given by `x ↦ (left_fun x, right_fun x)`. -/ def prod_fun (x : E) : F × G := (φ.left_fun x, φ.right_fun x) @[simp] lemma prod_fun_apply (x : E) : φ.prod_fun x = (φ.left_fun x, φ.right_fun x) := rfl protected lemma has_strict_fderiv_at : has_strict_fderiv_at φ.prod_fun (φ.left_deriv.equiv_prod_of_surjective_of_is_compl φ.right_deriv φ.left_range φ.right_range φ.is_compl_ker : E →L[𝕜] F × G) φ.pt := φ.left_has_deriv.prod φ.right_has_deriv /-- Implicit function theorem. If `f : E → F` and `g : E → G` are two maps strictly differentiable at `a`, their derivatives `f'`, `g'` are surjective, and the kernels of these derivatives are complementary subspaces of `E`, then `x ↦ (f x, g x)` defines a local homeomorphism between `E` and `F × G`. In particular, `{x | f x = f a}` is locally homeomorphic to `G`. -/ def to_local_homeomorph : local_homeomorph E (F × G) := φ.has_strict_fderiv_at.to_local_homeomorph _ /-- Implicit function theorem. If `f : E → F` and `g : E → G` are two maps strictly differentiable at `a`, their derivatives `f'`, `g'` are surjective, and the kernels of these derivatives are complementary subspaces of `E`, then `implicit_function_of_is_compl_ker` is the unique (germ of a) map `φ : F → G → E` such that `f (φ y z) = y` and `g (φ y z) = z`. -/ def implicit_function : F → G → E := function.curry $ φ.to_local_homeomorph.symm @[simp] lemma to_local_homeomorph_coe : ⇑(φ.to_local_homeomorph) = φ.prod_fun := rfl lemma to_local_homeomorph_apply (x : E) : φ.to_local_homeomorph x = (φ.left_fun x, φ.right_fun x) := rfl lemma pt_mem_to_local_homeomorph_source : φ.pt ∈ φ.to_local_homeomorph.source := φ.has_strict_fderiv_at.mem_to_local_homeomorph_source lemma map_pt_mem_to_local_homeomorph_target : (φ.left_fun φ.pt, φ.right_fun φ.pt) ∈ φ.to_local_homeomorph.target := φ.to_local_homeomorph.map_source $ φ.pt_mem_to_local_homeomorph_source lemma prod_map_implicit_function : ∀ᶠ (p : F × G) in 𝓝 (φ.prod_fun φ.pt), φ.prod_fun (φ.implicit_function p.1 p.2) = p := φ.has_strict_fderiv_at.eventually_right_inverse.mono $ λ ⟨z, y⟩ h, h lemma left_map_implicit_function : ∀ᶠ (p : F × G) in 𝓝 (φ.prod_fun φ.pt), φ.left_fun (φ.implicit_function p.1 p.2) = p.1 := φ.prod_map_implicit_function.mono $ λ z, congr_arg prod.fst lemma right_map_implicit_function : ∀ᶠ (p : F × G) in 𝓝 (φ.prod_fun φ.pt), φ.right_fun (φ.implicit_function p.1 p.2) = p.2 := φ.prod_map_implicit_function.mono $ λ z, congr_arg prod.snd lemma implicit_function_apply_image : ∀ᶠ x in 𝓝 φ.pt, φ.implicit_function (φ.left_fun x) (φ.right_fun x) = x := φ.has_strict_fderiv_at.eventually_left_inverse lemma map_nhds_eq : map φ.left_fun (𝓝 φ.pt) = 𝓝 (φ.left_fun φ.pt) := show map (prod.fst ∘ φ.prod_fun) (𝓝 φ.pt) = 𝓝 (φ.prod_fun φ.pt).1, by rw [← map_map, φ.has_strict_fderiv_at.map_nhds_eq_of_equiv, map_fst_nhds] lemma implicit_function_has_strict_fderiv_at (g'inv : G →L[𝕜] E) (hg'inv : φ.right_deriv.comp g'inv = continuous_linear_map.id 𝕜 G) (hg'invf : φ.left_deriv.comp g'inv = 0) : has_strict_fderiv_at (φ.implicit_function (φ.left_fun φ.pt)) g'inv (φ.right_fun φ.pt) := begin have := φ.has_strict_fderiv_at.to_local_inverse, simp only [prod_fun] at this, convert this.comp (φ.right_fun φ.pt) ((has_strict_fderiv_at_const _ _).prod (has_strict_fderiv_at_id _)), simp only [continuous_linear_map.ext_iff, continuous_linear_map.coe_comp', function.comp_app] at hg'inv hg'invf ⊢, simp [continuous_linear_equiv.eq_symm_apply, *] end end implicit_function_data namespace has_strict_fderiv_at section complemented /-! ### Case of a complemented kernel In this section we prove the following version of the implicit function theorem. Consider a map `f : E → F` and a point `a : E` such that `f` is strictly differentiable at `a`, its derivative `f'` is surjective and the kernel of `f'` is a complemented subspace of `E` (i.e., it has a closed complementary subspace). Then there exists a function `φ : F → ker f' → E` such that for `(y, z)` close to `(f a, 0)` we have `f (φ y z) = y` and the derivative of `φ (f a)` at zero is the embedding `ker f' → E`. Note that a map with these properties is not unique. E.g., different choices of a subspace complementary to `ker f'` lead to different maps `φ`. -/ variables {𝕜 : Type*} [nontrivially_normed_field 𝕜] {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] [complete_space E] {F : Type*} [normed_add_comm_group F] [normed_space 𝕜 F] [complete_space F] {f : E → F} {f' : E →L[𝕜] F} {a : E} section defs variables (f f') /-- Data used to apply the generic implicit function theorem to the case of a strictly differentiable map such that its derivative is surjective and has a complemented kernel. -/ @[simp] def implicit_function_data_of_complemented (hf : has_strict_fderiv_at f f' a) (hf' : f'.range = ⊤) (hker : f'.ker.closed_complemented) : implicit_function_data 𝕜 E F f'.ker := { left_fun := f, left_deriv := f', right_fun := λ x, classical.some hker (x - a), right_deriv := classical.some hker, pt := a, left_has_deriv := hf, right_has_deriv := (classical.some hker).has_strict_fderiv_at.comp a ((has_strict_fderiv_at_id a).sub_const a), left_range := hf', right_range := linear_map.range_eq_of_proj (classical.some_spec hker), is_compl_ker := linear_map.is_compl_of_proj (classical.some_spec hker) } /-- A local homeomorphism between `E` and `F × f'.ker` sending level surfaces of `f` to vertical subspaces. -/ def implicit_to_local_homeomorph_of_complemented (hf : has_strict_fderiv_at f f' a) (hf' : f'.range = ⊤) (hker : f'.ker.closed_complemented) : local_homeomorph E (F × f'.ker) := (implicit_function_data_of_complemented f f' hf hf' hker).to_local_homeomorph /-- Implicit function `g` defined by `f (g z y) = z`. -/ def implicit_function_of_complemented (hf : has_strict_fderiv_at f f' a) (hf' : f'.range = ⊤) (hker : f'.ker.closed_complemented) : F → f'.ker → E := (implicit_function_data_of_complemented f f' hf hf' hker).implicit_function end defs @[simp] lemma implicit_to_local_homeomorph_of_complemented_fst (hf : has_strict_fderiv_at f f' a) (hf' : f'.range = ⊤) (hker : f'.ker.closed_complemented) (x : E) : (hf.implicit_to_local_homeomorph_of_complemented f f' hf' hker x).fst = f x := rfl lemma implicit_to_local_homeomorph_of_complemented_apply (hf : has_strict_fderiv_at f f' a) (hf' : f'.range = ⊤) (hker : f'.ker.closed_complemented) (y : E) : hf.implicit_to_local_homeomorph_of_complemented f f' hf' hker y = (f y, classical.some hker (y - a)) := rfl @[simp] lemma implicit_to_local_homeomorph_of_complemented_apply_ker (hf : has_strict_fderiv_at f f' a) (hf' : f'.range = ⊤) (hker : f'.ker.closed_complemented) (y : f'.ker) : hf.implicit_to_local_homeomorph_of_complemented f f' hf' hker (y + a) = (f (y + a), y) := by simp only [implicit_to_local_homeomorph_of_complemented_apply, add_sub_cancel, classical.some_spec hker] @[simp] lemma implicit_to_local_homeomorph_of_complemented_self (hf : has_strict_fderiv_at f f' a) (hf' : f'.range = ⊤) (hker : f'.ker.closed_complemented) : hf.implicit_to_local_homeomorph_of_complemented f f' hf' hker a = (f a, 0) := by simp [hf.implicit_to_local_homeomorph_of_complemented_apply] lemma mem_implicit_to_local_homeomorph_of_complemented_source (hf : has_strict_fderiv_at f f' a) (hf' : f'.range = ⊤) (hker : f'.ker.closed_complemented) : a ∈ (hf.implicit_to_local_homeomorph_of_complemented f f' hf' hker).source := mem_to_local_homeomorph_source _ lemma mem_implicit_to_local_homeomorph_of_complemented_target (hf : has_strict_fderiv_at f f' a) (hf' : f'.range = ⊤) (hker : f'.ker.closed_complemented) : (f a, (0 : f'.ker)) ∈ (hf.implicit_to_local_homeomorph_of_complemented f f' hf' hker).target := by simpa only [implicit_to_local_homeomorph_of_complemented_self] using ((hf.implicit_to_local_homeomorph_of_complemented f f' hf' hker).map_source $ (hf.mem_implicit_to_local_homeomorph_of_complemented_source hf' hker)) /-- `implicit_function_of_complemented` sends `(z, y)` to a point in `f ⁻¹' z`. -/ lemma map_implicit_function_of_complemented_eq (hf : has_strict_fderiv_at f f' a) (hf' : f'.range = ⊤) (hker : f'.ker.closed_complemented) : ∀ᶠ (p : F × f'.ker) in 𝓝 (f a, 0), f (hf.implicit_function_of_complemented f f' hf' hker p.1 p.2) = p.1 := ((hf.implicit_to_local_homeomorph_of_complemented f f' hf' hker).eventually_right_inverse $ hf.mem_implicit_to_local_homeomorph_of_complemented_target hf' hker).mono $ λ ⟨z, y⟩ h, congr_arg prod.fst h /-- Any point in some neighborhood of `a` can be represented as `implicit_function` of some point. -/ lemma eq_implicit_function_of_complemented (hf : has_strict_fderiv_at f f' a) (hf' : f'.range = ⊤) (hker : f'.ker.closed_complemented) : ∀ᶠ x in 𝓝 a, hf.implicit_function_of_complemented f f' hf' hker (f x) (hf.implicit_to_local_homeomorph_of_complemented f f' hf' hker x).snd = x := (implicit_function_data_of_complemented f f' hf hf' hker).implicit_function_apply_image @[simp] lemma implicit_function_of_complemented_apply_image (hf : has_strict_fderiv_at f f' a) (hf' : f'.range = ⊤) (hker : f'.ker.closed_complemented) : hf.implicit_function_of_complemented f f' hf' hker (f a) 0 = a := begin convert (hf.implicit_to_local_homeomorph_of_complemented f f' hf' hker).left_inv (hf.mem_implicit_to_local_homeomorph_of_complemented_source hf' hker), exact congr_arg prod.snd (hf.implicit_to_local_homeomorph_of_complemented_self hf' hker).symm end lemma to_implicit_function_of_complemented (hf : has_strict_fderiv_at f f' a) (hf' : f'.range = ⊤) (hker : f'.ker.closed_complemented) : has_strict_fderiv_at (hf.implicit_function_of_complemented f f' hf' hker (f a)) f'.ker.subtypeL 0 := by convert (implicit_function_data_of_complemented f f' hf hf' hker).implicit_function_has_strict_fderiv_at f'.ker.subtypeL _ _; [skip, ext, ext]; simp [classical.some_spec hker] end complemented /-! ### Finite dimensional case In this section we prove the following version of the implicit function theorem. Consider a map `f : E → F` from a Banach normed space to a finite dimensional space. Take a point `a : E` such that `f` is strictly differentiable at `a` and its derivative `f'` is surjective. Then there exists a function `φ : F → ker f' → E` such that for `(y, z)` close to `(f a, 0)` we have `f (φ y z) = y` and the derivative of `φ (f a)` at zero is the embedding `ker f' → E`. This version deduces that `ker f'` is a complemented subspace from the fact that `F` is a finite dimensional space, then applies the previous version. Note that a map with these properties is not unique. E.g., different choices of a subspace complementary to `ker f'` lead to different maps `φ`. -/ section finite_dimensional variables {𝕜 : Type*} [nontrivially_normed_field 𝕜] [complete_space 𝕜] {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] [complete_space E] {F : Type*} [normed_add_comm_group F] [normed_space 𝕜 F] [finite_dimensional 𝕜 F] (f : E → F) (f' : E →L[𝕜] F) {a : E} /-- Given a map `f : E → F` to a finite dimensional space with a surjective derivative `f'`, returns a local homeomorphism between `E` and `F × ker f'`. -/ def implicit_to_local_homeomorph (hf : has_strict_fderiv_at f f' a) (hf' : f'.range = ⊤) : local_homeomorph E (F × f'.ker) := by haveI := finite_dimensional.complete 𝕜 F; exact hf.implicit_to_local_homeomorph_of_complemented f f' hf' f'.ker_closed_complemented_of_finite_dimensional_range /-- Implicit function `g` defined by `f (g z y) = z`. -/ def implicit_function (hf : has_strict_fderiv_at f f' a) (hf' : f'.range = ⊤) : F → f'.ker → E := function.curry $ (hf.implicit_to_local_homeomorph f f' hf').symm variables {f f'} @[simp] lemma implicit_to_local_homeomorph_fst (hf : has_strict_fderiv_at f f' a) (hf' : f'.range = ⊤) (x : E) : (hf.implicit_to_local_homeomorph f f' hf' x).fst = f x := rfl @[simp] lemma implicit_to_local_homeomorph_apply_ker (hf : has_strict_fderiv_at f f' a) (hf' : f'.range = ⊤) (y : f'.ker) : hf.implicit_to_local_homeomorph f f' hf' (y + a) = (f (y + a), y) := by apply implicit_to_local_homeomorph_of_complemented_apply_ker @[simp] lemma implicit_to_local_homeomorph_self (hf : has_strict_fderiv_at f f' a) (hf' : f'.range = ⊤) : hf.implicit_to_local_homeomorph f f' hf' a = (f a, 0) := by apply implicit_to_local_homeomorph_of_complemented_self lemma mem_implicit_to_local_homeomorph_source (hf : has_strict_fderiv_at f f' a) (hf' : f'.range = ⊤) : a ∈ (hf.implicit_to_local_homeomorph f f' hf').source := mem_to_local_homeomorph_source _ lemma mem_implicit_to_local_homeomorph_target (hf : has_strict_fderiv_at f f' a) (hf' : f'.range = ⊤) : (f a, (0 : f'.ker)) ∈ (hf.implicit_to_local_homeomorph f f' hf').target := by apply mem_implicit_to_local_homeomorph_of_complemented_target lemma tendsto_implicit_function (hf : has_strict_fderiv_at f f' a) (hf' : f'.range = ⊤) {α : Type*} {l : filter α} {g₁ : α → F} {g₂ : α → f'.ker} (h₁ : tendsto g₁ l (𝓝 $ f a)) (h₂ : tendsto g₂ l (𝓝 0)) : tendsto (λ t, hf.implicit_function f f' hf' (g₁ t) (g₂ t)) l (𝓝 a) := begin refine ((hf.implicit_to_local_homeomorph f f' hf').tendsto_symm (hf.mem_implicit_to_local_homeomorph_source hf')).comp _, rw [implicit_to_local_homeomorph_self], exact h₁.prod_mk_nhds h₂ end alias tendsto_implicit_function ← _root_.filter.tendsto.implicit_function /-- `implicit_function` sends `(z, y)` to a point in `f ⁻¹' z`. -/ lemma map_implicit_function_eq (hf : has_strict_fderiv_at f f' a) (hf' : f'.range = ⊤) : ∀ᶠ (p : F × f'.ker) in 𝓝 (f a, 0), f (hf.implicit_function f f' hf' p.1 p.2) = p.1 := by apply map_implicit_function_of_complemented_eq @[simp] lemma implicit_function_apply_image (hf : has_strict_fderiv_at f f' a) (hf' : f'.range = ⊤) : hf.implicit_function f f' hf' (f a) 0 = a := by apply implicit_function_of_complemented_apply_image /-- Any point in some neighborhood of `a` can be represented as `implicit_function` of some point. -/ lemma eq_implicit_function (hf : has_strict_fderiv_at f f' a) (hf' : f'.range = ⊤) : ∀ᶠ x in 𝓝 a, hf.implicit_function f f' hf' (f x) (hf.implicit_to_local_homeomorph f f' hf' x).snd = x := by apply eq_implicit_function_of_complemented lemma to_implicit_function (hf : has_strict_fderiv_at f f' a) (hf' : f'.range = ⊤) : has_strict_fderiv_at (hf.implicit_function f f' hf' (f a)) f'.ker.subtypeL 0 := by apply to_implicit_function_of_complemented end finite_dimensional end has_strict_fderiv_at
a00666136654471e4edf38c02d2e5b863cc8707a
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/category_theory/category/Kleisli.lean
736b45987fc722ad6c180c4605224eee1f286437
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,621
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 category_theory.category.basic /-! # The Kleisli construction on the Type category Define the Kleisli category for (control) monads. `category_theory/monad/kleisli` defines the general version for a monad on `C`, and demonstrates the equivalence between the two. ## TODO Generalise this to work with category_theory.monad -/ universes u v namespace category_theory /-- The Kleisli category on the (type-)monad `m`. Note that the monad is not assumed to be lawful yet. -/ @[nolint unused_arguments] def Kleisli (m : Type u → Type v) := Type u /-- Construct an object of the Kleisli category from a type. -/ def Kleisli.mk (m) (α : Type u) : Kleisli m := α instance Kleisli.category_struct {m} [monad.{u v} m] : category_struct (Kleisli m) := { hom := λ α β, α → m β, id := λ α x, pure x, comp := λ X Y Z f g, f >=> g } instance Kleisli.category {m} [monad.{u v} m] [is_lawful_monad m] : category (Kleisli m) := by refine { id_comp' := _, comp_id' := _, assoc' := _ }; intros; ext; unfold_projs; simp only [(>=>)] with functor_norm @[simp] lemma Kleisli.id_def {m} [monad m] (α : Kleisli m) : 𝟙 α = @pure m _ α := rfl lemma Kleisli.comp_def {m} [monad m] (α β γ : Kleisli m) (xs : α ⟶ β) (ys : β ⟶ γ) (a : α) : (xs ≫ ys) a = xs a >>= ys := rfl instance : inhabited (Kleisli id) := ⟨punit⟩ instance {α : Type u} [inhabited α] : inhabited (Kleisli.mk id α) := ⟨(default α : _)⟩ end category_theory
5930ac340bcdbb9b81275ff06753f9fb231cb516
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/doc/examples/NFM2022/nfm3.lean
3db250777703108b3c641cdfd2de34aa9119af06
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach" ]
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,357
lean
/- Enumerated types -/ inductive Weekday where | sunday | monday | tuesday | wednesday | thursday | friday | saturday #check Weekday.sunday -- Weekday open Weekday #check sunday def natOfWeekday (d : Weekday) : Nat := match d with | sunday => 1 | monday => 2 | tuesday => 3 | wednesday => 4 | thursday => 5 | friday => 6 | saturday => 7 def Weekday.next (d : Weekday) : Weekday := match d with | sunday => monday | monday => tuesday | tuesday => wednesday | wednesday => thursday | thursday => friday | friday => saturday | saturday => sunday def Weekday.previous : Weekday → Weekday | sunday => saturday | monday => sunday | tuesday => monday | wednesday => tuesday | thursday => wednesday | friday => thursday | saturday => friday /- Proving theorems using tactics -/ theorem Weekday.next_previous (d : Weekday) : d.next.previous = d := match d with | sunday => rfl | monday => rfl | tuesday => rfl | wednesday => rfl | thursday => rfl | friday => rfl | saturday => rfl theorem Weekday.next_previous' (d : Weekday) : d.next.previous = d := by -- switch to tactic mode cases d -- Creates 7 goals rfl; rfl; rfl; rfl; rfl; rfl; rfl theorem Weekday.next_previous'' (d : Weekday) : d.next.previous = d := by cases d <;> rfl
ab575e2013835d36074546fb06f0b83a7a1472ba
f3849be5d845a1cb97680f0bbbe03b85518312f0
/tests/lean/run/calc.lean
8fae77820940041adea25036b4e9e798e231a605
[ "Apache-2.0" ]
permissive
bjoeris/lean
0ed95125d762b17bfcb54dad1f9721f953f92eeb
4e496b78d5e73545fa4f9a807155113d8e6b0561
refs/heads/master
1,611,251,218,281
1,495,337,658,000
1,495,337,658,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
356
lean
namespace foo constant le : num → num → Prop axiom le_trans {a b c : num} : le a b → le b c → le a c attribute [trans] le_trans infix `<<`:50 := le end foo namespace foo theorem T {a b c d : num} : a << b → b << c → c << d → a << d := assume H1 H2 H3, calc a << b : H1 ... << c : H2 ... << d : H3 end foo
b9ad73e3dfa11ba30bc637caa6e50d6f03da3fb4
05d69962fb9deab19838de9bbcf33ebdbf8faa57
/mul_aux.lean
59d3e7e25253d73a6ee036106ee83e0867dda8c5
[]
no_license
pj0y1/polynom
6eb7c96dbf34960be5721a232a67f7a592aedf7a
9e198cc9104017fae7774574f141197bb295ee66
refs/heads/master
1,611,193,417,139
1,501,472,138,000
1,501,472,138,000
64,856,946
0
0
null
null
null
null
UTF-8
Lean
false
false
17,155
lean
import finsupp alg_aux open classical set prod.ops eq.ops open function comm_cancel_monoid set_option max_memory 2048 namespace function_aux variables {A B:Type} section commutativity --1 variables [comm_semigroup A][comm_semiring B] /- for polynoms to be commutative, B has to be comm_ring-/ theorem mul_comm (f g: A -> B)[finite (supp f)][finite (supp g)]: mul f g = mul g f := funext (λa, by rewrite [↑function.mul,Sum_exchange]; apply Sum_ext;intro x hx;apply Sum_ext;intro y hy;simp) -- thus in sum.lean eq_sum_of_eq_fun obsoleted end commutativity section assoc --2 open eq.ops variables [comm_cancel_monoid A][semiring B] variables (f g k:A -> B)(m n: A) variables [finite (supp f)][finite (supp g)][finite (supp k)] section --assoc_from_right_aux variables {C:Type}{p: C -> Prop} theorem ite_exchange {c:C}(u v:B): (ite (p c) (1:B) 0)*(u * v) = u * ((ite (p c) (1:B) 0) * v) := or.elim (em (p c)) (λh, by rewrite (if_pos h);simp) (λh, by rewrite (if_neg h);simp) theorem ite_exchange_Sum1{s: set C}{u:B}{v:C-> B}: (∑x∈s, (ite (p x) (1:B) 0)*(u * v x)) = ∑x∈s,u * ((ite (p x) (1:B) 0) * v x) := Sum_ext(λx hx, or.elim (em (p x)) (λh, by rewrite (if_pos h);simp) (λh, by rewrite (if_neg h);simp)) theorem ite_exchange_Sum2 {q: C -> C -> Prop}{s t: set C}{u:B}{v w:C -> B}: (∑x∈s, ∑y∈t, (ite (q x y) 1 0)*(u *(v x * w y))) = ∑x∈s, ∑y∈t, u*((ite (q x y) 1 0)*(v x * w y)):= Sum_ext (λx hx, Sum_ext (λy hy, or.elim (em (q x y)) (λh, by rewrite (if_pos h);simp) (λh, by rewrite (if_neg h);simp))) theorem mul_Sum2 {s t: set C}{u:B}{f:C-> C-> B}: (∑x∈s,∑y∈t, u * f x y) = u*(∑x∈s,∑y∈t, f x y) := by rewrite (semiring.mul_Sum _);apply Sum_ext;intros x hx; rewrite (semiring.mul_Sum _) end lemma assoc_aux1_aux {s: set A}[finite s]{fx gx: A-> B}: (∑x∈s\supp gx, (fx x)*(gx x)) = ∑x∈s\supp gx, 0 := Sum_ext (λx h, have x∉supp gx, from not_mem_of_mem_diff h, by rewrite [-(eq_zero_eq_not_mem_supp gx x) at this,this]; apply semiring.mul_zero) theorem assoc_aux1 {t:A -> B}: (∑x∈supp(mul f g),(t x)*(mul f g x))= ∑x∈img f g, (t x)*(mul f g x) := have finite(img f g), from !finite_img, have h:supp (mul f g)⊆ img f g, from mul_supp_subset_img f g, by rewrite [(@Sum_reduced_aux1 _ _ _ (img f g) (supp (mul f g)) _ _), (subset_inter_eq_self h),assoc_aux1_aux,Sum_zero];simp lemma assoc_aux2_aux: preimage (uncurry mul) (λx:A, m = n * x) = (λx:A×A, m = n* (x.1 * x.2)) := ext (λt, iff.intro (λl, have (uncurry mul) t ∈ (λx:A, m = mul n x), from (mem_of_mem_preimage l), have h1:m = n* (uncurry mul t), from this, have uncurry mul t = t.1 * t.2, from proof match t with (a,b) := rfl end qed, have m = n* (t.1 * t.2), by rewrite [-this,h1], show (λx:A×A, m = n * (x.1 * x.2)) t, from this) (λr, have h1: m = n * (t.1 * t.2), from r, have t.1 * t.2 = uncurry mul t, from proof match t with (a,b) := rfl end qed, have m = n * (uncurry mul t), by rewrite [-this, h1], have uncurry mul t ∈ (λx:A, m = n * x), from this, mem_preimage this)) lemma equiv_pred_curry : (λx:A×A,m = (x.1*x.2)*n) = (λx:A×A, m =n*(x.1*x.2)) := ext (λx, iff.intro (λ l, have m = (x.1*x.2)*n, from l, show x∈(λx, m = n*(x.1*x.2)), from eq.trans this (comm_cancel_monoid.mul_comm (x.1*x.2) n)) (λ r, have m = n* (x.1 *x.2), from r, show x∈(λx, m = (x.1*x.2)*n), from eq.trans this (comm_cancel_monoid.mul_comm n (x.1*x.2))) ) theorem assoc_aux2: (img f g)∩(λx, m=n*x) = image (uncurry mul) (supp f * supp g ∩ (λx,m=n*(x.1*x.2))):= by rewrite [-(assoc_aux2_aux m n)];apply image_inter corollary assoc_aux2_cor1: -- originally lem6 in nind.lean (img f g)∩(λx, m=n*x) = ∅ ↔ (supp f * supp g ∩ (λx,m=n*(x.1*x.2))) = ∅ := iff.intro (λl, by rewrite [(assoc_aux2 f g m n) at l]; apply (empty_of_empty_image l)) (λr, by rewrite [(assoc_aux2 f g m n),r,image_empty]) corollary assoc_aux2_cor2: -- lem8 in nind.lean (img f g)∩(λx,m=n*x) ≠ ∅ -> ∃ u:A, (img f g)∩(λx,m=n*x) = '{u} ∧ ∀v:A×A, v∈supp f*supp g∩(λp,m=n*(p.1*p.2)) -> u = v.1*v.2 := λh, obtain (u:A)(hu: u∈(img f g)∩(λx,m=n*x)), from exists_mem_of_ne_empty h, have h1: u∈(λx,m=n*x), from and.right hu, have h2:(λx,m=n*x) = '{u}, from proof or.elim (empty_or_singleton_right m n) (λh, absurd h (ne_empty_of_mem h1)) (λh, obtain (v:A)(hv:(λx,m=n*x)='{v}), from h, have u = v, from eq_of_mem_singleton (hv ▸ h1), by rewrite [-this at hv];exact hv) qed, have h3:(img f g)∩(λx,m=n*x) = '{u}, from proof have (img f g)∩'{u} = '{u}, from or.elim (@empty_or_singleton_of_inter_singleton _ u (img f g)) (λh, absurd h (ne_empty_of_mem (h2 ▸ hu))) (λh, h), h2⁻¹ ▸ this qed, have h4:(λx:A×A, uncurry mul x) = (λx, x.1 * x.2), from funext (λx, match x with (a,b) := rfl end), have ∀v:A×A, v∈(supp f * supp g)∩(λx,m=n*(x.1*x.2))-> u= v.1 * v.2, by apply singleton_image';rewrite [-h4,-(assoc_aux2 f g m n),h3], exists.intro u (and.intro h3 this) lemma assoc_aux3_aux {u:A}(h:m=n*u): (λx,m=n*(x.1*x.2)) = (λx,u=x.1*x.2) := ext (λ x, iff.intro (λl, have m=n*(x.1*x.2), from l, have n*u = n*(x.1 * x.2), from h ▸ this, comm_cancel_monoid.mul_left_cancel _ _ _ this) (λr, have u=x.1*x.2, from r, show m=n*(x.1*x.2), by rewrite [-this,h])) theorem assoc_aux3_right: (∑x∈(img f g)∩(λx,m=n*x), mul f g x) = ∑x∈supp f * supp g ∩(λx, m=n*(x.1*x.2)), (f x.1)*(g x.2) := have finite (supp f * supp g), from finite_product, or.elim (em (img f g ∩ (λx:A, m = n*x) = ∅) ) (λ he, by rewrite [he,(iff.mp (assoc_aux2_cor1 f g m n) he),*Sum_empty]) (λ hne,obtain (u:A) hu, from assoc_aux2_cor2 _ _ _ _ hne, have h1:m = n * u, from proof show u∈(λx,m=n*x), from mem_of_mem_inter_right ((and.left hu)⁻¹ ▸ (mem_singleton u)) qed, have h2: (λx,(ite (u=x.1*x.2) 1 0)*(f x.1 * g x.2)) = uncurry (λ x y, (ite (u=x * y) 1 0)*(f x * g y)), by rewrite -(uncurry_curry _), by rewrite [(and.left hu),Sum_singleton,(assoc_aux3_aux m n h1), -Sum_reduced,↑function.mul,h2,-Sum_uncurry]) theorem assoc_aux3_left: (∑x∈(img f g)∩(λx,m=x*n), mul f g x) = ∑x∈supp f * supp g ∩(λx, m=(x.1*x.2)*n), (f x.1)*(g x.2) := by rewrite [(equiv_pred m n),(equiv_pred_curry m n)];apply assoc_aux3_right theorem assoc_aux3_general_right: (∑x∈(img f g), (ite (m=n*x) 1 0)*(mul f g x)) = ∑x∈supp f * supp g, (ite (m=n*(x.1*x.2)) 1 0)*(f x.1* g x.2) := have finite (img f g), from finite_img f g, have finite (supp f * supp g), from finite_product, by rewrite [*Sum_reduced,assoc_aux3_right] theorem assoc_aux3_general_left: (∑x∈(img f g), (ite (m=x*n) 1 0)*(mul f g x)) = ∑x∈supp f * supp g, (ite (m=(x.1*x.2)*n) 1 0)*(f x.1* g x.2) := have finite (img f g), from finite_img f g, have finite (supp f * supp g), from finite_product, by rewrite [*Sum_reduced,assoc_aux3_left] theorem assoc_from_right: (∑x∈supp k, ∑y∈supp(mul f g), (ite (m=x*y) 1 0)*(k x * mul f g y))= ∑x∈supp k,∑y∈supp f,∑z∈supp g, (ite (m=x*(y*z)) 1 0)*(k x *(f y * g z)) := Sum_ext (λx hx, let f' := (λt,(ite (m=x*(t.1*t.2)) 1 0)*(f t.1 * g t.2)) in by rewrite [ite_exchange_Sum1, -(semiring.mul_Sum _ (k x)), ite_exchange_Sum2,mul_Sum2, assoc_aux1, (assoc_aux3_general_right f g m x), (@Sum_curry _ _ _ _ _ _ f' _ _ _ _)]) /-right direction-/ theorem assoc_from_left_aux1 : (∑x∈supp(mul k f),∑y∈supp g,(ite (m=x*y) 1 0)*(mul k f x * g y)) = ∑y∈supp g,(∑x∈supp (mul k f),(ite (m=x*y) 1 0)*(mul k f x)) * g y := have finite (supp (mul k f)), from mul_finite_supp, by rewrite [Sum_exchange];apply Sum_ext;intros x hx; rewrite (semiring.Sum_mul _);apply Sum_ext;intros y hy;simp theorem assoc_from_left_aux2: (∑x∈supp (mul k f),(ite (m=x*n) 1 0)*(mul k f x)) = ∑x∈supp k,∑y∈supp f, (ite (m=(x*y)*n) 1 0)*(k x * f y):= let f' := (λt,(ite (m=(t.1*t.2)*n) 1 0)*(k t.1 * f t.2)) in by rewrite [assoc_aux1,assoc_aux3_general_left,(@Sum_curry _ _ _ _ _ _ f' _ _ _ _)] theorem assoc_from_left_aux3: (∑y∈supp g,(∑x∈supp (mul k f),(ite (m=x*y) 1 0)*(mul k f x)) * g y)= ∑y∈supp g,∑x∈supp k,∑z∈supp f,((ite (m=(x*z)*y) 1 0)*(k x * f z))* g y := Sum_ext (λy hy, by rewrite [assoc_from_left_aux2,(semiring.Sum_mul _)]; apply Sum_ext; intros x hx;rewrite (semiring.Sum_mul _)) theorem assoc_from_left_aux4: (∑y∈supp g,∑x∈supp k,∑z∈supp f,((ite (m=(x*z)*y) 1 0)*(k x * f z))* g y) = ∑x∈supp k,∑y∈supp g,∑z∈supp f,((ite (m=(x*z)*y) 1 0)*(k x * f z))* g y := by rewrite Sum_exchange theorem assoc_from_left_aux5: (∑x∈supp k,∑y∈supp g,∑z∈supp f,((ite (m=(x*z)*y) 1 0)*(k x * f z))* g y) = ∑x∈supp k,∑z∈supp f,∑y∈supp g,((ite (m=(x*z)*y) 1 0)*(k x * f z))* g y:= by apply Sum_ext; intros x hx; rewrite Sum_exchange theorem assoc_from_left: (∑x∈supp(mul k f),∑y∈supp g,(ite (m=x*y) 1 0)*(mul k f x * g y)) = ∑x∈supp k,∑y∈supp f,∑z∈supp g, ((ite (m=(x*y)*z) 1 0)*(k x *f y)) * g z := have finite (supp (mul k f)), from mul_finite_supp, (assoc_from_left_aux1 f g k m) ⬝ (assoc_from_left_aux3 f g k m) ⬝ (assoc_from_left_aux4 f g k m) ⬝ (assoc_from_left_aux5 f g k m) theorem mul_assoc_aux: (∑x∈supp k,∑y∈supp f,∑z∈supp g, (ite (m=x*(y*z)) 1 0)*(k x *(f y * g z))) = ∑x∈supp k,∑y∈supp f,∑z∈supp g, ((ite (m=(x*y)*z) 1 0)*(k x *f y)) * g z := Sum_ext (λx hx, Sum_ext (λy hy, Sum_ext (λz hz, by simp))) theorem mul_assoc_aux1 : mul k (mul f g) m = ∑x∈supp k, ∑y∈supp(mul f g), (ite (m=x*y) 1 0)*(k x * mul f g y) := by rewrite [↑mul at {1}] theorem mul_assoc_aux2 : mul (mul k f) g m = ∑x∈supp(mul k f),∑y∈supp g,(ite (m=x*y) 1 0)*(mul k f x * g y) := by rewrite [↑mul at {1}] theorem mul_assoc : mul (mul f g) k = mul f (mul g k) := funext (λm, (mul_assoc_aux2 g k f m) ⬝ (assoc_from_left g k f m) ⬝ (mul_assoc_aux g k f m)⁻¹ ⬝ (assoc_from_right g k f m)⁻¹ ⬝ (mul_assoc_aux1 g k f m)⁻¹) end assoc section one --3 variables [monoid A][semiring B] variables (f: A -> B)[finite (supp f)](a:A) -- mul_one and one_mul aux theorem singleton_of_one_eq_zero (H:(0:B)=(1:B)): ∀x:B, x=(0:B):= λx, show x = (0:B), from calc x = x * (1:B) : !semiring.mul_one ... = x * (0:B) : H ... = 0 : !semiring.mul_zero lemma singleton_rfl: (λx, a=x) = '{a} := ext (λx,iff.intro (λl, have a = x, from l, show x∈'{a}, from mem_singleton_of_eq (eq.symm this)) (λr, have x=a, from eq_of_mem_singleton r, show x∈(λx,a=x), from (eq.symm this))) lemma mul_one_aux2 : (∑x∈supp f, (ite (a=x) 1 0)*(f x))= f a := have H:(∑x∈supp f∩'{a}, f x) = f a, from proof or.elim (@empty_or_singleton_of_inter_singleton _ a (supp f)) (λh, have h1:a ∈'{a}, from mem_singleton a, have h2: a∉ supp f ∩'{a}, by rewrite h; apply not_mem_empty, have h3: a∉ supp f, from not_mem_of_mem_of_not_mem_inter_right h1 h2, by rewrite [-eq_zero_eq_not_mem_supp at h3,h3,h,Sum_empty]) (λh, by rewrite [h,Sum_singleton]) qed, by rewrite [Sum_reduced,(singleton_rfl a),H] lemma mul_one_aux1 : (∑y∈supp f, (ite (a=y * 1) 1 0)*(f y * 1)) = ∑y∈supp f, (ite (a=y) 1 0)*(f y):= Sum_ext (λy hy, have h1:f y * 1 = f y, by simp, have h2:y * 1 = y, by simp, by rewrite [h1,h2]) theorem mul_one : mul f (@one A B _ _) = f := funext (λ a, or.elim (em ((0:B) = (1:B))) (λhe, have h1:f a = (0:B), from singleton_of_one_eq_zero he (f a), have h2:mul f one a = (0:B), from singleton_of_one_eq_zero he _, by rewrite [h2,h1]) (λhne, have H:(0:B)≠(1:B), from hne, have finite (supp (@one A B _ _)), from one_finite_supp, have one (1:A) = (1:B), from if_pos rfl, by rewrite [↑function.mul, Sum_exchange, (one_supp_singleton H), Sum_singleton,this,(mul_one_aux1 _ _),(mul_one_aux2 _ _)])) theorem one_mul_aux : (∑y∈ supp f, (ite (a= 1*y) 1 0)*(1 * f y)) = ∑y∈ supp f, (ite (a=y) 1 0)*(f y) := Sum_ext (λy hy, have h1:1*y = y, by simp, have h2: 1* f y = f y,by simp, by rewrite [h1,h2]) theorem one_mul : mul (@one A B _ _) f = f := funext (λa, or.elim (em ((0:B) = (1:B))) (λhe, have h1:f a = (0:B), from singleton_of_one_eq_zero he (f a), have h2:(mul one f) a = (0:B), from singleton_of_one_eq_zero he (mul one f a), by rewrite [-h1 at h2,h2]) (λhne, have h:(0:B)≠(1:B), from hne, have one (1:A) = (1:B), from if_pos rfl, by rewrite [↑function.mul,(one_supp_singleton h),Sum_singleton, this,(one_mul_aux _ _),(mul_one_aux2 _ _)] )) end one section distrib --4 variables [has_mul A][semiring B](f g k: A -> B) variables [finite (supp f)][finite (supp g)][finite (supp k)] lemma mul_distrib_aux{f g: A -> B}: ∀a:A, (f + g) a = f a + g a := λa, rfl lemma mul_distrib_left_aux {s: set A}[finite s]{g: A->B}(f:A->B) (w:B)(H: supp f ⊆ s): (∑x∈s,(g x)*(w * f x)) =∑x∈supp f, (g x)*(w * f x) := have h:∀t,t∈ s\supp f -> (g t)*(w * f t)= 0, from proof λt ht, have t∉ supp f, from not_mem_of_mem_diff ht, have f t = 0, by rewrite eq_zero_eq_not_mem_supp;exact this, by rewrite this;simp qed, by rewrite [(Sum_reduced_flex h),(subset_inter_eq_self H)] lemma mul_distrib_left_aux1 {s:set A}{k:A -> B}(f g:A -> B)(w:B): (∑x∈s, (k x)*(w * ((f+g) x) )) = ∑x∈s,((k x)*(w * f x) + (k x)*(w * g x)) := Sum_ext (λx h, calc (k x)*(w * ((f + g) x)) = (k x)*(w * (f x + g x)): mul_distrib_aux ... = (k x)*((w * f x) + (w * g x)): left_distrib ... = (k x)*(w * f x) + (k x)*(w * g x): left_distrib) theorem mul_left_distrib : mul f (g + k) = (mul f g) + (mul f k) := funext (λm, have finite (supp g ∪ supp k), from !finite_union, have h1:supp (g+k) ⊆ supp g ∪ supp k, from add_supp_subset_union, have h2:supp g ⊆ supp g ∪ supp k, by apply subset_union_left, have h3:supp k ⊆ supp g ∪ supp k, by apply subset_union_right, by rewrite [mul_distrib_aux,↑function.mul, -Sum_add]; apply Sum_ext;intros x hx; rewrite [-(mul_distrib_left_aux (g+k) (f x) h1), (mul_distrib_left_aux1 g k (f x)),Sum_add, (mul_distrib_left_aux g (f x) h2), (mul_distrib_left_aux k (f x) h3)]) lemma mul_distrib_right_aux {s: set A}[finite s]{g: A->B}(f:A->B) (w:B)(H: supp f ⊆ s): (∑x∈s,(g x)*(f x * w)) =∑x∈supp f, (g x)*(f x * w) := have h:∀t,t∈ s\supp f -> (g t)*(f t * w)= 0, from proof λt ht, have t∉ supp f, from not_mem_of_mem_diff ht, have f t = 0, by rewrite eq_zero_eq_not_mem_supp;exact this, by rewrite this;simp qed, by rewrite [(Sum_reduced_flex h),(subset_inter_eq_self H)] lemma mul_distrib_right_aux2 (s t: set A)[finite s]{g: A -> A->B}(f k:A->B) (H: supp f ⊆ s): (∑y∈t,∑x∈s,(g y x)*(f x * k y)) =∑y∈t,∑x∈supp f, (g y x)*(f x * k y) := Sum_ext (λy hy,mul_distrib_right_aux f (k y) H) lemma mul_distrib_right_aux1 {s:set A}{k:A-> B}(f g:A -> B)(w:B): (∑x∈s, (k x)*(((f+g) x) * w )) = ∑x∈s,((k x)*(f x * w) + (k x)*(g x * w)) := Sum_ext (λx h, calc (k x)*( ((f + g) x) * w) = (k x)*((f x + g x) * w): mul_distrib_aux ... = (k x)*((f x * w) + (g x) * w): right_distrib ... = (k x)*(f x * w) + (k x)*(g x * w): left_distrib) theorem mul_right_distrib : mul (f + g) k = (mul f k) + (mul g k) := funext (λm, have finite (supp f ∪ supp g), from !finite_union, have h1:supp (f+g) ⊆ supp f ∪ supp g, from add_supp_subset_union, have finite (supp (f+g)), from add_finite_supp, have h2:supp f ⊆ supp f ∪ supp g, by apply subset_union_left, have h3:supp g ⊆ supp f ∪ supp g, by apply subset_union_right, by rewrite [mul_distrib_aux,↑function.mul, (@Sum_exchange _ _ _ _ _ _ _ (supp f) (supp k) _ _), (@Sum_exchange _ _ _ _ _ _ _ (supp g) (supp k) _ _), -(mul_distrib_right_aux2 _ _ _ _ h2), -(mul_distrib_right_aux2 _ _ _ _ h3),-Sum_add, (@Sum_exchange _ _ _ _ _ _ _ (supp (f+g)) (supp k) _ _)]; apply Sum_ext;intros x hx; rewrite [-Sum_add,-(mul_distrib_right_aux1 f g (k x)), (mul_distrib_right_aux (f+g) (k x) h1)]) end distrib section -- zero_mul variables [has_mul A][semiring B](f : A -> B) variable [finite (supp f)] theorem mul_zero: mul f zero = zero := funext (λa, by rewrite [↑function.mul, zero_empty_supp, ↑function.zero,Sum_exchange,Sum_empty]) theorem zero_mul: mul zero f = zero := funext (λa, by rewrite [↑function.mul,zero_empty_supp,Sum_empty]) end end function_aux
6870a4a8d1bf2b48abb6e012666eaf56e649eb3f
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch5/ex0602.lean
82fcf5c912ec5bfc3b0266eb00505cddc637834c
[]
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
128
lean
example (x y : ℕ) (p : ℕ → Prop) (q : Prop) (h : q → x = y) (h' : p y) (hq : q) : p x := by { rw (h hq), assumption }
8dce62e66f2ec730cbe6b234c8d9ad2332d3bbf6
a721fe7446524f18ba361625fc01033d9c8b7a78
/src/principia/topology/connectedness.lean
7911b259feaf7138cb2c0e52016ec974c980fbbc
[]
no_license
Sterrs/leaning
8fd80d1f0a6117a220bb2e57ece639b9a63deadc
3901cc953694b33adda86cb88ca30ba99594db31
refs/heads/master
1,627,023,822,744
1,616,515,221,000
1,616,515,221,000
245,512,190
2
0
null
1,616,429,050,000
1,583,527,118,000
Lean
UTF-8
Lean
false
false
15,263
lean
import .topological_space import .continuity namespace hidden namespace topological_space variables {α β : Type} open classical local attribute [instance] classical.prop_decidable structure disconnects (X : topological_space α) (U V: myset α): Prop := (neq_empty_left: U ≠ ∅) (neq_empty_right: V ≠ ∅) (open_left: X.is_open U) (open_right: X.is_open V) (disjoint: U ∩ V = ∅) (cover: U ∪ V = myset.univ) def is_disconnected (X: topological_space α): Prop := ∃ U V: myset α, disconnects X U V def is_connected (X : topological_space α) : Prop := ¬is_disconnected X theorem disconnect_clopen (X: topological_space α) (U V: myset α): disconnects X U V → X.is_closed U ∧ X.is_closed V := begin assume h, cases h with _ _ hUo hVo hUVdsj hUVcov, -- also a candidate for myset have: U.compl = V, { apply myset.setext, intro x, split, { assume hx, have: x ∈ U ∪ V, { rw hUVcov, trivial, }, cases this with hU hV, { contradiction, }, { assumption, }, }, { assume hx hUx, have: x ∈ U ∩ V, { split; assumption, }, rw hUVdsj at this, from this, }, }, rw ←myset.compl_compl U, conv { congr, rw this, skip, rw ←this, }, unfold is_closed, repeat {rw myset.compl_compl}, split; assumption, end theorem surjective_image_connected (X: topological_space α) (Y: topological_space β) (f: α → β) (hfc: is_continuous X Y f) (hsurj: function.surjective f): is_connected X → is_connected Y := begin assume hXc, assume himdc, cases himdc with U himdc, cases himdc with V himdc, have hpreUo := hfc U himdc.open_left, have hpreVo := hfc V himdc.open_right, apply hXc, existsi (myset.inverse_image f U), existsi (myset.inverse_image f V), split, { assume hpreUe, have hUne := himdc.neq_empty_left, rw ←myset.exists_iff_neq_empty at hUne, rw ←myset.empty_iff_eq_empty at hpreUe, cases hUne with y hy, cases hsurj y with x hx, apply hpreUe x, rw ←hx at hy, from hy, }, { have hVne := himdc.neq_empty_right, assume hpreVe, rw ←myset.exists_iff_neq_empty at hVne, rw ←myset.empty_iff_eq_empty at hpreVe, cases hVne with y hy, cases hsurj y with x hx, apply hpreVe x, rw ←hx at hy, from hy, }, { from hfc U himdc.open_left, }, { from hfc V himdc.open_right, }, { rw ←myset.inverse_image_intersection, rw himdc.disjoint, refl, }, { rw ←myset.inverse_image_union, rw himdc.cover, have := myset.inverse_image_of_image_of_univ (myset.function_restrict_to_image f), rw myset.to_image_surjective at this, from this.symm, }, end theorem image_connected (X: topological_space α) (Y: topological_space β) (f: α → β) (hfc: is_continuous X Y f) (hconn: is_connected X): is_connected (Y.subspace_topology (myset.imageu f)) := begin apply surjective_image_connected X _ (myset.function_restrict_to_image f), { apply continuous_to_image, from hfc, }, { intro y, cases y.property with x hx, existsi x, apply subtype.eq, from hx, }, { from hconn, } end theorem discrete_disconnected (x y: α) (hxy: x ≠ y): is_disconnected (discrete_topology α) := begin existsi {z | z = x}, existsi {z | z ≠ x}, split, { rw ←myset.exists_iff_neq_empty, existsi x, from rfl, }, { rw ←myset.exists_iff_neq_empty, existsi y, change ¬(x = y) at hxy, from λ h, hxy h.symm, }, { trivial, }, { trivial, }, { apply myset.setext, intro z, split; assume h, { cases h, contradiction, }, { exfalso, from h, }, }, { apply myset.setext, intro z, split; assume h, { trivial, }, { apply decidable.em, }, }, end theorem indiscrete_connected: is_connected (indiscrete_topology α) := begin assume hdc, cases hdc with U hdc, cases hdc with V hdc, cases hdc with hUne hVne hUo hVo hUVdj hUVcov, cases hUo with hU hU, { contradiction, }, { cases hVo with hV hV, { contradiction, }, { rw ←myset.exists_iff_neq_empty at hUne, rw ←myset.exists_iff_neq_empty at hVne, cases hUne with x hxU, cases hVne with y hyU, rw ←myset.empty_iff_eq_empty at hUVdj, apply hUVdj x, split, { assumption, }, { rw hV, trivial, }, }, }, end theorem empty_connected (X: topological_space α): is_connected (subspace_topology X ∅) := begin rw ←empty_indiscrete, apply indiscrete_connected, end theorem singleton_connected (X: topological_space α) (x: α): is_connected (subspace_topology X (myset.singleton x)) := begin rw ←singleton_indiscrete, apply indiscrete_connected, end -- maybe split up more to avoid cpu stress theorem connected_iff_N_image_const (X: topological_space α): is_connected X ↔ ∀ f: α → mynat, is_continuous X (discrete_topology mynat) f → ∀ x y: α, f x = f y := begin split, { assume hXc, intro f, assume hfc, intros x y, by_contradiction hfxfy, apply hXc, existsi myset.inverse_image f {n | n = f x}, existsi myset.inverse_image f {n | n ≠ f x}, split, { rw ←myset.exists_iff_neq_empty, existsi x, from rfl, }, { rw ←myset.exists_iff_neq_empty, existsi y, assume h, from hfxfy h.symm, }, { apply hfc, trivial, }, { apply hfc, trivial, }, { rw ←myset.inverse_image_intersection, apply myset.inverse_image_empty, apply myset.setext, intro z, split, { assume h, cases h, contradiction, }, { assume h, exfalso, from h, }, }, { apply myset.setext, intro z, split, { assume h, trivial, }, { assume h, apply decidable.em, }, }, }, { assume hfNc, assume hXdc, cases hXdc with U hXdc, cases hXdc with V hXdc, suffices: ∃ (f : α → mynat), is_continuous X (discrete_topology mynat) f ∧ ∃ (x y : α), f x ≠ f y, { cases this with f hf, cases hf with hfc hxy, cases hxy with x hxy, cases hxy with y hxy, apply hxy, apply hfNc, assumption, }, { existsi (λ x, if x ∈ U then (0: mynat) else 1), split, { have := disconnect_clopen _ _ _ hXdc, apply gluing_lemma X _ U V, { from this.left, }, { from this.right, }, { from hXdc.cover, }, { suffices hconst: (λ (x : subtype U), ite (↑x ∈ U) (0: mynat) 1) = (λ x, 0), { rw hconst, apply constant_continuous, }, { apply funext, intro x, have hxU: (↑x ∈ U) := x.property, rw if_pos hxU, }, }, { suffices hconst: (λ (x : subtype V), ite (↑x ∈ U) (0: mynat) 1) = (λ x, 1), { rw hconst, apply constant_continuous, }, { apply funext, intro x, have hxU: (↑x ∉ U), { assume hxU, have hUVx: ↑x ∈ U ∩ V, { split, { assumption, }, { from x.property, }, }, rw hXdc.disjoint at hUVx, from hUVx, }, rw if_neg hxU, }, }, }, { cases hXdc with hUne hVne _ _ hUVdisj, rw ←myset.exists_iff_neq_empty at hUne, rw ←myset.exists_iff_neq_empty at hVne, cases hUne with x hx, cases hVne with y hy, existsi x, existsi y, simp, rw if_pos hx, have hyU: y ∉ U, { assume hyU, have: y ∈ U ∩ V, { split; assumption, }, rw hUVdisj at this, from this, }, rw if_neg hyU, from mynat.zero_ne_one, }, }, }, end -- so it gets it from the other equality for you private lemma transitivity' {α: Type} {x y z w: α}: y = z → x = y → z = w → x = w := begin assume hyz hxy hzw, transitivity z, transitivity y, all_goals {assumption}, end -- does this even end up being faster (: theorem s_union_of_overlapping_connected (X: topological_space α) (S: myset (myset α)) (hconn: ∀ U: myset α, U ∈ S → is_connected (subspace_topology X U)) (hlap: ∀ U V: myset α, U ∈ S → V ∈ S → U ∩ V ≠ ∅): is_connected (subspace_topology X (⋃₀ S)) := begin rw connected_iff_N_image_const, intro f, assume hfc, intros x y, cases x.property with U hU, cases hU with hU hxU, cases y.property with V hV, cases hV with hV hxV, have hUVdsj := hlap U V hU hV, rw ←myset.exists_iff_neq_empty at hUVdsj, cases hUVdsj with z hz, have hUcon := hconn U hU, have hVcon := hconn V hV, rw connected_iff_N_image_const at hUcon, rw connected_iff_N_image_const at hVcon, transitivity f (⟨z, ⟨U, ⟨hU, hz.left⟩⟩⟩: subtype (⋃₀ S)), { have step1 := hUcon (λ x: subtype U, f ⟨x, ⟨U, ⟨hU, x.property⟩⟩⟩), let g := (λ x: subtype U, f ⟨x, ⟨U, ⟨hU, x.property⟩⟩⟩), have h_elp_me: is_continuous (subspace_topology X U) (discrete_topology mynat) g, { apply composition_continuous (subspace_topology X U) (X.subspace_topology (⋃₀ S)) (discrete_topology mynat), { have: U ⊆ ⋃₀ S, { intro u, assume hUu, existsi U, from ⟨hU, hUu⟩, }, apply s_inclusion_continuous X U (⋃₀ S) this, }, { from hfc, }, }, have step2 := step1 h_elp_me ⟨x.val, hxU⟩ ⟨z, hz.left⟩, apply transitivity' step2, { congr, apply subtype.eq, refl, }, { from rfl, }, }, { symmetry, have step1 := hVcon (λ x: subtype V, f ⟨x, ⟨V, ⟨hV, x.property⟩⟩⟩), let g := (λ x: subtype V, f ⟨x, ⟨V, ⟨hV, x.property⟩⟩⟩), have h_elp_me: is_continuous (subspace_topology X V) (discrete_topology mynat) g, { apply composition_continuous (subspace_topology X V) (X.subspace_topology (⋃₀ S)) (discrete_topology mynat), { have: V ⊆ ⋃₀ S, { intro v, assume hVv, existsi V, from ⟨hV, hVv⟩, }, apply s_inclusion_continuous X V (⋃₀ S) this, }, { from hfc, }, }, have step2 := step1 h_elp_me ⟨y.val, hxV⟩ ⟨z, hz.right⟩, apply transitivity' step2, { congr, apply subtype.eq, refl, }, { from rfl, }, }, end theorem union_of_two_overlapping_connected (X: topological_space α) (U V: myset α) (hUcn: is_connected (X.subspace_topology U)) (hVcn: is_connected (X.subspace_topology V)) (hlap: U ∩ V ≠ ∅): is_connected (subspace_topology X (U ∪ V)) := begin rw myset.union_two_sUnion, apply s_union_of_overlapping_connected, { intro W, assume hW, cases hW; {rw hW, assumption}, }, { intros W1 W2, assume hW1 hW2, rw ←myset.exists_iff_neq_empty at hlap ⊢, cases hlap with x hx, existsi x, cases hx with hUx hVx, split, { cases hW1; {rw hW1, assumption}, }, { cases hW2; {rw hW2, assumption}, }, }, end private lemma line_connected (X: topological_space α) (Y: topological_space β) (hYcn: is_connected Y) (x: α): is_connected ((product_topology X Y).subspace_topology {xy | xy.fst = x}) := begin have: {xy : α × β | xy.fst = x} = myset.imageu (λ y: β, (x, y)), { apply myset.setext, intro z, split; assume hx, { existsi z.snd, cases z, apply congr, apply congr_arg prod.mk, from hx.symm, refl, }, { cases hx with y hy, rw ←hy, from rfl, }, }, rw this, clear this, apply image_connected Y _ (λ (y : β), (x, y)), { rw continuous_iff_components_continuous, split, { apply constant_continuous _ _ x, }, { apply identity_continuous, }, }, { assumption, }, end private lemma cross_connected (X: topological_space α) (Y: topological_space β) (hXcn: is_connected X) (hYcn: is_connected Y) (x: α) (y: β): is_connected ((product_topology X Y).subspace_topology (λ xy', xy'.fst = x ∨ xy'.snd = y)) := begin apply union_of_two_overlapping_connected, { apply line_connected, assumption, }, { have homeom := swap_homeomorphism X Y, have hlcn := line_connected Y X hXcn y, have himcn := image_connected _ _ _ (restriction_continuous _ _ _ _ homeom.g_continuous) hlcn, have: (λ a : α × β, a.snd = y) = myset.imageu (λ (x : subtype {xy : β × α | xy.fst = y}), (x.val.snd, x.val.fst)), { apply myset.setext, intro z, split; assume hz, { existsi (⟨(z.snd, z.fst), hz⟩: subtype {xy : β × α | xy.fst = y}), cases z, refl, }, { cases hz with z' hz', rw ←hz', from z'.property, }, }, rw this, clear this, assumption, }, { rw ←myset.exists_iff_neq_empty, existsi (x, y), split, { from rfl, }, { from rfl, }, }, end theorem product_connected (X: topological_space α) (Y: topological_space β) (hXcn: is_connected X) (hYcn: is_connected Y): is_connected (product_topology X Y) := begin apply surjective_image_connected _ _ _ (univ_homeomorphism _).g_continuous, { intro a, existsi (⟨a, trivial⟩: subtype myset.univ), refl, }, { by_cases hXe: (myset.univ: myset (α × β)) = ∅, { rw hXe, apply empty_connected, }, { cases myset.exists_iff_neq_empty.mpr hXe with xy hxy, suffices h: ⋃₀ myset.imageu (λ y: β, (λ xy': α × β, xy'.fst = xy.fst ∨ xy'.snd = y)) = myset.univ, { rw ←h, apply s_union_of_overlapping_connected, { intro U, assume hUc, cases hUc with y hy, rw ←hy, apply cross_connected; assumption, }, { intros U V, assume hUc hVc, rw ←myset.exists_iff_neq_empty, existsi xy, split, { cases hUc with _ hUc, rw ←hUc, left, refl, }, { cases hVc with _ hVc, rw ←hVc, left, refl, }, }, }, { apply myset.setext, intro xy'', split; assume hx, { trivial, }, { existsi λ (xy' : α × β), xy'.fst = xy.fst ∨ xy'.snd = xy''.snd, split, { existsi xy''.snd, refl, }, { right, refl, }, }, }, }, }, end end topological_space end hidden
111685b5b5a39102b919d2b022092d1e840b5f14
6b02ce66658141f3e0aa3dfa88cd30bbbb24d17b
/src/Lean/Parser/Tactic.lean
96ed2925c54e27a30890e558941668acb2c63010
[ "Apache-2.0" ]
permissive
pbrinkmeier/lean4
d31991fd64095e64490cb7157bcc6803f9c48af4
32fd82efc2eaf1232299e930ec16624b370eac39
refs/heads/master
1,681,364,001,662
1,618,425,427,000
1,618,425,427,000
358,314,562
0
0
Apache-2.0
1,618,504,558,000
1,618,501,999,000
null
UTF-8
Lean
false
false
1,215
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Parser.Term namespace Lean namespace Parser namespace Tactic builtin_initialize register_parser_alias "tacticSeq" tacticSeq @[builtinTacticParser] def «unknown» := leading_parser withPosition (ident >> errorAtSavedPos "unknown tactic" true) @[builtinTacticParser] def nestedTactic := tacticSeqBracketed /- Auxiliary parser for expanding `match` tactic -/ @[builtinTacticParser] def eraseAuxDiscrs := leading_parser:maxPrec "eraseAuxDiscrs!" def matchRhs := Term.hole <|> Term.syntheticHole <|> tacticSeq def matchAlts := Term.matchAlts (rhsParser := matchRhs) @[builtinTacticParser] def «match» := leading_parser:leadPrec "match " >> sepBy1 Term.matchDiscr ", " >> Term.optType >> " with " >> matchAlts @[builtinTacticParser] def introMatch := leading_parser nonReservedSymbol "intro " >> matchAlts @[builtinTacticParser] def decide := leading_parser nonReservedSymbol "decide" @[builtinTacticParser] def nativeDecide := leading_parser nonReservedSymbol "nativeDecide" end Tactic end Parser end Lean
76a42edba8517e14f937a15ecfc958f076c1c443
efce24474b28579aba3272fdb77177dc2b11d7aa
/src/homotopy_theory/formal/cofibrations/brown.lean
5729bb3fb1fd05ee38d1ec2bfc95d890f74b8b8c
[ "Apache-2.0" ]
permissive
rwbarton/lean-homotopy-theory
cff499f24268d60e1c546e7c86c33f58c62888ed
39e1b4ea1ed1b0eca2f68bc64162dde6a6396dee
refs/heads/lean-3.4.2
1,622,711,883,224
1,598,550,958,000
1,598,550,958,000
136,023,667
12
6
Apache-2.0
1,573,187,573,000
1,528,116,262,000
Lean
UTF-8
Lean
false
false
10,435
lean
import .arrow import .cofibration_category import tactic.slice /- Brown factorization, aka "Ken Brown's lemma", and a relative version. Following Rădulescu-Banu, Cofibrations in Homotopy Theory, section 1.3. -/ universes v u namespace homotopy_theory.cofibrations open category_theory open category_theory.category open precofibration_category open cofibration_category open homotopy_theory.weak_equivalences variables {C : Type u} [category.{v} C] [cofibration_category.{v} C] [has_initial_object.{v} C] structure brown_factorization {a b : C} (f : a ⟶ b) : Type (max u v) := -- ab represents a coproduct of a and b, used to formulate the condition on f' + s (ab : pushout (! a) (! b)) (b' : C) (f' : a ⟶ b') (r : b' ⟶ b) (s : b ⟶ b') (hf' : is_cof f') (hf's : is_cof (ab.is_pushout.induced f' s (initial.uniqueness _ _))) (hs : is_acof s) (hf'r : f' ≫ r = f) (hsr : s ≫ r = 𝟙 b) lemma brown_factorization.hr {a b : C} {f : a ⟶ b} (c : brown_factorization f) : is_weq c.r := begin convert category_with_weak_equivalences.weq_of_comp_weq_left c.hs.2 _, rw c.hsr, apply weq_id end lemma brown_factorization.weq_f' {a b : C} {f : a ⟶ b} (c : brown_factorization f) (hf : is_weq f) : is_weq c.f' := begin convert category_with_weak_equivalences.weq_of_comp_weq_right c.hr _, rw c.hf'r, exact hf end --- Any map between cofibrant objects admits a Brown factorization (R-B, Lemma 1.3.1). lemma exists_brown_factorization {a b : C} (ha : cofibrant a) (hb : cofibrant b) (f : a ⟶ b) : nonempty (brown_factorization f) := let ab := pushout_by_cof (! a) (! b) ha, ⟨b', j, g, hj, hg, hf⟩ := factorization (ab.is_pushout.induced f (𝟙 b) (initial.uniqueness _ _)) in ⟨⟨ab, b', ab.map₀ ≫ j, g, ab.map₁ ≫ j, cof_comp (pushout_is_cof ab.is_pushout.transpose hb) hj, by convert hj; apply ab.is_pushout.uniqueness; simp, begin split, { refine cof_comp (pushout_is_cof ab.is_pushout ha) hj }, { convert category_with_weak_equivalences.weq_of_comp_weq_right hg _, rw [assoc, hf], simpa using weq_id _ } end, by rw [assoc, hf]; simp, by rw [assoc, hf]; simp⟩⟩ --- R-B, Lemma 1.3.3 lemma relative_factorization {a₁ a₁' b₁ a₂ b₂ : C} (ha₁ : cofibrant a₁) (ha₂ : cofibrant a₂) (f₁' : a₁ ⟶ a₁') (r₁ : a₁' ⟶ b₁) (hf₁' : is_cof f₁') (hr : is_weq r₁) (f₂ : a₂ ⟶ b₂) (a : a₁ ⟶ a₂) (b : b₁ ⟶ b₂) (s : (f₁' ≫ r₁) ≫ b = a ≫ f₂) : ∃ a₂' (a' : a₁' ⟶ a₂') (f₂' : a₂ ⟶ a₂') (r₂ : a₂' ⟶ b₂) (hf' : f₁' ≫ a' = a ≫ f₂'), r₁ ≫ b = a' ≫ r₂ ∧ f₂' ≫ r₂ = f₂ ∧ is_cof f₂' ∧ is_weq r₂ ∧ is_cof ((pushout_by_cof f₁' a hf₁').is_pushout.induced a' f₂' hf') := let po := pushout_by_cof f₁' a hf₁', g := po.is_pushout.induced (r₁ ≫ b) f₂ (by rw [←s, assoc]), ⟨a₂', s, r₂, hs, hr₂, hg⟩ := factorization g in ⟨a₂', po.map₀ ≫ s, po.map₁ ≫ s, r₂, by rw [←assoc, ←assoc, po.is_pushout.commutes], by rw [assoc, hg]; simp, by simp [hg], cof_comp (pushout_is_cof po.is_pushout hf₁') hs, hr₂, by convert hs; apply po.is_pushout.uniqueness; simp⟩ /-- R-B, Lemma 1.3.4. The statement there is missing hypotheses on the maps a and b, needed for the last two conclusions. -/ lemma exists_relative_brown_factorization {a₁ b₁ a₂ b₂ : C} (ha₁ : cofibrant a₁) (hb₁ : cofibrant b₁) (ha₂ : cofibrant a₂) (hb₂ : cofibrant b₂) (f₁ : a₁ ⟶ b₁) (f₂ : a₂ ⟶ b₂) (a : a₁ ⟶ a₂) (b : b₁ ⟶ b₂) (S : f₁ ≫ b = a ≫ f₂) (c₁ : brown_factorization f₁) : ∃ (c₂ : brown_factorization f₂) (b' : c₁.b' ⟶ c₂.b') (hf' : c₁.f' ≫ b' = a ≫ c₂.f') (hr : c₁.r ≫ b = b' ≫ c₂.r) (hs : c₁.s ≫ b' = b ≫ c₂.s), (is_cof b → is_cof ((pushout_by_cof c₁.f' a c₁.hf').is_pushout.induced b' c₂.f' hf')) ∧ (is_cof a → is_acof ((pushout_by_cof c₁.s b c₁.hs.1).is_pushout.induced b' c₂.s hs)) := let po_a := pushout_by_cof c₁.f' a c₁.hf', a₃ := po_a.ob, f' := po_a.map₁, cof_f' : is_cof f' := pushout_is_cof po_a.is_pushout c₁.hf', po_b := pushout_by_cof c₁.s b c₁.hs.1, b₃ := po_b.ob, s := po_b.map₁, acof_s : is_acof s := pushout_is_acof po_b.is_pushout c₁.hs, r := po_b.is_pushout.induced (c₁.r ≫ b) (𝟙 _) (by rw [←assoc, c₁.hsr]; simp), f₃ : a₃ ⟶ b₃ := po_a.is_pushout.induced (c₁.r ≫ b ≫ s) (f₂ ≫ s) begin conv { to_rhs, rw [←assoc, ←S], rw [←c₁.hf'r, assoc] }, simp end, a₂b₂ := pushout_by_cof (! a₂) (! b₂) ha₂, -- TODO: lemma here? cof_a₃ : cofibrant a₃ := begin change is_cof _, convert cof_comp ha₂ (pushout_is_cof po_a.is_pushout c₁.hf'), apply initial.uniqueness end, cof_b₃ : cofibrant b₃ := begin change is_cof _, convert cof_comp hb₂ (pushout_is_cof po_b.is_pushout c₁.hs.1), apply initial.uniqueness end, a₃b₃ := pushout_by_cof (! a₃) (! b₃) cof_a₃, a₁_b₁ := c₁.ab.ob, cof_a₁_b₁ : cofibrant a₁_b₁ := begin change is_cof _, convert cof_comp hb₁ (pushout_is_cof c₁.ab.is_pushout ha₁), apply initial.uniqueness end, a₃_b₃ := a₃b₃.ob, cof_a₃_b₃ : cofibrant a₃_b₃ := begin change is_cof _, convert cof_comp cof_b₃ (pushout_is_cof a₃b₃.is_pushout cof_a₃), apply initial.uniqueness end, ⟨b₂', b', fs₃', r₃, hfs₃', hr₃, hf'sr, cof_fs₃', weq_r₃, cof_p⟩ := begin refine relative_factorization cof_a₁_b₁ cof_a₃_b₃ _ c₁.r c₁.hf's c₁.hr (a₃b₃.is_pushout.induced f₃ (𝟙 b₃) (initial.uniqueness _ _)) (pushout_of_maps c₁.ab.is_pushout a₃b₃.is_pushout (𝟙 _) (a ≫ f') (b ≫ s) (initial.uniqueness _ _) (initial.uniqueness _ _)) (b ≫ s) _, apply c₁.ab.is_pushout.uniqueness, { slice_lhs 1 2 { simp }, conv { to_lhs, rw [c₁.hf'r, S, assoc] }, rw induced_pushout_of_maps, simp }, { slice_lhs 1 2 { simp }, conv { to_lhs, rw [c₁.hsr, id_comp] }, rw induced_pushout_of_maps, simp } end, f₃' := a₃b₃.map₀ ≫ fs₃', s₃ := a₃b₃.map₁ ≫ fs₃', f₂' := f' ≫ f₃', r₂ := r₃ ≫ r, s₂ := s ≫ s₃ in have sr : s ≫ r = 𝟙 _, by simp, have s₂r₂ : s₂ ≫ r₂ = 𝟙 _, begin slice_lhs 3 4 { rw hf'sr }, slice_lhs 2 3 { rw Is_pushout.induced_commutes₁ }, simp end, have weq_r₂ : is_weq r₂, begin refine weq_comp weq_r₃ _, rw ←weq_iff_weq_inv sr, exact acof_s.2 end, ⟨⟨a₂b₂, b₂', f₂', r₂, s₂, cof_comp (pushout_is_cof po_a.is_pushout c₁.hf') (cof_comp (pushout_is_cof a₃b₃.is_pushout.transpose cof_b₃) cof_fs₃'), begin have := cof_pushout cof_f' acof_s.1 a₂b₂.is_pushout (by convert a₃b₃.is_pushout; apply initial.uniqueness) (by apply initial.uniqueness), convert cof_comp this cof_fs₃', apply a₂b₂.is_pushout.uniqueness; conv { to_rhs, rw ←assoc }; simp end, begin refine ⟨_, (weq_iff_weq_inv s₂r₂).mpr weq_r₂⟩, exact cof_comp acof_s.1 (cof_comp (pushout_is_cof a₃b₃.is_pushout cof_a₃) cof_fs₃') end, begin slice_lhs 3 4 { rw hf'sr }, slice_lhs 2 3 { rw Is_pushout.induced_commutes₀ }, slice_lhs 1 2 { rw Is_pushout.induced_commutes₁ }, simp [sr] end, s₂r₂⟩, b', begin convert congr_arg (λ z, c₁.ab.map₀ ≫ z) hfs₃' using 1, { slice_rhs 1 2 { rw Is_pushout.induced_commutes₀ } }, { slice_rhs 1 2 { dsimp [pushout_of_maps], rw Is_pushout.induced_commutes₀ }, simp } end, begin have : c₁.r ≫ b = c₁.r ≫ b ≫ (s ≫ r), by rw [sr]; simp, rw this, slice_lhs 1 3 { rw hr₃ }, simp end, begin convert congr_arg (λ z, c₁.ab.map₁ ≫ z) hfs₃' using 1, { slice_rhs 1 2 { rw Is_pushout.induced_commutes₁ } }, { slice_rhs 1 2 { dsimp [pushout_of_maps], rw Is_pushout.induced_commutes₁ }, simp } end, begin intro hb, let v := _, let S₂ : cof_square v b' := ⟨_, _, _, _, cof_p⟩, let S₁ : cof_square a v, { refine ⟨c₁.ab.map₀, f' ≫ a₃b₃.map₀, by simp [v, pushout_of_maps], pushout_is_cof c₁.ab.is_pushout.transpose hb₁, _⟩, let po : pushout _ _ := _, change is_cof (po.is_pushout.induced _ _ _), have : is_cof (b ≫ s) := cof_comp hb acof_s.1, convert cof_pushout this cof_f' (Is_pushout_of_Is_pushout_of_Is_pushout c₁.ab.is_pushout.transpose po.is_pushout) (by convert a₃b₃.is_pushout.transpose; apply initial.uniqueness) (by apply initial.uniqueness) using 1, symmetry, apply pushout_induced_eq_iff; simp }, have : c₁.f' = S₁.f₁ ≫ S₂.f₁, by simp, have S : is_cof_square a b' c₁.f' _ := is_cof_square_comp ⟨S₁, rfl, rfl⟩ ⟨S₂, rfl, rfl⟩ this rfl, convert S.corner_cof.snd.snd, simp end, begin intro ha, let G := _, change is_acof G, suffices : is_cof G, { refine ⟨this, _⟩, have sG : s ≫ G = s₂, by simp, have : is_acof s := pushout_is_acof po_b.is_pushout c₁.hs, refine category_with_weak_equivalences.weq_of_comp_weq_left this.2 _, rw sG, exact (weq_iff_weq_inv s₂r₂).mpr weq_r₂ }, -- From here on, the proof resembles the previous one let v := _, let S₂ : cof_square v b' := ⟨_, _, _, _, cof_p⟩, let S₁ : cof_square b v, { refine ⟨c₁.ab.map₁, s ≫ a₃b₃.map₁, by simp [v, pushout_of_maps], pushout_is_cof c₁.ab.is_pushout ha₁, _⟩, let po : pushout _ _ := _, change is_cof (po.is_pushout.induced _ _ _), have : is_cof (a ≫ f') := cof_comp ha cof_f', convert cof_pushout this acof_s.1 (Is_pushout_of_Is_pushout_of_Is_pushout c₁.ab.is_pushout po.is_pushout) (by convert a₃b₃.is_pushout; apply initial.uniqueness) (by apply initial.uniqueness) using 1, symmetry, apply pushout_induced_eq_iff; simp }, have : c₁.s = S₁.f₁ ≫ S₂.f₁, by simp, have S : is_cof_square b b' c₁.s _ := is_cof_square_comp ⟨S₁, rfl, rfl⟩ ⟨S₂, rfl, rfl⟩ this rfl, convert S.corner_cof.snd.snd, simp end⟩ end homotopy_theory.cofibrations
a3afd46f6ae6585795e99e0acca3f41b96e8a37c
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/analysis/inner_product_space/rayleigh.lean
a85ca67aafd3c14d6a81c16c7ba935faba49d3ac
[ "Apache-2.0" ]
permissive
jumpy4/mathlib
d3829e75173012833e9f15ac16e481e17596de0f
af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13
refs/heads/master
1,693,508,842,818
1,636,203,271,000
1,636,203,271,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,313
lean
/- Copyright (c) 2021 Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth, Frédéric Dupuis -/ import analysis.inner_product_space.calculus import analysis.inner_product_space.dual import analysis.calculus.lagrange_multipliers import linear_algebra.eigenspace /-! # The Rayleigh quotient The Rayleigh quotient of a self-adjoint operator `T` on an inner product space `E` is the function `λ x, ⟪T x, x⟫ / ∥x∥ ^ 2`. The main results of this file are `is_self_adjoint.has_eigenvector_of_is_max_on` and `is_self_adjoint.has_eigenvector_of_is_min_on`, which state that if `E` is complete, and if the Rayleigh quotient attains its global maximum/minimum over some sphere at the point `x₀`, then `x₀` is an eigenvector of `T`, and the `supr`/`infi` of `λ x, ⟪T x, x⟫ / ∥x∥ ^ 2` is the corresponding eigenvalue. The corollaries `is_self_adjoint.has_eigenvalue_supr_of_finite_dimensional` and `is_self_adjoint.has_eigenvalue_supr_of_finite_dimensional` state that if `E` is finite-dimensional and nontrivial, then `T` has some (nonzero) eigenvectors with eigenvalue the `supr`/`infi` of `λ x, ⟪T x, x⟫ / ∥x∥ ^ 2`. ## TODO A slightly more elaborate corollary is that if `E` is complete and `T` is a compact operator, then `T` has some (nonzero) eigenvector with eigenvalue either `⨆ x, ⟪T x, x⟫ / ∥x∥ ^ 2` or `⨅ x, ⟪T x, x⟫ / ∥x∥ ^ 2` (not necessarily both). -/ variables {𝕜 : Type*} [is_R_or_C 𝕜] variables {E : Type*} [inner_product_space 𝕜 E] local notation `⟪`x`, `y`⟫` := @inner 𝕜 _ _ x y open_locale nnreal open module.End metric namespace continuous_linear_map variables (T : E →L[𝕜] E) local notation `rayleigh_quotient` := λ x : E, T.re_apply_inner_self x / ∥(x:E)∥ ^ 2 lemma rayleigh_smul (x : E) {c : 𝕜} (hc : c ≠ 0) : rayleigh_quotient (c • x) = rayleigh_quotient x := begin by_cases hx : x = 0, { simp [hx] }, have : ∥c∥ ≠ 0 := by simp [hc], have : ∥x∥ ≠ 0 := by simp [hx], field_simp [norm_smul, T.re_apply_inner_self_smul], ring end lemma image_rayleigh_eq_image_rayleigh_sphere {r : ℝ} (hr : 0 < r) : rayleigh_quotient '' {0}ᶜ = rayleigh_quotient '' (sphere 0 r) := begin ext a, split, { rintros ⟨x, (hx : x ≠ 0), hxT⟩, have : ∥x∥ ≠ 0 := by simp [hx], let c : 𝕜 := ↑∥x∥⁻¹ * r, have : c ≠ 0 := by simp [c, hx, hr.ne'], refine ⟨c • x, _, _⟩, { field_simp [norm_smul, is_R_or_C.norm_eq_abs, abs_of_nonneg hr.le] }, { rw T.rayleigh_smul x this, exact hxT } }, { rintros ⟨x, hx, hxT⟩, exact ⟨x, nonzero_of_mem_sphere hr ⟨x, hx⟩, hxT⟩ }, end lemma supr_rayleigh_eq_supr_rayleigh_sphere {r : ℝ} (hr : 0 < r) : (⨆ x : {x : E // x ≠ 0}, rayleigh_quotient x) = ⨆ x : sphere (0:E) r, rayleigh_quotient x := show (⨆ x : ({0} : set E)ᶜ, rayleigh_quotient x) = _, by simp only [@csupr_set _ _ _ _ rayleigh_quotient, T.image_rayleigh_eq_image_rayleigh_sphere hr] lemma infi_rayleigh_eq_infi_rayleigh_sphere {r : ℝ} (hr : 0 < r) : (⨅ x : {x : E // x ≠ 0}, rayleigh_quotient x) = ⨅ x : sphere (0:E) r, rayleigh_quotient x := show (⨅ x : ({0} : set E)ᶜ, rayleigh_quotient x) = _, by simp only [@cinfi_set _ _ _ _ rayleigh_quotient, T.image_rayleigh_eq_image_rayleigh_sphere hr] end continuous_linear_map namespace is_self_adjoint section real variables {F : Type*} [inner_product_space ℝ F] lemma has_strict_fderiv_at_re_apply_inner_self {T : F →L[ℝ] F} (hT : is_self_adjoint (T : F →ₗ[ℝ] F)) (x₀ : F) : has_strict_fderiv_at T.re_apply_inner_self (bit0 (inner_right (T x₀))) x₀ := begin convert T.has_strict_fderiv_at.inner (has_strict_fderiv_at_id x₀), ext y, simp [bit0, hT.apply_clm x₀ y, real_inner_comm x₀] end variables [complete_space F] {T : F →L[ℝ] F} local notation `rayleigh_quotient` := λ x : F, T.re_apply_inner_self x / ∥(x:F)∥ ^ 2 lemma linearly_dependent_of_is_local_extr_on (hT : is_self_adjoint (T : F →ₗ[ℝ] F)) {x₀ : F} (hextr : is_local_extr_on T.re_apply_inner_self (sphere (0:F) ∥x₀∥) x₀) : ∃ a b : ℝ, (a, b) ≠ 0 ∧ a • x₀ + b • T x₀ = 0 := begin have H : is_local_extr_on T.re_apply_inner_self {x : F | ∥x∥ ^ 2 = ∥x₀∥ ^ 2} x₀, { convert hextr, ext x, simp [dist_eq_norm] }, -- find Lagrange multipliers for the function `T.re_apply_inner_self` and the -- hypersurface-defining function `λ x, ∥x∥ ^ 2` obtain ⟨a, b, h₁, h₂⟩ := is_local_extr_on.exists_multipliers_of_has_strict_fderiv_at_1d H (has_strict_fderiv_at_norm_sq x₀) (hT.has_strict_fderiv_at_re_apply_inner_self x₀), refine ⟨a, b, h₁, _⟩, apply (inner_product_space.to_dual_map ℝ F).injective, simp only [linear_isometry.map_add, linear_isometry.map_smul, linear_isometry.map_zero], change a • inner_right x₀ + b • inner_right (T x₀) = 0, apply smul_right_injective (F →L[ℝ] ℝ) (two_ne_zero : (2:ℝ) ≠ 0), simpa only [bit0, add_smul, smul_add, one_smul, add_zero] using h₂ end lemma eq_smul_self_of_is_local_extr_on_real (hT : is_self_adjoint (T : F →ₗ[ℝ] F)) {x₀ : F} (hextr : is_local_extr_on T.re_apply_inner_self (sphere (0:F) ∥x₀∥) x₀) : T x₀ = (rayleigh_quotient x₀) • x₀ := begin obtain ⟨a, b, h₁, h₂⟩ := hT.linearly_dependent_of_is_local_extr_on hextr, by_cases hx₀ : x₀ = 0, { simp [hx₀] }, by_cases hb : b = 0, { have : a ≠ 0 := by simpa [hb] using h₁, refine absurd _ hx₀, apply smul_right_injective F this, simpa [hb] using h₂ }, let c : ℝ := - b⁻¹ * a, have hc : T x₀ = c • x₀, { have : b * (b⁻¹ * a) = a := by field_simp [mul_comm], apply smul_right_injective F hb, simp [c, ← neg_eq_of_add_eq_zero h₂, ← mul_smul, this] }, convert hc, have : ∥x₀∥ ≠ 0 := by simp [hx₀], field_simp, simpa [inner_smul_left, real_inner_self_eq_norm_sq, sq] using congr_arg (λ x, ⟪x, x₀⟫_ℝ) hc, end end real section complete_space variables [complete_space E] {T : E →L[𝕜] E} local notation `rayleigh_quotient` := λ x : E, T.re_apply_inner_self x / ∥(x:E)∥ ^ 2 lemma eq_smul_self_of_is_local_extr_on (hT : is_self_adjoint (T : E →ₗ[𝕜] E)) {x₀ : E} (hextr : is_local_extr_on T.re_apply_inner_self (sphere (0:E) ∥x₀∥) x₀) : T x₀ = (↑(rayleigh_quotient x₀) : 𝕜) • x₀ := begin letI := inner_product_space.is_R_or_C_to_real 𝕜 E, letI : is_scalar_tower ℝ 𝕜 E := restrict_scalars.is_scalar_tower _ _ _, let S : E →L[ℝ] E := @continuous_linear_map.restrict_scalars 𝕜 E E _ _ _ _ _ _ _ ℝ _ _ _ _ T, have hSA : is_self_adjoint (S : E →ₗ[ℝ] E) := λ x y, by { have := hT x y, simp only [continuous_linear_map.coe_coe] at this, simp only [real_inner_eq_re_inner, this, continuous_linear_map.coe_restrict_scalars, continuous_linear_map.coe_coe, linear_map.coe_restrict_scalars_eq_coe] }, exact eq_smul_self_of_is_local_extr_on_real hSA hextr, end /-- For a self-adjoint operator `T`, a local extremum of the Rayleigh quotient of `T` on a sphere centred at the origin is an eigenvector of `T`. -/ lemma has_eigenvector_of_is_local_extr_on (hT : is_self_adjoint (T : E →ₗ[𝕜] E)) {x₀ : E} (hx₀ : x₀ ≠ 0) (hextr : is_local_extr_on T.re_apply_inner_self (sphere (0:E) ∥x₀∥) x₀) : has_eigenvector (T : E →ₗ[𝕜] E) ↑(rayleigh_quotient x₀) x₀ := begin refine ⟨_, hx₀⟩, rw module.End.mem_eigenspace_iff, exact hT.eq_smul_self_of_is_local_extr_on hextr end /-- For a self-adjoint operator `T`, a maximum of the Rayleigh quotient of `T` on a sphere centred at the origin is an eigenvector of `T`, with eigenvalue the global supremum of the Rayleigh quotient. -/ lemma has_eigenvector_of_is_max_on (hT : is_self_adjoint (T : E →ₗ[𝕜] E)) {x₀ : E} (hx₀ : x₀ ≠ 0) (hextr : is_max_on T.re_apply_inner_self (sphere (0:E) ∥x₀∥) x₀) : has_eigenvector (T : E →ₗ[𝕜] E) ↑(⨆ x : {x : E // x ≠ 0}, rayleigh_quotient x) x₀ := begin convert hT.has_eigenvector_of_is_local_extr_on hx₀ (or.inr hextr.localize), have hx₀' : 0 < ∥x₀∥ := by simp [hx₀], have hx₀'' : x₀ ∈ sphere (0:E) (∥x₀∥) := by simp, rw T.supr_rayleigh_eq_supr_rayleigh_sphere hx₀', refine is_max_on.supr_eq hx₀'' _, intros x hx, dsimp, have : ∥x∥ = ∥x₀∥ := by simpa using hx, rw this, exact div_le_div_of_le (sq_nonneg ∥x₀∥) (hextr hx) end /-- For a self-adjoint operator `T`, a minimum of the Rayleigh quotient of `T` on a sphere centred at the origin is an eigenvector of `T`, with eigenvalue the global infimum of the Rayleigh quotient. -/ lemma has_eigenvector_of_is_min_on (hT : is_self_adjoint (T : E →ₗ[𝕜] E)) {x₀ : E} (hx₀ : x₀ ≠ 0) (hextr : is_min_on T.re_apply_inner_self (sphere (0:E) ∥x₀∥) x₀) : has_eigenvector (T : E →ₗ[𝕜] E) ↑(⨅ x : {x : E // x ≠ 0}, rayleigh_quotient x) x₀ := begin convert hT.has_eigenvector_of_is_local_extr_on hx₀ (or.inl hextr.localize), have hx₀' : 0 < ∥x₀∥ := by simp [hx₀], have hx₀'' : x₀ ∈ sphere (0:E) (∥x₀∥) := by simp, rw T.infi_rayleigh_eq_infi_rayleigh_sphere hx₀', refine is_min_on.infi_eq hx₀'' _, intros x hx, dsimp, have : ∥x∥ = ∥x₀∥ := by simpa using hx, rw this, exact div_le_div_of_le (sq_nonneg ∥x₀∥) (hextr hx) end end complete_space section finite_dimensional variables [finite_dimensional 𝕜 E] [nontrivial E] {T : E →ₗ[𝕜] E} /-- The supremum of the Rayleigh quotient of a self-adjoint operator `T` on a nontrivial finite-dimensional vector space is an eigenvalue for that operator. -/ lemma has_eigenvalue_supr_of_finite_dimensional (hT : is_self_adjoint T) : has_eigenvalue T ↑(⨆ x : {x : E // x ≠ 0}, is_R_or_C.re ⟪T x, x⟫ / ∥(x:E)∥ ^ 2) := begin let T' : E →L[𝕜] E := T.to_continuous_linear_map, have hT' : is_self_adjoint (T' : E →ₗ[𝕜] E) := hT, obtain ⟨x, hx⟩ : ∃ x : E, x ≠ 0 := exists_ne 0, have H₁ : is_compact (sphere (0:E) ∥x∥) := is_compact_sphere _ _, have H₂ : (sphere (0:E) ∥x∥).nonempty := ⟨x, by simp⟩, -- key point: in finite dimension, a continuous function on the sphere has a max obtain ⟨x₀, hx₀', hTx₀⟩ := H₁.exists_forall_ge H₂ T'.re_apply_inner_self_continuous.continuous_on, have hx₀ : ∥x₀∥ = ∥x∥ := by simpa using hx₀', have : is_max_on T'.re_apply_inner_self (sphere 0 ∥x₀∥) x₀, { simpa only [← hx₀] using hTx₀ }, have hx₀_ne : x₀ ≠ 0, { have : ∥x₀∥ ≠ 0 := by simp only [hx₀, norm_eq_zero, hx, ne.def, not_false_iff], simpa [← norm_eq_zero, ne.def] }, exact has_eigenvalue_of_has_eigenvector (hT'.has_eigenvector_of_is_max_on hx₀_ne this) end /-- The infimum of the Rayleigh quotient of a self-adjoint operator `T` on a nontrivial finite-dimensional vector space is an eigenvalue for that operator. -/ lemma has_eigenvalue_infi_of_finite_dimensional (hT : is_self_adjoint T) : has_eigenvalue T ↑(⨅ x : {x : E // x ≠ 0}, is_R_or_C.re ⟪T x, x⟫ / ∥(x:E)∥ ^ 2) := begin let T' : E →L[𝕜] E := T.to_continuous_linear_map, have hT' : is_self_adjoint (T' : E →ₗ[𝕜] E) := hT, obtain ⟨x, hx⟩ : ∃ x : E, x ≠ 0 := exists_ne 0, have H₁ : is_compact (sphere (0:E) ∥x∥) := is_compact_sphere _ _, have H₂ : (sphere (0:E) ∥x∥).nonempty := ⟨x, by simp⟩, -- key point: in finite dimension, a continuous function on the sphere has a min obtain ⟨x₀, hx₀', hTx₀⟩ := H₁.exists_forall_le H₂ T'.re_apply_inner_self_continuous.continuous_on, have hx₀ : ∥x₀∥ = ∥x∥ := by simpa using hx₀', have : is_min_on T'.re_apply_inner_self (sphere 0 ∥x₀∥) x₀, { simpa only [← hx₀] using hTx₀ }, have hx₀_ne : x₀ ≠ 0, { have : ∥x₀∥ ≠ 0 := by simp only [hx₀, norm_eq_zero, hx, ne.def, not_false_iff], simpa [← norm_eq_zero, ne.def] }, exact has_eigenvalue_of_has_eigenvector (hT'.has_eigenvector_of_is_min_on hx₀_ne this) end end finite_dimensional end is_self_adjoint
fb519176c9c088266d95801cc536cac8c9dbf8c9
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/linear_algebra/finsupp_vector_space.lean
cccfd64c0873b315872d194c89c1d4f1acaf4f12
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,092
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import data.mv_polynomial import linear_algebra.dimension import linear_algebra.direct_sum.finsupp import linear_algebra.finite_dimensional /-! # Linear structures on function with finite support `ι →₀ M` This file contains results on the `R`-module structure on functions of finite support from a type `ι` to an `R`-module `M`, in particular in the case that `R` is a field. Furthermore, it contains some facts about isomorphisms of vector spaces from equality of dimension as well as the cardinality of finite dimensional vector spaces. ## TODO Move the second half of this file to more appropriate other files. -/ noncomputable theory local attribute [instance, priority 100] classical.prop_decidable open set linear_map submodule namespace finsupp section ring variables {R : Type*} {M : Type*} {ι : Type*} variables [ring R] [add_comm_group M] [module R M] lemma linear_independent_single {φ : ι → Type*} {f : Π ι, φ ι → M} (hf : ∀i, linear_independent R (f i)) : linear_independent R (λ ix : Σ i, φ i, single ix.1 (f ix.1 ix.2)) := begin apply @linear_independent_Union_finite R _ _ _ _ ι φ (λ i x, single i (f i x)), { assume i, have h_disjoint : disjoint (span R (range (f i))) (ker (lsingle i)), { rw ker_lsingle, exact disjoint_bot_right }, apply (hf i).map h_disjoint }, { intros i t ht hit, refine (disjoint_lsingle_lsingle {i} t (disjoint_singleton_left.2 hit)).mono _ _, { rw span_le, simp only [supr_singleton], rw range_coe, apply range_comp_subset_range }, { refine supr_le_supr (λ i, supr_le_supr _), intros hi, rw span_le, rw range_coe, apply range_comp_subset_range } } end open linear_map submodule lemma is_basis_single {φ : ι → Type*} (f : Π ι, φ ι → M) (hf : ∀i, is_basis R (f i)) : is_basis R (λ ix : Σ i, φ i, single ix.1 (f ix.1 ix.2)) := begin split, { apply linear_independent_single, exact λ i, (hf i).1 }, { rw [range_sigma_eq_Union_range, span_Union], simp only [image_univ.symm, λ i, image_comp (single i) (f i), span_single_image], simp only [image_univ, (hf _).2, map_top, supr_lsingle_range] } end lemma is_basis_single_one : is_basis R (λ i : ι, single i (1 : R)) := by convert (is_basis_single (λ (i : ι) (x : unit), (1 : R)) (λ i, is_basis_singleton_one R)).comp (λ i : ι, ⟨i, ()⟩) ⟨λ _ _, and.left ∘ sigma.mk.inj, λ ⟨i, ⟨⟩⟩, ⟨i, rfl⟩⟩ end ring section comm_ring variables {R : Type*} {M : Type*} {N : Type*} {ι : Type*} {κ : Type*} variables [comm_ring R] [add_comm_group M] [module R M] [add_comm_group N] [module R N] /-- If b : ι → M and c : κ → N are bases then so is λ i, b i.1 ⊗ₜ c i.2 : ι × κ → M ⊗ N. -/ lemma is_basis.tensor_product {b : ι → M} (hb : is_basis R b) {c : κ → N} (hc : is_basis R c) : is_basis R (λ i : ι × κ, b i.1 ⊗ₜ[R] c i.2) := by { convert linear_equiv.is_basis is_basis_single_one ((tensor_product.congr (module_equiv_finsupp hb) (module_equiv_finsupp hc)).trans $ (finsupp_tensor_finsupp _ _ _ _ _).trans $ lcongr (equiv.refl _) (tensor_product.lid R R)).symm, ext ⟨i, k⟩, rw [function.comp_apply, linear_equiv.eq_symm_apply], simp } end comm_ring section dim universes u v variables {K : Type u} {V : Type v} {ι : Type v} variables [field K] [add_comm_group V] [vector_space K V] lemma dim_eq : vector_space.dim K (ι →₀ V) = cardinal.mk ι * vector_space.dim K V := begin rcases exists_is_basis K V with ⟨bs, hbs⟩, rw [← cardinal.lift_inj, cardinal.lift_mul, ← hbs.mk_eq_dim, ← (is_basis_single _ (λa:ι, hbs)).mk_eq_dim, ← cardinal.sum_mk, ← cardinal.lift_mul, cardinal.lift_inj], { simp only [cardinal.mk_image_eq (single_injective.{u u} _), cardinal.sum_const] } end end dim end finsupp section vector_space /- We use `universe variables` instead of `universes` here because universes introduced by the `universes` keyword do not get replaced by metavariables once a lemma has been proven. So if you prove a lemma using universe `u`, you can only apply it to universe `u` in other lemmas of the same section. -/ universe variables u v w variables {K : Type u} {V V₁ V₂ : Type v} {V' : Type w} variables [field K] variables [add_comm_group V] [vector_space K V] variables [add_comm_group V₁] [vector_space K V₁] variables [add_comm_group V₂] [vector_space K V₂] variables [add_comm_group V'] [vector_space K V'] open vector_space lemma equiv_of_dim_eq_lift_dim (h : cardinal.lift.{v w} (dim K V) = cardinal.lift.{w v} (dim K V')) : nonempty (V ≃ₗ[K] V') := begin haveI := classical.dec_eq V, haveI := classical.dec_eq V', rcases exists_is_basis K V with ⟨m, hm⟩, rcases exists_is_basis K V' with ⟨m', hm'⟩, rw [←cardinal.lift_inj.1 hm.mk_eq_dim, ←cardinal.lift_inj.1 hm'.mk_eq_dim] at h, rcases quotient.exact h with ⟨e⟩, let e := (equiv.ulift.symm.trans e).trans equiv.ulift, exact ⟨((module_equiv_finsupp hm).trans (finsupp.dom_lcongr e)).trans (module_equiv_finsupp hm').symm⟩, end /-- Two `K`-vector spaces are equivalent if their dimension is the same. -/ def equiv_of_dim_eq_dim (h : dim K V₁ = dim K V₂) : V₁ ≃ₗ[K] V₂ := begin classical, exact classical.choice (equiv_of_dim_eq_lift_dim (cardinal.lift_inj.2 h)) end /-- An `n`-dimensional `K`-vector space is equivalent to `fin n → K`. -/ def fin_dim_vectorspace_equiv (n : ℕ) (hn : (dim K V) = n) : V ≃ₗ[K] (fin n → K) := begin have : cardinal.lift.{v u} (n : cardinal.{v}) = cardinal.lift.{u v} (n : cardinal.{u}), by simp, have hn := cardinal.lift_inj.{v u}.2 hn, rw this at hn, rw ←@dim_fin_fun K _ n at hn, exact classical.choice (equiv_of_dim_eq_lift_dim hn), end end vector_space section vector_space universes u open vector_space variables (K V : Type u) [field K] [add_comm_group V] [vector_space K V] lemma cardinal_mk_eq_cardinal_mk_field_pow_dim [finite_dimensional K V] : cardinal.mk V = cardinal.mk K ^ dim K V := begin rcases exists_is_basis K V with ⟨s, hs⟩, have : nonempty (fintype s), { rw [← cardinal.lt_omega_iff_fintype, cardinal.lift_inj.1 hs.mk_eq_dim], exact finite_dimensional.dim_lt_omega K V }, cases this with hsf, letI := hsf, calc cardinal.mk V = cardinal.mk (s →₀ K) : quotient.sound ⟨(module_equiv_finsupp hs).to_equiv⟩ ... = cardinal.mk (s → K) : quotient.sound ⟨finsupp.equiv_fun_on_fintype⟩ ... = _ : by rw [← cardinal.lift_inj.1 hs.mk_eq_dim, cardinal.power_def] end lemma cardinal_lt_omega_of_finite_dimensional [fintype K] [finite_dimensional K V] : cardinal.mk V < cardinal.omega := begin rw cardinal_mk_eq_cardinal_mk_field_pow_dim K V, exact cardinal.power_lt_omega (cardinal.lt_omega_iff_fintype.2 ⟨infer_instance⟩) (finite_dimensional.dim_lt_omega K V), end end vector_space
46256b05bc217d6eb97d8365371ad0210c690580
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/library/init/category/combinators.lean
d034302bc04048055f9e44e63cffcbe6d0151a12
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,609
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad Monad combinators, as in Haskell's Control.Monad. -/ prelude import init.category.monad init.data.list.basic universes u v w def mmap {m : Type u → Type v} [monad m] {α : Type w} {β : Type u} (f : α → m β) : list α → m (list β) | [] := return [] | (h :: t) := do h' ← f h, t' ← mmap t, return (h' :: t') def mmap' {m : Type → Type v} [monad m] {α : Type u} {β : Type} (f : α → m β) : list α → m unit | [] := return () | (h :: t) := f h >> mmap' t def mfor {m : Type u → Type v} [monad m] {α : Type w} {β : Type u} (l : list α) (f : α → m β) : m (list β) := mmap f l def mfor' {m : Type → Type v} [monad m] {α : Type u} {β : Type} (l : list α) (f : α → m β) : m unit := mmap' f l infix ` =<< `:2 := λ u v, v >>= u infix ` >=> `:2 := λ s t a, s a >>= t infix ` <=< `:2 := λ t s a, s a >>= t def mjoin {m : Type u → Type u} [monad m] {α : Type u} (a : m (m α)) : m α := bind a id def mfilter {m : Type → Type v} [monad m] {α : Type} (f : α → m bool) : list α → m (list α) | [] := return [] | (h :: t) := do b ← f h, t' ← mfilter t, cond b (return (h :: t')) (return t') def mfoldl {m : Type u → Type v} [monad m] {s : Type u} {α : Type w} : (s → α → m s) → s → list α → m s | f s [] := return s | f s (h :: r) := do s' ← f s h, mfoldl f s' r def when {m : Type → Type} [monad m] (c : Prop) [h : decidable c] (t : m unit) : m unit := ite c t (pure ()) def mcond {m : Type → Type} [monad m] {α : Type} (mbool : m bool) (tm fm : m α) : m α := do b ← mbool, cond b tm fm def mwhen {m : Type → Type} [monad m] (c : m bool) (t : m unit) : m unit := mcond c t (return ()) namespace monad def mapm := @mmap def mapm' := @mmap' def for := @mfor def for' := @mfor' def join := @mjoin def filter := @mfilter def foldl := @mfoldl def cond := @mcond def sequence {m : Type u → Type v} [monad m] {α : Type u} : list (m α) → m (list α) | [] := return [] | (h :: t) := do h' ← h, t' ← sequence t, return (h' :: t') def sequence' {m : Type → Type u} [monad m] {α : Type} : list (m α) → m unit | [] := return () | (h :: t) := h >> sequence' t def whenb {m : Type → Type} [monad m] (b : bool) (t : m unit) : m unit := _root_.cond b t (return ()) def unlessb {m : Type → Type} [monad m] (b : bool) (t : m unit) : m unit := _root_.cond b (return ()) t def lift {m : Type u → Type v} [monad m] {α φ : Type u} (f : α → φ) (ma : m α) : m φ := do a ← ma, return (f a) def lift₂ {m : Type u → Type v} [monad m] {α φ : Type u} (f : α → α → φ) (ma₁ ma₂: m α) : m φ := do a₁ ← ma₁, a₂ ← ma₂, return (f a₁ a₂) def lift₃ {m : Type u → Type v} [monad m] {α φ : Type u} (f : α → α → α → φ) (ma₁ ma₂ ma₃ : m α) : m φ := do a₁ ← ma₁, a₂ ← ma₂, a₃ ← ma₃, return (f a₁ a₂ a₃) def lift₄ {m : Type u → Type v} [monad m] {α φ : Type u} (f : α → α → α → α → φ) (ma₁ ma₂ ma₃ ma₄ : m α) : m φ := do a₁ ← ma₁, a₂ ← ma₂, a₃ ← ma₃, a₄ ← ma₄, return (f a₁ a₂ a₃ a₄) def lift₅ {m : Type u → Type v} [monad m] {α φ : Type u} (f : α → α → α → α → α → φ) (ma₁ ma₂ ma₃ ma₄ ma₅ : m α) : m φ := do a₁ ← ma₁, a₂ ← ma₂, a₃ ← ma₃, a₄ ← ma₄, a₅ ← ma₅, return (f a₁ a₂ a₃ a₄ a₅) end monad
1486d015cd836c9dfda900569196ef8ed6db2ec5
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/reader.lean
7aadc489ed365a5fb9dcf610c2bac67ed92f3597
[ "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
298
lean
import system.io def lifted_test : state_t ℕ (reader_t ℕ io) unit := do 0 ← get, 1 ← read, adapt_reader (λ n, (n, 2)) ((do p ← read, put p.2) : state_t ℕ (reader_t (ℕ × ℕ) io) _), 2 ← get, pure () #eval (lifted_test.run 0).run 1
7e96df9726bbc606e832fe25bc7a8457bb569cbe
6214e13b31733dc9aeb4833db6a6466005763162
/src/soundness.lean
a4c81d92ec35f77feb1a0d36dfab14b622c7a892
[]
no_license
joshua0pang/esverify-theory
272a250445f3aeea49a7e72d1ab58c2da6618bbe
8565b123c87b0113f83553d7732cd6696c9b5807
refs/heads/master
1,585,873,849,081
1,527,304,393,000
1,527,304,393,000
154,901,199
1
0
null
1,540,593,067,000
1,540,593,067,000
null
UTF-8
Lean
false
false
3,779
lean
import .definitions3 .progress .preservation lemma true_true_freevars: FV (prop.term value.true ⋀ prop.term value.true) = FV (prop.term value.true) := have h1: FV (prop.term value.true ⋀ prop.term value.true) = ∅, from set.eq_empty_of_forall_not_mem ( assume x: var, assume : x ∈ FV (prop.term value.true ⋀ prop.term value.true), have x ∈ FV (prop.term value.true) ∨ x ∈ FV (prop.term value.true), from free_in_prop.and.inv this, or.elim this ( assume : x ∈ FV (prop.term value.true), have x ∈ FV (term.value value.true), from free_in_prop.term.inv this, show «false», from free_in_term.value.inv this ) ( assume : x ∈ FV (prop.term value.true), have x ∈ FV (term.value value.true), from free_in_prop.term.inv this, show «false», from free_in_term.value.inv this ) ), have h2: FV (prop.term value.true) = ∅, from set.eq_empty_of_forall_not_mem ( assume x: var, assume : x ∈ FV (prop.term value.true), have x ∈ FV (term.value value.true), from free_in_prop.term.inv this, show «false», from free_in_term.value.inv this ), show FV (prop.term value.true ⋀ prop.term value.true) = FV (prop.term value.true), from eq.trans h1 h2.symm lemma true_true_implies_true {σ: env}: σ ⊨ vc.implies (prop.term value.true ⋀ prop.term value.true).to_vc (prop.term value.true).to_vc := begin apply valid_env.mpr, assume h1, unfold prop.to_vc, from valid_env.true end lemma true_spec_freevars: FV (spec.to_prop (spec.term value.true)) ⊆ FV (prop.term value.true) := begin assume x, assume h1, unfold spec.to_prop at h1, have h2, from free_in_prop.term.inv h1, have h3: ¬ free_in_term x ↑value.true, from free_in_term.value.inv, contradiction end lemma true_spec_valid: env.empty ⊨ prop.to_vc (spec.to_prop (spec.term ↑value.true)) := begin unfold vc.subst_env, unfold spec.to_prop, unfold prop.to_vc, from valid.tru end lemma dsoundness {s s': dstack} {Q: propctx}: (s ⟹* s') → (⊩ₛ s: Q) → (is_dvalue s' ∨ ∃s'', s' ⟹ s'') := begin have : ∀{s s': dstack} {Q: propctx}, (s ⟹* s') → (⊩ₛ s: Q) → (∃Q': propctx, ⊩ₛ s' : Q'), by begin assume s s' Q steps_to_s', induction steps_to_s', case trans_dstep.rfl s₁ { assume s₁_verified, existsi Q, from s₁_verified }, case trans_dstep.trans s₁ s₂ s₃ s₁_steps_to_s₂ s₂_steps_to_s₃ ih { assume s₁_verified, cases ih s₁_verified with Q₂ h1, cases preservation h1 s₃ s₂_steps_to_s₃ with Q₃ h2, from exists.intro Q₃ h2.left } end, assume h1 h2, cases this h1 h2 with Q' h3, from progress h3 end lemma soundness_source_programs {e: exp} {s: stack} {Q: propctx}: (value.true ⊢ e: Q) → ((env.empty, e) ⟶* s) → (is_value s ∨ ∃s', s ⟶ s') := assume : value.true ⊢ e: Q, have value.true ⊩ e: Q, from exp.vcgen.extension this, have value.true ⋀ value.true ⊩ e : Q, from strengthen_exp this (value.true ⋀ value.true) true_true_freevars (λσ, true_true_implies_true), have h1: ⊩ₛ (spec.term value.true, env.empty, e) : value.true ⋀ Q, from stack.dvcgen.top env.dvcgen.empty true_spec_freevars true_spec_valid this, assume : (env.empty, e) ⟶* s, have ∃d', ((spec.term value.true, env.empty, e) ⟹* d') ∧ stack_equiv_dstack s d', from dstep_of_step_trans this (spec.term value.true, env.empty, e) stack_equiv_dstack.top, let ⟨d', h2⟩ := this in have is_dvalue d' ∨ ∃d'', d' ⟹ d'', from dsoundness h2.left h1, show is_value s ∨ ∃s', s ⟶ s', from value_or_step_of_dvalue_or_dstep h2.right this
d91bdce38f15d5e7522069b42e6deae147451fd6
c1a29ca460720df88ab68dc42d9a1a02e029d505
/examples/introduction/unnamed_111.lean
91ebd546cb8a9c2df8e51a63d55280052bfbb537
[]
no_license
agusakov/mathematics_in_lean
acb5b3d659e4522ae4b4836ea550527f03f6546c
2539562e4d91c858c73dbecb5b282ce1a7d38b6d
refs/heads/master
1,665,963,365,241
1,592,080,022,000
1,592,080,022,000
272,078,062
0
0
null
1,592,078,772,000
1,592,078,772,000
null
UTF-8
Lean
false
false
141
lean
#check 2 + 2 = 4 def fermat_last_theorem := ∀ x y z n : ℕ, n > 2 → x * y * z ≠ 0 → x^n + y^n ≠ z^n #check fermat_last_theorem
2bc84d1502db4c448828a2b721ef2bac026b444a
130c49f47783503e462c16b2eff31933442be6ff
/stage0/src/Init/WF.lean
de9c3ff473299e269f924c6b6fa0c8b1565fee8d
[ "Apache-2.0" ]
permissive
Hazel-Brown/lean4
8aa5860e282435ffc30dcdfccd34006c59d1d39c
79e6732fc6bbf5af831b76f310f9c488d44e7a16
refs/heads/master
1,689,218,208,951
1,629,736,869,000
1,629,736,896,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,166
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 -/ prelude import Init.SizeOf import Init.Data.Nat.Basic universe u v set_option codegen false inductive Acc {α : Sort u} (r : α → α → Prop) : α → Prop where | intro (x : α) (h : (y : α) → r y x → Acc r y) : Acc r x abbrev Acc.ndrec.{u1, u2} {α : Sort u2} {r : α → α → Prop} {C : α → Sort u1} (m : (x : α) → ((y : α) → r y x → Acc r y) → ((y : α) → (a : r y x) → C y) → C x) {a : α} (n : Acc r a) : C a := Acc.rec (motive := fun α _ => C α) m n abbrev Acc.ndrecOn.{u1, u2} {α : Sort u2} {r : α → α → Prop} {C : α → Sort u1} {a : α} (n : Acc r a) (m : (x : α) → ((y : α) → r y x → Acc r y) → ((y : α) → (a : r y x) → C y) → C x) : C a := Acc.rec (motive := fun α _ => C α) m n namespace Acc variable {α : Sort u} {r : α → α → Prop} def inv {x y : α} (h₁ : Acc r x) (h₂ : r y x) : Acc r y := Acc.recOn (motive := fun (x : α) _ => r y x → Acc r y) h₁ (fun x₁ ac₁ ih h₂ => ac₁ y h₂) h₂ end Acc inductive WellFounded {α : Sort u} (r : α → α → Prop) : Prop where | intro (h : ∀ a, Acc r a) : WellFounded r class WellFoundedRelation (α : Sort u) : Type u where r : α → α → Prop wf : WellFounded r namespace WellFounded def apply {α : Sort u} {r : α → α → Prop} (wf : WellFounded r) (a : α) : Acc r a := WellFounded.recOn (motive := fun x => (y : α) → Acc r y) wf (fun p => p) a section variable {α : Sort u} {r : α → α → Prop} (hwf : WellFounded r) theorem recursion {C : α → Sort v} (a : α) (h : ∀ x, (∀ y, r y x → C y) → C x) : C a := by induction (apply hwf a) with | intro x₁ ac₁ ih => exact h x₁ ih theorem induction {C : α → Prop} (a : α) (h : ∀ x, (∀ y, r y x → C y) → C x) : C a := recursion hwf a h variable {C : α → Sort v} variable (F : ∀ x, (∀ y, r y x → C y) → C x) def fixF (x : α) (a : Acc r x) : C x := by induction a with | intro x₁ ac₁ ih => exact F x₁ ih def fixFEq (x : α) (acx : Acc r x) : fixF F x acx = F x (fun (y : α) (p : r y x) => fixF F y (Acc.inv acx p)) := by induction acx with | intro x r ih => exact rfl end variable {α : Sort u} {C : α → Sort v} {r : α → α → Prop} -- Well-founded fixpoint def fix (hwf : WellFounded r) (F : ∀ x, (∀ y, r y x → C y) → C x) (x : α) : C x := fixF F x (apply hwf x) -- Well-founded fixpoint satisfies fixpoint equation theorem fix_eq (hwf : WellFounded r) (F : ∀ x, (∀ y, r y x → C y) → C x) (x : α) : fix hwf F x = F x (fun y h => fix hwf F y) := fixFEq F x (apply hwf x) end WellFounded open WellFounded -- Empty relation is well-founded def emptyWf {α : Sort u} : WellFounded (@emptyRelation α) := by apply WellFounded.intro intro a apply Acc.intro a intro b h cases h -- Subrelation of a well-founded relation is well-founded namespace Subrelation variable {α : Sort u} {r q : α → α → Prop} def accessible {a : α} (h₁ : Subrelation q r) (ac : Acc r a) : Acc q a := by induction ac with | intro x ax ih => apply Acc.intro intro y h exact ih y (h₁ h) def wf (h₁ : Subrelation q r) (h₂ : WellFounded r) : WellFounded q := ⟨fun a => accessible @h₁ (apply h₂ a)⟩ end Subrelation -- The inverse image of a well-founded relation is well-founded namespace InvImage variable {α : Sort u} {β : Sort v} {r : β → β → Prop} private def accAux (f : α → β) {b : β} (ac : Acc r b) : (x : α) → f x = b → Acc (InvImage r f) x := by induction ac with | intro x acx ih => intro z e apply Acc.intro intro y lt subst x apply ih (f y) lt y rfl def accessible {a : α} (f : α → β) (ac : Acc r (f a)) : Acc (InvImage r f) a := accAux f ac a rfl def wf (f : α → β) (h : WellFounded r) : WellFounded (InvImage r f) := ⟨fun a => accessible f (apply h (f a))⟩ end InvImage -- The transitive closure of a well-founded relation is well-founded namespace TC variable {α : Sort u} {r : α → α → Prop} def accessible {z : α} (ac : Acc r z) : Acc (TC r) z := by induction ac with | intro x acx ih => apply Acc.intro x intro y rel induction rel with | base a b rab => exact ih a rab | trans a b c rab rbc ih₁ ih₂ => apply Acc.inv (ih₂ acx ih) rab def wf (h : WellFounded r) : WellFounded (TC r) := ⟨fun a => accessible (apply h a)⟩ end TC -- less-than is well-founded def Nat.ltWf : WellFounded Nat.lt := by apply WellFounded.intro intro n induction n with | zero => apply Acc.intro 0 intro _ h apply absurd h (Nat.not_lt_zero _) | succ n ih => apply Acc.intro (Nat.succ n) intro m h have : m = n ∨ m < n := Nat.eq_or_lt_of_le (Nat.le_of_succ_le_succ h) match this with | Or.inl e => subst e; assumption | Or.inr e => exact Acc.inv ih e def measure {α : Sort u} : (α → Nat) → α → α → Prop := InvImage (fun a b => a < b) def measureWf {α : Sort u} (f : α → Nat) : WellFounded (measure f) := InvImage.wf f Nat.ltWf def sizeofMeasure (α : Sort u) [SizeOf α] : α → α → Prop := measure sizeOf def sizeofMeasureWf (α : Sort u) [SizeOf α] : WellFounded (sizeofMeasure α) := measureWf sizeOf instance hasWellFoundedOfSizeOf (α : Sort u) [SizeOf α] : WellFoundedRelation α where r := sizeofMeasure α wf := sizeofMeasureWf α namespace Prod open WellFounded section variable {α : Type u} {β : Type v} variable (ra : α → α → Prop) variable (rb : β → β → Prop) -- Lexicographical order based on ra and rb inductive Lex : α × β → α × β → Prop where | left {a₁} (b₁) {a₂} (b₂) (h : ra a₁ a₂) : Lex (a₁, b₁) (a₂, b₂) | right (a) {b₁ b₂} (h : rb b₁ b₂) : Lex (a, b₁) (a, b₂) -- relational product based on ra and rb inductive Rprod : α × β → α × β → Prop where | intro {a₁ b₁ a₂ b₂} (h₁ : ra a₁ a₂) (h₂ : rb b₁ b₂) : Rprod (a₁, b₁) (a₂, b₂) end section variable {α : Type u} {β : Type v} variable {ra : α → α → Prop} {rb : β → β → Prop} def lexAccessible (aca : (a : α) → Acc ra a) (acb : (b : β) → Acc rb b) (a : α) (b : β) : Acc (Lex ra rb) (a, b) := by induction (aca a) generalizing b with | intro xa aca iha => induction (acb b) with | intro xb acb ihb => apply Acc.intro (xa, xb) intro p lt cases lt with | left _ _ h => apply iha _ h | right _ h => apply ihb _ h -- The lexicographical order of well founded relations is well-founded def lexWf (ha : WellFounded ra) (hb : WellFounded rb) : WellFounded (Lex ra rb) := ⟨fun (a, b) => lexAccessible (WellFounded.apply ha) (WellFounded.apply hb) a b⟩ -- relational product is a Subrelation of the Lex def rprodSubLex (a : α × β) (b : α × β) (h : Rprod ra rb a b) : Lex ra rb a b := by cases h with | intro h₁ h₂ => exact Lex.left _ _ h₁ -- The relational product of well founded relations is well-founded def rprodWf (ha : WellFounded ra) (hb : WellFounded rb) : WellFounded (Rprod ra rb) := by apply Subrelation.wf (r := Lex ra rb) (h₂ := lexWf ha hb) intro a b h exact rprodSubLex a b h end instance {α : Type u} {β : Type v} [s₁ : WellFoundedRelation α] [s₂ : WellFoundedRelation β] : WellFoundedRelation (α × β) where r := Lex s₁.r s₂.r wf := lexWf s₁.wf s₂.wf end Prod namespace PSigma section variable {α : Sort u} {β : α → Sort v} variable (r : α → α → Prop) variable (s : ∀ a, β a → β a → Prop) -- Lexicographical order based on r and s inductive Lex : PSigma β → PSigma β → Prop where | left : ∀ {a₁ : α} (b₁ : β a₁) {a₂ : α} (b₂ : β a₂), r a₁ a₂ → Lex ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ | right : ∀ (a : α) {b₁ b₂ : β a}, s a b₁ b₂ → Lex ⟨a, b₁⟩ ⟨a, b₂⟩ end section variable {α : Sort u} {β : α → Sort v} variable {r : α → α → Prop} {s : ∀ (a : α), β a → β a → Prop} def lexAccessible {a} (aca : Acc r a) (acb : (a : α) → WellFounded (s a)) (b : β a) : Acc (Lex r s) ⟨a, b⟩ := by induction aca with | intro xa aca iha => induction (WellFounded.apply (acb xa) b) with | intro xb acb ihb => apply Acc.intro intro p lt cases lt with | left => apply iha; assumption | right => apply ihb; assumption -- The lexicographical order of well founded relations is well-founded def lexWf (ha : WellFounded r) (hb : (x : α) → WellFounded (s x)) : WellFounded (Lex r s) := WellFounded.intro fun ⟨a, b⟩ => lexAccessible (WellFounded.apply ha a) hb b end section variable {α : Sort u} {β : Sort v} def lexNdep (r : α → α → Prop) (s : β → β → Prop) := Lex r (fun a => s) def lexNdepWf {r : α → α → Prop} {s : β → β → Prop} (ha : WellFounded r) (hb : WellFounded s) : WellFounded (lexNdep r s) := WellFounded.intro fun ⟨a, b⟩ => lexAccessible (WellFounded.apply ha a) (fun x => hb) b end section variable {α : Sort u} {β : Sort v} -- Reverse lexicographical order based on r and s inductive RevLex (r : α → α → Prop) (s : β → β → Prop) : @PSigma α (fun a => β) → @PSigma α (fun a => β) → Prop where | left : {a₁ a₂ : α} → (b : β) → r a₁ a₂ → RevLex r s ⟨a₁, b⟩ ⟨a₂, b⟩ | right : (a₁ : α) → {b₁ : β} → (a₂ : α) → {b₂ : β} → s b₁ b₂ → RevLex r s ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ end section open WellFounded variable {α : Sort u} {β : Sort v} variable {r : α → α → Prop} {s : β → β → Prop} def revLexAccessible {b} (acb : Acc s b) (aca : (a : α) → Acc r a): (a : α) → Acc (RevLex r s) ⟨a, b⟩ := by induction acb with | intro xb acb ihb => intro a induction (aca a) with | intro xa aca iha => apply Acc.intro intro p lt cases lt with | left => apply iha; assumption | right => apply ihb; assumption def revLexWf (ha : WellFounded r) (hb : WellFounded s) : WellFounded (RevLex r s) := WellFounded.intro fun ⟨a, b⟩ => revLexAccessible (apply hb b) (WellFounded.apply ha) a end section def skipLeft (α : Type u) {β : Type v} (s : β → β → Prop) : @PSigma α (fun a => β) → @PSigma α (fun a => β) → Prop := RevLex emptyRelation s def skipLeftWf (α : Type u) {β : Type v} {s : β → β → Prop} (hb : WellFounded s) : WellFounded (skipLeft α s) := revLexWf emptyWf hb def mkSkipLeft {α : Type u} {β : Type v} {b₁ b₂ : β} {s : β → β → Prop} (a₁ a₂ : α) (h : s b₁ b₂) : skipLeft α s ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ := RevLex.right _ _ h end instance WellFoundedRelation {α : Type u} {β : α → Type v} [s₁ : WellFoundedRelation α] [s₂ : ∀ a, WellFoundedRelation (β a)] : WellFoundedRelation (PSigma β) where r := Lex s₁.r (fun a => (s₂ a).r) wf := lexWf s₁.wf (fun a => (s₂ a).wf) end PSigma
f9ab594fb7a58d3444eb75239a4daed7473d3f38
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/data/stream/init.lean
d48687ae32734224390ce07189632bb9a899cdfc
[ "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
22,037
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ /-! # Streams a.k.a. infinite lists a.k.a. infinite sequences This file used to be in the core library. It was moved to `mathlib` and renamed to `init` to avoid name clashes. -/ open nat function option universes u v w def stream (α : Type u) := nat → α namespace stream variables {α : Type u} {β : Type v} {δ : Type w} def cons (a : α) (s : stream α) : stream α := λ i, match i with | 0 := a | succ n := s n end notation h :: t := cons h t @[reducible] def head (s : stream α) : α := s 0 def tail (s : stream α) : stream α := λ i, s (i+1) def drop (n : nat) (s : stream α) : stream α := λ i, s (i+n) @[reducible] def nth (n : nat) (s : stream α) : α := s n protected theorem eta (s : stream α) : head s :: tail s = s := funext (λ i, begin cases i; refl end) theorem nth_zero_cons (a : α) (s : stream α) : nth 0 (a :: s) = a := rfl theorem head_cons (a : α) (s : stream α) : head (a :: s) = a := rfl theorem tail_cons (a : α) (s : stream α) : tail (a :: s) = s := rfl theorem tail_drop (n : nat) (s : stream α) : tail (drop n s) = drop n (tail s) := funext (λ i, begin unfold tail drop, simp [nat.add_comm, nat.add_left_comm] end) theorem nth_drop (n m : nat) (s : stream α) : nth n (drop m s) = nth (n+m) s := rfl theorem tail_eq_drop (s : stream α) : tail s = drop 1 s := rfl theorem drop_drop (n m : nat) (s : stream α) : drop n (drop m s) = drop (n+m) s := funext (λ i, begin unfold drop, rw nat.add_assoc end) theorem nth_succ (n : nat) (s : stream α) : nth (succ n) s = nth n (tail s) := rfl theorem drop_succ (n : nat) (s : stream α) : drop (succ n) s = drop n (tail s) := rfl protected theorem ext {s₁ s₂ : stream α} : (∀ n, nth n s₁ = nth n s₂) → s₁ = s₂ := assume h, funext h def all (p : α → Prop) (s : stream α) := ∀ n, p (nth n s) def any (p : α → Prop) (s : stream α) := ∃ n, p (nth n s) theorem all_def (p : α → Prop) (s : stream α) : all p s = ∀ n, p (nth n s) := rfl theorem any_def (p : α → Prop) (s : stream α) : any p s = ∃ n, p (nth n s) := rfl protected def mem (a : α) (s : stream α) := any (λ b, a = b) s instance : has_mem α (stream α) := ⟨stream.mem⟩ theorem mem_cons (a : α) (s : stream α) : a ∈ (a::s) := exists.intro 0 rfl theorem mem_cons_of_mem {a : α} {s : stream α} (b : α) : a ∈ s → a ∈ b :: s := assume ⟨n, h⟩, exists.intro (succ n) (by rw [nth_succ, tail_cons, h]) theorem eq_or_mem_of_mem_cons {a b : α} {s : stream α} : a ∈ b::s → a = b ∨ a ∈ s := assume ⟨n, h⟩, begin cases n with n', { left, exact h }, { right, rw [nth_succ, tail_cons] at h, exact ⟨n', h⟩ } end theorem mem_of_nth_eq {n : nat} {s : stream α} {a : α} : a = nth n s → a ∈ s := assume h, exists.intro n h section map variable (f : α → β) def map (s : stream α) : stream β := λ n, f (nth n s) theorem drop_map (n : nat) (s : stream α) : drop n (map f s) = map f (drop n s) := stream.ext (λ i, rfl) theorem nth_map (n : nat) (s : stream α) : nth n (map f s) = f (nth n s) := rfl theorem tail_map (s : stream α) : tail (map f s) = map f (tail s) := begin rw tail_eq_drop, refl end theorem head_map (s : stream α) : head (map f s) = f (head s) := rfl theorem map_eq (s : stream α) : map f s = f (head s) :: map f (tail s) := by rw [← stream.eta (map f s), tail_map, head_map] theorem map_cons (a : α) (s : stream α) : map f (a :: s) = f a :: map f s := begin rw [← stream.eta (map f (a :: s)), map_eq], refl end theorem map_id (s : stream α) : map id s = s := rfl theorem map_map (g : β → δ) (f : α → β) (s : stream α) : map g (map f s) = map (g ∘ f) s := rfl theorem map_tail (s : stream α) : map f (tail s) = tail (map f s) := rfl theorem mem_map {a : α} {s : stream α} : a ∈ s → f a ∈ map f s := assume ⟨n, h⟩, exists.intro n (by rw [nth_map, h]) theorem exists_of_mem_map {f} {b : β} {s : stream α} : b ∈ map f s → ∃ a, a ∈ s ∧ f a = b := assume ⟨n, h⟩, ⟨nth n s, ⟨n, rfl⟩, h.symm⟩ end map section zip variable (f : α → β → δ) def zip (s₁ : stream α) (s₂ : stream β) : stream δ := λ n, f (nth n s₁) (nth n s₂) theorem drop_zip (n : nat) (s₁ : stream α) (s₂ : stream β) : drop n (zip f s₁ s₂) = zip f (drop n s₁) (drop n s₂) := stream.ext (λ i, rfl) theorem nth_zip (n : nat) (s₁ : stream α) (s₂ : stream β) : nth n (zip f s₁ s₂) = f (nth n s₁) (nth n s₂) := rfl theorem head_zip (s₁ : stream α) (s₂ : stream β) : head (zip f s₁ s₂) = f (head s₁) (head s₂) := rfl theorem tail_zip (s₁ : stream α) (s₂ : stream β) : tail (zip f s₁ s₂) = zip f (tail s₁) (tail s₂) := rfl theorem zip_eq (s₁ : stream α) (s₂ : stream β) : zip f s₁ s₂ = f (head s₁) (head s₂) :: zip f (tail s₁) (tail s₂) := begin rw [← stream.eta (zip f s₁ s₂)], refl end end zip def const (a : α) : stream α := λ n, a theorem mem_const (a : α) : a ∈ const a := exists.intro 0 rfl theorem const_eq (a : α) : const a = a :: const a := begin apply stream.ext, intro n, cases n; refl end theorem tail_const (a : α) : tail (const a) = const a := suffices tail (a :: const a) = const a, by rwa [← const_eq] at this, rfl theorem map_const (f : α → β) (a : α) : map f (const a) = const (f a) := rfl theorem nth_const (n : nat) (a : α) : nth n (const a) = a := rfl theorem drop_const (n : nat) (a : α) : drop n (const a) = const a := stream.ext (λ i, rfl) def iterate (f : α → α) (a : α) : stream α := λ n, nat.rec_on n a (λ n r, f r) theorem head_iterate (f : α → α) (a : α) : head (iterate f a) = a := rfl theorem tail_iterate (f : α → α) (a : α) : tail (iterate f a) = iterate f (f a) := begin funext n, induction n with n' ih, { refl }, { unfold tail iterate, unfold tail iterate at ih, rw add_one at ih, dsimp at ih, rw add_one, dsimp, rw ih } end theorem iterate_eq (f : α → α) (a : α) : iterate f a = a :: iterate f (f a) := begin rw [← stream.eta (iterate f a)], rw tail_iterate, refl end theorem nth_zero_iterate (f : α → α) (a : α) : nth 0 (iterate f a) = a := rfl theorem nth_succ_iterate (n : nat) (f : α → α) (a : α) : nth (succ n) (iterate f a) = nth n (iterate f (f a)) := by rw [nth_succ, tail_iterate] section bisim variable (R : stream α → stream α → Prop) local infix ` ~ `:50 := R def is_bisimulation := ∀ ⦃s₁ s₂⦄, s₁ ~ s₂ → head s₁ = head s₂ ∧ tail s₁ ~ tail s₂ theorem nth_of_bisim (bisim : is_bisimulation R) : ∀ {s₁ s₂} n, s₁ ~ s₂ → nth n s₁ = nth n s₂ ∧ drop (n+1) s₁ ~ drop (n+1) s₂ | s₁ s₂ 0 h := bisim h | s₁ s₂ (n+1) h := match bisim h with | ⟨h₁, trel⟩ := nth_of_bisim n trel end -- If two streams are bisimilar, then they are equal theorem eq_of_bisim (bisim : is_bisimulation R) : ∀ {s₁ s₂}, s₁ ~ s₂ → s₁ = s₂ := λ s₁ s₂ r, stream.ext (λ n, and.elim_left (nth_of_bisim R bisim n r)) end bisim theorem bisim_simple (s₁ s₂ : stream α) : head s₁ = head s₂ → s₁ = tail s₁ → s₂ = tail s₂ → s₁ = s₂ := assume hh ht₁ ht₂, eq_of_bisim (λ s₁ s₂, head s₁ = head s₂ ∧ s₁ = tail s₁ ∧ s₂ = tail s₂) (λ s₁ s₂ ⟨h₁, h₂, h₃⟩, begin constructor, exact h₁, rw [← h₂, ← h₃], repeat { constructor }; assumption end) (and.intro hh (and.intro ht₁ ht₂)) theorem coinduction {s₁ s₂ : stream α} : head s₁ = head s₂ → (∀ (β : Type u) (fr : stream α → β), fr s₁ = fr s₂ → fr (tail s₁) = fr (tail s₂)) → s₁ = s₂ := assume hh ht, eq_of_bisim (λ s₁ s₂, head s₁ = head s₂ ∧ ∀ (β : Type u) (fr : stream α → β), fr s₁ = fr s₂ → fr (tail s₁) = fr (tail s₂)) (λ s₁ s₂ h, have h₁ : head s₁ = head s₂, from and.elim_left h, have h₂ : head (tail s₁) = head (tail s₂), from and.elim_right h α (@head α) h₁, have h₃ : ∀ (β : Type u) (fr : stream α → β), fr (tail s₁) = fr (tail s₂) → fr (tail (tail s₁)) = fr (tail (tail s₂)), from λ β fr, and.elim_right h β (λ s, fr (tail s)), and.intro h₁ (and.intro h₂ h₃)) (and.intro hh ht) theorem iterate_id (a : α) : iterate id a = const a := coinduction rfl (λ β fr ch, begin rw [tail_iterate, tail_const], exact ch end) local attribute [reducible] stream theorem map_iterate (f : α → α) (a : α) : iterate f (f a) = map f (iterate f a) := begin funext n, induction n with n' ih, { refl }, { unfold map iterate nth, dsimp, unfold map iterate nth at ih, dsimp at ih, rw ih } end section corec def corec (f : α → β) (g : α → α) : α → stream β := λ a, map f (iterate g a) def corec_on (a : α) (f : α → β) (g : α → α) : stream β := corec f g a theorem corec_def (f : α → β) (g : α → α) (a : α) : corec f g a = map f (iterate g a) := rfl theorem corec_eq (f : α → β) (g : α → α) (a : α) : corec f g a = f a :: corec f g (g a) := begin rw [corec_def, map_eq, head_iterate, tail_iterate], refl end theorem corec_id_id_eq_const (a : α) : corec id id a = const a := by rw [corec_def, map_id, iterate_id] theorem corec_id_f_eq_iterate (f : α → α) (a : α) : corec id f a = iterate f a := rfl end corec section corec' def corec' (f : α → β × α) : α → stream β := corec (prod.fst ∘ f) (prod.snd ∘ f) theorem corec'_eq (f : α → β × α) (a : α) : corec' f a = (f a).1 :: corec' f (f a).2 := corec_eq _ _ _ end corec' -- corec is also known as unfold def unfolds (g : α → β) (f : α → α) (a : α) : stream β := corec g f a theorem unfolds_eq (g : α → β) (f : α → α) (a : α) : unfolds g f a = g a :: unfolds g f (f a) := begin unfold unfolds, rw [corec_eq] end theorem nth_unfolds_head_tail : ∀ (n : nat) (s : stream α), nth n (unfolds head tail s) = nth n s := begin intro n, induction n with n' ih, { intro s, refl }, { intro s, rw [nth_succ, nth_succ, unfolds_eq, tail_cons, ih] } end theorem unfolds_head_eq : ∀ (s : stream α), unfolds head tail s = s := λ s, stream.ext (λ n, nth_unfolds_head_tail n s) def interleave (s₁ s₂ : stream α) : stream α := corec_on (s₁, s₂) (λ ⟨s₁, s₂⟩, head s₁) (λ ⟨s₁, s₂⟩, (s₂, tail s₁)) infix `⋈`:65 := interleave theorem interleave_eq (s₁ s₂ : stream α) : s₁ ⋈ s₂ = head s₁ :: head s₂ :: (tail s₁ ⋈ tail s₂) := begin unfold interleave corec_on, rw corec_eq, dsimp, rw corec_eq, refl end theorem tail_interleave (s₁ s₂ : stream α) : tail (s₁ ⋈ s₂) = s₂ ⋈ (tail s₁) := begin unfold interleave corec_on, rw corec_eq, refl end theorem interleave_tail_tail (s₁ s₂ : stream α) : tail s₁ ⋈ tail s₂ = tail (tail (s₁ ⋈ s₂)) := begin rw [interleave_eq s₁ s₂], refl end theorem nth_interleave_left : ∀ (n : nat) (s₁ s₂ : stream α), nth (2*n) (s₁ ⋈ s₂) = nth n s₁ | 0 s₁ s₂ := rfl | (succ n) s₁ s₂ := begin change nth (succ (succ (2*n))) (s₁ ⋈ s₂) = nth (succ n) s₁, rw [nth_succ, nth_succ, interleave_eq, tail_cons, tail_cons, nth_interleave_left], refl end theorem nth_interleave_right : ∀ (n : nat) (s₁ s₂ : stream α), nth (2*n+1) (s₁ ⋈ s₂) = nth n s₂ | 0 s₁ s₂ := rfl | (succ n) s₁ s₂ := begin change nth (succ (succ (2*n+1))) (s₁ ⋈ s₂) = nth (succ n) s₂, rw [nth_succ, nth_succ, interleave_eq, tail_cons, tail_cons, nth_interleave_right], refl end theorem mem_interleave_left {a : α} {s₁ : stream α} (s₂ : stream α) : a ∈ s₁ → a ∈ s₁ ⋈ s₂ := assume ⟨n, h⟩, exists.intro (2*n) (by rw [h, nth_interleave_left]) theorem mem_interleave_right {a : α} {s₁ : stream α} (s₂ : stream α) : a ∈ s₂ → a ∈ s₁ ⋈ s₂ := assume ⟨n, h⟩, exists.intro (2*n+1) (by rw [h, nth_interleave_right]) def even (s : stream α) : stream α := corec (λ s, head s) (λ s, tail (tail s)) s def odd (s : stream α) : stream α := even (tail s) theorem odd_eq (s : stream α) : odd s = even (tail s) := rfl theorem head_even (s : stream α) : head (even s) = head s := rfl theorem tail_even (s : stream α) : tail (even s) = even (tail (tail s)) := begin unfold even, rw corec_eq, refl end theorem even_cons_cons (a₁ a₂ : α) (s : stream α) : even (a₁ :: a₂ :: s) = a₁ :: even s := begin unfold even, rw corec_eq, refl end theorem even_tail (s : stream α) : even (tail s) = odd s := rfl theorem even_interleave (s₁ s₂ : stream α) : even (s₁ ⋈ s₂) = s₁ := eq_of_bisim (λ s₁' s₁, ∃ s₂, s₁' = even (s₁ ⋈ s₂)) (λ s₁' s₁ ⟨s₂, h₁⟩, begin rw h₁, constructor, {refl}, {exact ⟨tail s₂, by rw [interleave_eq, even_cons_cons, tail_cons]⟩} end) (exists.intro s₂ rfl) theorem interleave_even_odd (s₁ : stream α) : even s₁ ⋈ odd s₁ = s₁ := eq_of_bisim (λ s' s, s' = even s ⋈ odd s) (λ s' s (h : s' = even s ⋈ odd s), begin rw h, constructor, {refl}, {simp [odd_eq, odd_eq, tail_interleave, tail_even]} end) rfl theorem nth_even : ∀ (n : nat) (s : stream α), nth n (even s) = nth (2*n) s | 0 s := rfl | (succ n) s := begin change nth (succ n) (even s) = nth (succ (succ (2 * n))) s, rw [nth_succ, nth_succ, tail_even, nth_even], refl end theorem nth_odd : ∀ (n : nat) (s : stream α), nth n (odd s) = nth (2*n + 1) s := λ n s, begin rw [odd_eq, nth_even], refl end theorem mem_of_mem_even (a : α) (s : stream α) : a ∈ even s → a ∈ s := assume ⟨n, h⟩, exists.intro (2*n) (by rw [h, nth_even]) theorem mem_of_mem_odd (a : α) (s : stream α) : a ∈ odd s → a ∈ s := assume ⟨n, h⟩, exists.intro (2*n+1) (by rw [h, nth_odd]) def append_stream : list α → stream α → stream α | [] s := s | (list.cons a l) s := a :: append_stream l s theorem nil_append_stream (s : stream α) : append_stream [] s = s := rfl theorem cons_append_stream (a : α) (l : list α) (s : stream α) : append_stream (a::l) s = a :: append_stream l s := rfl infix `++ₛ`:65 := append_stream theorem append_append_stream : ∀ (l₁ l₂ : list α) (s : stream α), (l₁ ++ l₂) ++ₛ s = l₁ ++ₛ (l₂ ++ₛ s) | [] l₂ s := rfl | (list.cons a l₁) l₂ s := by rw [list.cons_append, cons_append_stream, cons_append_stream, append_append_stream] theorem map_append_stream (f : α → β) : ∀ (l : list α) (s : stream α), map f (l ++ₛ s) = list.map f l ++ₛ map f s | [] s := rfl | (list.cons a l) s := by rw [cons_append_stream, list.map_cons, map_cons, cons_append_stream, map_append_stream] theorem drop_append_stream : ∀ (l : list α) (s : stream α), drop l.length (l ++ₛ s) = s | [] s := by refl | (list.cons a l) s := by rw [list.length_cons, add_one, drop_succ, cons_append_stream, tail_cons, drop_append_stream] theorem append_stream_head_tail (s : stream α) : [head s] ++ₛ tail s = s := by rw [cons_append_stream, nil_append_stream, stream.eta] theorem mem_append_stream_right : ∀ {a : α} (l : list α) {s : stream α}, a ∈ s → a ∈ l ++ₛ s | a [] s h := h | a (list.cons b l) s h := have ih : a ∈ l ++ₛ s, from mem_append_stream_right l h, mem_cons_of_mem _ ih theorem mem_append_stream_left : ∀ {a : α} {l : list α} (s : stream α), a ∈ l → a ∈ l ++ₛ s | a [] s h := absurd h (list.not_mem_nil _) | a (list.cons b l) s h := or.elim (list.eq_or_mem_of_mem_cons h) (λ (aeqb : a = b), exists.intro 0 aeqb) (λ (ainl : a ∈ l), mem_cons_of_mem b (mem_append_stream_left s ainl)) def approx : nat → stream α → list α | 0 s := [] | (n+1) s := list.cons (head s) (approx n (tail s)) theorem approx_zero (s : stream α) : approx 0 s = [] := rfl theorem approx_succ (n : nat) (s : stream α) : approx (succ n) s = head s :: approx n (tail s) := rfl theorem nth_approx : ∀ (n : nat) (s : stream α), list.nth (approx (succ n) s) n = some (nth n s) | 0 s := rfl | (n+1) s := begin rw [approx_succ, add_one, list.nth, nth_approx], refl end theorem append_approx_drop : ∀ (n : nat) (s : stream α), append_stream (approx n s) (drop n s) = s := begin intro n, induction n with n' ih, { intro s, refl }, { intro s, rw [approx_succ, drop_succ, cons_append_stream, ih (tail s), stream.eta] } end -- Take theorem reduces a proof of equality of infinite streams to an -- induction over all their finite approximations. theorem take_theorem (s₁ s₂ : stream α) : (∀ (n : nat), approx n s₁ = approx n s₂) → s₁ = s₂ := begin intro h, apply stream.ext, intro n, induction n with n ih, { have aux := h 1, simp [approx] at aux, exact aux }, { have h₁ : some (nth (succ n) s₁) = some (nth (succ n) s₂), { rw [← nth_approx, ← nth_approx, h (succ (succ n))] }, injection h₁ } end -- auxiliary def for cycle corecursive def private def cycle_f : α × list α × α × list α → α | (v, _, _, _) := v -- auxiliary def for cycle corecursive def private def cycle_g : α × list α × α × list α → α × list α × α × list α | (v₁, [], v₀, l₀) := (v₀, l₀, v₀, l₀) | (v₁, list.cons v₂ l₂, v₀, l₀) := (v₂, l₂, v₀, l₀) private lemma cycle_g_cons (a : α) (a₁ : α) (l₁ : list α) (a₀ : α) (l₀ : list α) : cycle_g (a, a₁::l₁, a₀, l₀) = (a₁, l₁, a₀, l₀) := rfl def cycle : Π (l : list α), l ≠ [] → stream α | [] h := absurd rfl h | (list.cons a l) h := corec cycle_f cycle_g (a, l, a, l) theorem cycle_eq : ∀ (l : list α) (h : l ≠ []), cycle l h = l ++ₛ cycle l h | [] h := absurd rfl h | (list.cons a l) h := have gen : ∀ l' a', corec cycle_f cycle_g (a', l', a, l) = (a' :: l') ++ₛ corec cycle_f cycle_g (a, l, a, l), begin intro l', induction l' with a₁ l₁ ih, {intros, rw [corec_eq], refl}, {intros, rw [corec_eq, cycle_g_cons, ih a₁], refl} end, gen l a theorem mem_cycle {a : α} {l : list α} : ∀ (h : l ≠ []), a ∈ l → a ∈ cycle l h := assume h ainl, begin rw [cycle_eq], exact mem_append_stream_left _ ainl end theorem cycle_singleton (a : α) (h : [a] ≠ []) : cycle [a] h = const a := coinduction rfl (λ β fr ch, by rwa [cycle_eq, const_eq]) def tails (s : stream α) : stream (stream α) := corec id tail (tail s) theorem tails_eq (s : stream α) : tails s = tail s :: tails (tail s) := by unfold tails; rw [corec_eq]; refl theorem nth_tails : ∀ (n : nat) (s : stream α), nth n (tails s) = drop n (tail s) := begin intro n, induction n with n' ih, { intros, refl }, { intro s, rw [nth_succ, drop_succ, tails_eq, tail_cons, ih] } end theorem tails_eq_iterate (s : stream α) : tails s = iterate tail (tail s) := rfl def inits_core (l : list α) (s : stream α) : stream (list α) := corec_on (l, s) (λ ⟨a, b⟩, a) (λ p, match p with (l', s') := (l' ++ [head s'], tail s') end) def inits (s : stream α) : stream (list α) := inits_core [head s] (tail s) theorem inits_core_eq (l : list α) (s : stream α) : inits_core l s = l :: inits_core (l ++ [head s]) (tail s) := begin unfold inits_core corec_on, rw [corec_eq], refl end theorem tail_inits (s : stream α) : tail (inits s) = inits_core [head s, head (tail s)] (tail (tail s)) := begin unfold inits, rw inits_core_eq, refl end theorem inits_tail (s : stream α) : inits (tail s) = inits_core [head (tail s)] (tail (tail s)) := rfl theorem cons_nth_inits_core : ∀ (a : α) (n : nat) (l : list α) (s : stream α), a :: nth n (inits_core l s) = nth n (inits_core (a::l) s) := begin intros a n, induction n with n' ih, { intros, refl }, { intros l s, rw [nth_succ, inits_core_eq, tail_cons, ih, inits_core_eq (a::l) s], refl } end theorem nth_inits : ∀ (n : nat) (s : stream α), nth n (inits s) = approx (succ n) s := begin intro n, induction n with n' ih, { intros, refl }, { intros, rw [nth_succ, approx_succ, ← ih, tail_inits, inits_tail, cons_nth_inits_core] } end theorem inits_eq (s : stream α) : inits s = [head s] :: map (list.cons (head s)) (inits (tail s)) := begin apply stream.ext, intro n, cases n, { refl }, { rw [nth_inits, nth_succ, tail_cons, nth_map, nth_inits], refl } end theorem zip_inits_tails (s : stream α) : zip append_stream (inits s) (tails s) = const s := begin apply stream.ext, intro n, rw [nth_zip, nth_inits, nth_tails, nth_const, approx_succ, cons_append_stream, append_approx_drop, stream.eta] end def pure (a : α) : stream α := const a def apply (f : stream (α → β)) (s : stream α) : stream β := λ n, (nth n f) (nth n s) infix `⊛`:75 := apply -- input as \o* theorem identity (s : stream α) : pure id ⊛ s = s := rfl theorem composition (g : stream (β → δ)) (f : stream (α → β)) (s : stream α) : pure comp ⊛ g ⊛ f ⊛ s = g ⊛ (f ⊛ s) := rfl theorem homomorphism (f : α → β) (a : α) : pure f ⊛ pure a = pure (f a) := rfl theorem interchange (fs : stream (α → β)) (a : α) : fs ⊛ pure a = pure (λ f : α → β, f a) ⊛ fs := rfl theorem map_eq_apply (f : α → β) (s : stream α) : map f s = pure f ⊛ s := rfl def nats : stream nat := λ n, n theorem nth_nats (n : nat) : nth n nats = n := rfl theorem nats_eq : nats = 0 :: map succ nats := begin apply stream.ext, intro n, cases n, refl, rw [nth_succ], refl end end stream
9ee5f1b8c9884fe0699ce2ba7f2ac60dfa762d82
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/src/Init/Data/HashSet.lean
ff9e65d498303540a8051b2a58f53bdf96c0f421
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
6,459
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import Init.Data.Array.Basic import Init.Data.List.Control import Init.Data.Option.Basic import Init.Data.Hashable universes u v w def HashSetBucket (α : Type u) := { b : Array (List α) // b.size > 0 } def HashSetBucket.update {α : Type u} (data : HashSetBucket α) (i : USize) (d : List α) (h : i.toNat < data.val.size) : HashSetBucket α := ⟨ data.val.uset i d h, transRelRight Greater (Array.szFSetEq (data.val) ⟨USize.toNat i, h⟩ d) data.property ⟩ structure HashSetImp (α : Type u) := (size : Nat) (buckets : HashSetBucket α) def mkHashSetImp {α : Type u} (nbuckets := 8) : HashSetImp α := let n := if nbuckets = 0 then 8 else nbuckets; { size := 0, buckets := ⟨ mkArray n [], have p₁ : (mkArray n ([] : List α)).size = n from Array.szMkArrayEq _ _; have p₂ : n = (if nbuckets = 0 then 8 else nbuckets) from rfl; have p₃ : (if nbuckets = 0 then 8 else nbuckets) > 0 from match nbuckets with | 0 => Nat.zeroLtSucc _ | (Nat.succ x) => Nat.zeroLtSucc _; transRelRight Greater (Eq.trans p₁ p₂) p₃ ⟩ } namespace HashSetImp variables {α : Type u} def mkIdx {n : Nat} (h : n > 0) (u : USize) : { u : USize // u.toNat < n } := ⟨u %ₙ n, USize.modnLt _ h⟩ @[inline] def reinsertAux (hashFn : α → USize) (data : HashSetBucket α) (a : α) : HashSetBucket α := let ⟨i, h⟩ := mkIdx data.property (hashFn a); data.update i (a :: data.val.uget i h) h @[inline] def foldBucketsM {δ : Type w} {m : Type w → Type w} [Monad m] (data : HashSetBucket α) (d : δ) (f : δ → α → m δ) : m δ := data.val.foldlM (fun d as => as.foldlM f d) d @[inline] def foldBuckets {δ : Type w} (data : HashSetBucket α) (d : δ) (f : δ → α → δ) : δ := Id.run $ foldBucketsM data d f @[inline] def foldM {δ : Type w} {m : Type w → Type w} [Monad m] (f : δ → α → m δ) (d : δ) (h : HashSetImp α) : m δ := foldBucketsM h.buckets d f @[inline] def fold {δ : Type w} (f : δ → α → δ) (d : δ) (m : HashSetImp α) : δ := foldBuckets m.buckets d f def find? [HasBeq α] [Hashable α] (m : HashSetImp α) (a : α) : Option α := match m with | ⟨_, buckets⟩ => let ⟨i, h⟩ := mkIdx buckets.property (hash a); (buckets.val.uget i h).find? (fun a' => a == a') def contains [HasBeq α] [Hashable α] (m : HashSetImp α) (a : α) : Bool := match m with | ⟨_, buckets⟩ => let ⟨i, h⟩ := mkIdx buckets.property (hash a); (buckets.val.uget i h).contains a -- TODO: remove `partial` by using well-founded recursion partial def moveEntries [Hashable α] : Nat → Array (List α) → HashSetBucket α → HashSetBucket α | i, source, target => if h : i < source.size then let idx : Fin source.size := ⟨i, h⟩; let es : List α := source.get idx; -- We remove `es` from `source` to make sure we can reuse its memory cells when performing es.foldl let source := source.set idx []; let target := es.foldl (reinsertAux hash) target; moveEntries (i+1) source target else target def expand [Hashable α] (size : Nat) (buckets : HashSetBucket α) : HashSetImp α := let nbuckets := buckets.val.size * 2; have aux₁ : nbuckets > 0 from Nat.mulPos buckets.property (Nat.zeroLtBit0 Nat.oneNeZero); have aux₂ : (mkArray nbuckets ([] : List α)).size = nbuckets from Array.szMkArrayEq _ _; let new_buckets : HashSetBucket α := ⟨mkArray nbuckets [], aux₂.symm ▸ aux₁⟩; { size := size, buckets := moveEntries 0 buckets.val new_buckets } def insert [HasBeq α] [Hashable α] (m : HashSetImp α) (a : α) : HashSetImp α := match m with | ⟨size, buckets⟩ => let ⟨i, h⟩ := mkIdx buckets.property (hash a); let bkt := buckets.val.uget i h; if bkt.contains a then ⟨size, buckets.update i (bkt.replace a a) h⟩ else let size' := size + 1; let buckets' := buckets.update i (a :: bkt) h; if size' ≤ buckets.val.size then { size := size', buckets := buckets' } else expand size' buckets' def erase [HasBeq α] [Hashable α] (m : HashSetImp α) (a : α) : HashSetImp α := match m with | ⟨ size, buckets ⟩ => let ⟨i, h⟩ := mkIdx buckets.property (hash a); let bkt := buckets.val.uget i h; if bkt.contains a then ⟨size - 1, buckets.update i (bkt.erase a) h⟩ else m inductive WellFormed [HasBeq α] [Hashable α] : HashSetImp α → Prop | mkWff : ∀ n, WellFormed (mkHashSetImp n) | insertWff : ∀ m a, WellFormed m → WellFormed (insert m a) | eraseWff : ∀ m a, WellFormed m → WellFormed (erase m a) end HashSetImp def HashSet (α : Type u) [HasBeq α] [Hashable α] := { m : HashSetImp α // m.WellFormed } open HashSetImp def mkHashSet {α : Type u} [HasBeq α] [Hashable α] (nbuckets := 8) : HashSet α := ⟨ mkHashSetImp nbuckets, WellFormed.mkWff nbuckets ⟩ namespace HashSet variables {α : Type u} [HasBeq α] [Hashable α] instance : Inhabited (HashSet α) := ⟨mkHashSet⟩ instance : HasEmptyc (HashSet α) := ⟨mkHashSet⟩ @[inline] def insert (m : HashSet α) (a : α) : HashSet α := match m with | ⟨ m, hw ⟩ => ⟨ m.insert a, WellFormed.insertWff m a hw ⟩ @[inline] def erase (m : HashSet α) (a : α) : HashSet α := match m with | ⟨ m, hw ⟩ => ⟨ m.erase a, WellFormed.eraseWff m a hw ⟩ @[inline] def find? (m : HashSet α) (a : α) : Option α := match m with | ⟨ m, _ ⟩ => m.find? a @[inline] def contains (m : HashSet α) (a : α) : Bool := match m with | ⟨ m, _ ⟩ => m.contains a @[inline] def foldM {δ : Type w} {m : Type w → Type w} [Monad m] (f : δ → α → m δ) (d : δ) (h : HashSet α) : m δ := match h with | ⟨ h, _ ⟩ => h.foldM f d @[inline] def fold {δ : Type w} (f : δ → α → δ) (d : δ) (m : HashSet α) : δ := match m with | ⟨ m, _ ⟩ => m.fold f d @[inline] def size (m : HashSet α) : Nat := match m with | ⟨ {size := sz, ..}, _ ⟩ => sz @[inline] def isEmpty (m : HashSet α) : Bool := m.size = 0 @[inline] def empty : HashSet α := mkHashSet def toList (m : HashSet α) : List α := m.fold (fun r a => a::r) [] def toArray (m : HashSet α) : Array α := m.fold (fun r a => r.push a) #[] def numBuckets (m : HashSet α) : Nat := m.val.buckets.val.size end HashSet
226e9cc68a7dcffe9397104f3c7756d194f28be3
1d265c7dd8cb3d0e1d645a19fd6157a2084c3921
/src/other/int_vector3d_cross_full.lean
28e8b90b677539372d3b8204eec31958c3994e4d
[ "MIT" ]
permissive
hanzhi713/lean-proofs
de432372f220d302be09b5ca4227f8986567e4fd
4d8356a878645b9ba7cb036f87737f3f1e68ede5
refs/heads/master
1,585,580,245,658
1,553,646,623,000
1,553,646,623,000
151,342,188
0
1
null
null
null
null
UTF-8
Lean
false
false
7,194
lean
-- theorem add_assoc' (a b c : ℤ) : a+b+c = a+(b+c) := add_assoc a b c -- theorem add_comm' (a b : ℤ) : a + b = b + a := add_comm a b -- theorem mul_assoc' (a b c : ℤ) : a*b*c = a*(b*c) := mul_assoc a b c -- theorem mul_comm' (a b:ℤ) : a*b=b*a := mul_comm a b -- theorem add_mul' (a b c : ℤ) : (a+b)*c = a*c+b*c := add_mul a b c -- theorem zero_add' (a:ℤ) : 0 + a = a := zero_add a -- theorem sub_eq_add_neg' (a b : ℤ) : a - b = a + -b := sub_eq_add_neg a b -- theorem sub_neg_eq_add' (a b :ℤ) : a - -b = a + b := sub_neg_eq_add a b -- theorem sub_self' (a: ℤ) : a - a = 0 := sub_self a -- theorem neg_eq_neg_one_mul' (a:ℤ): -a = -1 * a := neg_eq_neg_one_mul a -- this is a proof that ∀ vectors a, b ∈ ℤ³, (a × b) ⬝ a = 0 axiom add_assoc' : ∀ a b c : ℤ, a + b + c = a + (b + c) axiom add_comm' : ∀ a b : ℤ, a + b = b + a axiom zero_add' : ∀ a : ℤ, 0 + a = a axiom sub_self' : ∀ a : ℤ, a - a = 0 axiom sub_eq_add_neg': ∀ a b : ℤ, a - b = a + -b axiom sub_neg_eq_add': ∀ a b : ℤ, a - -b = a + b axiom mul_assoc' : ∀ a b c: ℤ, a * b *c = a * (b * c) axiom mul_comm' : ∀ a b : ℤ, a * b = b * a axiom add_mul' : ∀ a b c : ℤ, (a + b) * c = a * c + b * c axiom neg_eq_neg_one_mul' : ∀ a : ℤ, -a = -1 * a theorem zero_sub' (a : ℤ) : 0 - a = -a := calc 0 - a = 0 + -a : by rw sub_eq_add_neg' ... = -a : by rw zero_add' theorem neg_mul_eq_mul_neg' (a b : ℤ) : -(a * b) = a * -b := calc -(a * b) = -1 * (a * b) : by rw neg_eq_neg_one_mul' ... = -1 * a * b : by rw mul_assoc' ... = a * -1 * b : by rw mul_comm' a ... = a * (-1 * b) : by rw mul_assoc' ... = a * -b : by rw neg_eq_neg_one_mul' b theorem neg_mul_eq_neg_mul_symm' (a b : ℤ) : -a * b = -(a * b) := calc -a * b = -1 * a * b : by rw neg_eq_neg_one_mul' ... = -1 * (a * b) : by rw mul_assoc' ... = -(a * b) : by rw neg_eq_neg_one_mul' (a * b) theorem times_one : ∀ {a : ℤ}, a = 1 * a := assume a, calc a = 0 + a : by rw zero_add' ... = 0 - -a : by rw sub_neg_eq_add' ... = 0 - -1 * a : by rw neg_eq_neg_one_mul' ... = 0 - -(1 * a) : by rw neg_mul_eq_neg_mul_symm' ... = 0 + 1 * a : by rw sub_neg_eq_add' ... = 1 * a : by rw zero_add' theorem add_sub_assoc' {a b c : ℤ} : a + b - c = a + (b - c) := calc a + b - c = a + b + -c : by rw sub_eq_add_neg' ... = a + (b + -c) : by rw add_assoc' ... = a + (b - c) : by rw sub_eq_add_neg' theorem sub_add_eq_sub_sub' {a b c : ℤ} : a - (b + c) = a - b - c := calc a - (b + c) = a + -(b + c) : by rw sub_eq_add_neg' ... = a + (-1)* (b + c) : by rw neg_eq_neg_one_mul' ... = a + (b + c) * -1 : by rw mul_comm' ... = a + (b * -1 + c * -1) : by rw add_mul' ... = a + b * -1 + c * -1 : by rw add_assoc' ... = a + -1*b + -1*c : by rw [mul_comm' b, mul_comm' c] ... = (a + -b) + -c : by rw [neg_eq_neg_one_mul' b, neg_eq_neg_one_mul' c] ... = a - b + -c : by rw sub_eq_add_neg' ... = a - b - c : by rw sub_eq_add_neg' (a-b) theorem neg_mul_comm' (a b: ℤ) : -a * b = a * -b := calc -a * b = -(a * b) : by rw neg_mul_eq_neg_mul_symm' ... = a * -b : by rw neg_mul_eq_mul_neg' theorem sub_mul' (a b c: ℤ) : (a - b) * c = a * c - b * c := calc (a - b) * c = (a + (-b)) * c : by rw sub_eq_add_neg' ... = a * c + -b * c : by rw add_mul' ... = a * c + b * -c : by rw neg_mul_comm' ... = a * c + - (b * c) : by rw neg_mul_eq_mul_neg' ... = a * c - b * c : by rw sub_eq_add_neg' theorem sub_add_symm' {a b c : ℤ} : a - (b - c) = a - b + c := calc a - (b - c) = a + -(b - c) : by rw sub_eq_add_neg' ... = a + -1* (b - c) : by rw neg_eq_neg_one_mul' ... = a + (b - c) * -1 : by rw mul_comm' ... = a + (b*-1 - c*-1) : by rw sub_mul' ... = a + (-1*b - -1*c) : by rw [mul_comm' b, mul_comm' c] ... = a + -1*b - -1*c : by rw add_sub_assoc' ... = a + -b - -c : by rw [neg_eq_neg_one_mul' b, neg_eq_neg_one_mul' c] ... = a - b - -c : by rw sub_eq_add_neg' a ... = a - b + c : by rw sub_neg_eq_add' theorem sub_add' {a b c : ℤ} : a - b + c = a - (b - c):= begin apply eq.symm, exact sub_add_symm' end theorem mul_right_comm' {a b c : ℤ} : a * b * c = a * c * b := calc a * b * c = a * (b * c): by rw mul_assoc' ... = a * (c * b) : by rw mul_comm' b ... = a * c * b : by rw mul_assoc' theorem add_right_comm' {a b c : ℤ} : a + b + c = a + c + b := calc a + b + c = a + (b + c) : by rw add_assoc' ... = a + (c + b) : by rw add_comm' c ... = a + c + b : by rw add_assoc' def dot: ℤ × ℤ × ℤ → ℤ × ℤ × ℤ → ℤ := λ ⟨a, b, c⟩ ⟨d, e, f⟩, a*d + b*e + c*f def cross: ℤ × ℤ × ℤ → ℤ × ℤ × ℤ → ℤ × ℤ × ℤ := λ ⟨a, b, c⟩ ⟨d, e, f⟩, ⟨b*f - c*e, c*d - a*f, a*e - b*d⟩ variables m n p j k l : ℤ #eval cross (124, 1294, 123) (156, 949, 29238499) #reduce dot (cross (8, 1, 5) (2, 8, 9)) (2, 8, 9) #reduce dot (cross (m, n, p) (j, k, l)) (j, k, l) theorem cross' (a b c d e f: ℤ) : cross (a, b, c) (d, e, f) = (b*f - c*e, c*d - a*f, a*e - b*d) := rfl theorem dot' (a b c d e f: ℤ) : dot (a, b, c) (d, e, f) = a*d + b*e + c*f := rfl theorem add_sub_swap1' (a b c d: ℤ): a - b + c - d = a - d - b + c := calc a - b + c - d = a - b + c + -d : by rw sub_eq_add_neg' ... = a - b + (c + -d) : by rw add_assoc' ... = a - b + (-d + c) : by rw add_comm' c ... = a - b + -d + c : by rw add_assoc' ... = a - (b - -d) + c : by rw sub_add' ... = a - (b + d) + c : by rw sub_neg_eq_add' ... = a - (d + b) + c : by rw add_comm' b ... = a - d - b + c : by rw sub_add_eq_sub_sub' theorem add_sub_swap2' (a b c d: ℤ) : -a + b + (c - d) = c - a + (b - d) := calc -a + b + (c - d) = -a + b + c - d : by rw add_sub_assoc' ... = -a + c + b - d : by rw add_right_comm' ... = c + -a + b - d : by rw add_comm' c ... = c - a + b - d : by rw sub_eq_add_neg' c ... = c - a + (b - d) : by rw add_sub_assoc' theorem mul_swap' (a b c: ℤ) : a * b * c = c * b *a := calc a * b * c = a * c * b : by rw mul_right_comm' ... = a * (c * b) : by rw mul_assoc' ... = (c * b) * a : by rw mul_comm' theorem proof (a b c d e f: ℤ) : dot (cross (a, b, c) (d, e, f)) (a, b, c) = 0 := calc dot (cross (a, b, c) (d, e, f)) (a, b, c) = dot (b*f - c*e, c*d - a*f, a*e - b*d) (a, b, c) : by rw cross' ... = (b*f - c*e)*a + (c*d - a*f)*b + (a*e - b*d)*c : by rw dot' ... = b*f*a - c*e*a + (c*d*b - a*f*b) + (a*e*c - b*d*c) : by rw [sub_mul', sub_mul', sub_mul'] ... = b*f*a - c*e*a + c*d*b - a*f*b + (a*e*c - b*d*c) : by rw add_sub_assoc' ... = b*f*a - a*f*b - c*e*a + c*d*b + (a*e*c - b*d*c) : by rw add_sub_swap1' ... = a*f*b - a*f*b - c*e*a + c*d*b + (a*e*c - b*d*c) : by rw mul_swap' ... = 0 - c*e*a + c*d*b + (a*e*c - b*d*c) : by rw sub_self' ... = -(c*e*a) + c*d*b + (a*e*c - b*d*c) : by rw zero_sub' ... = a*e*c - c*e*a + (c*d*b - b*d*c) : by rw add_sub_swap2' ... = c*e*a - c*e*a + (c*d*b - b*d*c) : by rw mul_swap' ... = 0 + (c*d*b - b*d*c) : by rw sub_self' ... = (c*d*b - b*d*c) : by rw zero_add' ... = b*d*c - b*d*c : by rw mul_swap' ... = 0 : by rw sub_self'
bed890a54bf626c4a1f06c2cb384c1914a6b6f55
947b78d97130d56365ae2ec264df196ce769371a
/src/Lean/Elab/PreDefinition/MkInhabitant.lean
70fcd3aa706a16d81927d88160457d5c769e1654
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,607
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.AppBuilder namespace Lean namespace Elab open Meta private def mkInhabitant? (type : Expr) : MetaM (Option Expr) := catch (do inh ← mkAppM `arbitrary #[type]; pure inh) (fun _ => pure none) private def findAssumption? (xs : Array Expr) (type : Expr) : MetaM (Option Expr) := do xs.findM? fun x => do { xType ← inferType x; isDefEq xType type } private def mkFnInhabitantAux? (xs : Array Expr) : Nat → Expr → MetaM (Option Expr) | 0, type => mkInhabitant? type | i+1, type => do let x := xs.get! i; type ← mkForallFVars #[x] type; val? ← mkInhabitant? type; match val? with | none => mkFnInhabitantAux? i type | some val => do val ← mkLambdaFVars (xs.extract 0 i) val; pure $ some val private def mkFnInhabitant? (xs : Array Expr) (type : Expr) : MetaM (Option Expr) := mkFnInhabitantAux? xs xs.size type /- TODO: add a global IO.Ref to let users customize/extend this procedure -/ def mkInhabitantFor (declName : Name) (xs : Array Expr) (type : Expr) : MetaM Expr := do val? ← mkInhabitant? type; match val? with | some val => mkLambdaFVars xs val | none => do x? ← findAssumption? xs type; match x? with | some x => mkLambdaFVars xs x | none => do val? ← mkFnInhabitant? xs type; match x? with | some val => pure val | none => throwError ("failed to compile partial definition '" ++ declName ++ "', failed to show that type is inhabited") end Elab end Lean
22904cfa241077ebf6b4285fed8ba4d264691819
8f209eb34c0c4b9b6be5e518ebfc767a38bed79c
/code/src/internal/Ant/implies.lean
8dc11c3855a96dd56d0c0eeccbcd8a3e0efdd2ab
[]
no_license
hediet/masters-thesis
13e3bcacb6227f25f7ec4691fb78cb0363f2dfb5
dc40c14cc4ed073673615412f36b4e386ee7aac9
refs/heads/master
1,680,591,056,302
1,617,710,887,000
1,617,710,887,000
311,762,038
4
0
null
null
null
null
UTF-8
Lean
false
false
890
lean
import tactic import data.finset import ..internal_definitions import .rhss import .map variable [GuardModule] open GuardModule @[trans] lemma Ant.implies_trans (a b c : Ant bool) (h1: a ⟶ b) (h2: b ⟶ c): a ⟶ c := begin induction h1 generalizing c; cases h2, { refine Ant.implies.rhs _; tauto, }, { refine Ant.implies.branch _ _; tauto, }, { refine Ant.implies.diverge _ _; tauto, }, end @[refl] lemma Ant.implies_refl (a : Ant bool) : a ⟶ a := by induction a; simp [Ant.implies.rhs, Ant.implies.branch, Ant.implies.diverge, *] lemma Ant.implies_equal_structure { a b: Ant bool } (h: a ⟶ b): a.map (λ x, false) = b.map (λ x, false) := by induction h; simp [Ant.map, *] lemma Ant.implies_same_rhss { a b: Ant bool } (h: a ⟶ b): a.rhss = b.rhss := begin have := congr_arg Ant.rhss (Ant.implies_equal_structure h), finish [Ant.map_rhss], end
339cb00189c0d348d93e762c137bf537756348fd
4d3f29a7b2eff44af8fd0d3176232e039acb9ee3
/LAMR/Examples/using_lean/examples4.lean
71b6ece15b948000539275605554a724203e4176
[]
no_license
marijnheule/lamr
5fc5d69d326ff92e321242cfd7f72e78d7f99d7e
28cc4114c7361059bb54f407fa312bf38b48728b
refs/heads/main
1,689,338,013,620
1,630,359,632,000
1,630,359,632,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,831
lean
-- textbook: List import Init open List variable {α : Type} variable (as bs cs : List α) variable (a b c : α) #check a :: as #check as ++ bs example : [] ++ as = as := nil_append as example : (a :: as) ++ bs = a :: (as ++ bs) := cons_append a as bs -- end textbook: List -- textbook: append_nil' theorem append_nil' : as ++ [] = as := by induction as with | nil => rw [nil_append] | cons a as ih => rw [cons_append, ih] -- end textbook: append_nil' -- textbook: append_assoc' theorem append_assoc' : as ++ bs ++ cs = as ++ (bs ++ cs) := by induction as with | nil => rw [nil_append, nil_append] | cons a as ih => rw [cons_append, cons_append, ih, ←cons_append] -- end textbook: append_assoc' -- textbook: reverse theorem reverse_def : reverse as = reverseAux as [] := rfl theorem reverseAux_nil : reverseAux [] as = as := rfl theorem reverseAux_cons : reverseAux (a :: as) bs = reverseAux as (a :: bs) := rfl -- end textbook: reverse theorem reverse_nil : reverse ([] : List α) = [] := rfl -- textbook: reverse identities theorem reverseAux_append : reverseAux (as ++ bs) cs = reverseAux bs (reverseAux as cs) := by induction as generalizing cs with | nil => rw [nil_append, reverseAux_nil] | cons a as ih => rw [cons_append, reverseAux_cons, reverseAux_cons, ih] theorem reverseAux_append' : reverseAux as (bs ++ cs) = reverseAux as bs ++ cs := by induction as generalizing bs with | nil => rw [reverseAux_nil, reverseAux_nil] | cons a as ih => rw [reverseAux_cons, reverseAux_cons, ←cons_append, ih] -- end textbook: reverse identities -- textbook: reverse_append theorem reverse_append : reverse (as ++ bs) = reverse bs ++ reverse as := by rw [reverse_def, reverseAux_append, reverse_def, ←reverseAux_append', nil_append, reverse_def] -- end textbook: reverse_append
5c415ef8bf1fd4d39a604cbcbbda6c8e54dc35f8
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/2073.lean
2ee5893bcf01c754c9468556d950baca0be2cd71
[ "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
107
lean
def Commute (a b : Nat) := a * b = b * a example : Commute m n := calc m * n = n * m := Nat.mul_comm ..
9e673c48e29a27cd08bcea3f0924c45bba8dad40
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/simp17.lean
905907de54be5c5b0ce87c95a09356188ffa53c8
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
351
lean
rewrite_set simple add_rewrite and_truer and_truel and_falser and_falsel or_falsel Nat::add_zeror a_neq_a : simple (* add_congr_theorem("simple", "and_congrr") *) variables a b c : Nat (* local t = parse_lean([[c + 0 ≠ b + 1 ∧ b = 0 ∧ c = 1]]) local s, pr = simplify(t, "simple") print(s) print(pr) print(get_environment():type_check(pr)) *)
c03e8238b5391f14aca788841dd4a175a00fad1e
cf39355caa609c0f33405126beee2739aa3cb77e
/library/init/control/state.lean
ca00bbb040c29cb36306e1a1c1c229157fc26959
[ "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
7,811
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich The state monad transformer. -/ prelude import init.control.alternative init.control.lift import init.control.id init.control.except universes u v w structure state_t (σ : Type u) (m : Type u → Type v) (α : Type u) : Type (max u v) := (run : σ → m (α × σ)) attribute [pp_using_anonymous_constructor] state_t @[reducible] def state (σ α : Type u) : Type u := state_t σ id α namespace state_t section variables {σ : Type u} {m : Type u → Type v} variable [monad m] variables {α β : Type u} @[inline] protected def pure (a : α) : state_t σ m α := ⟨λ s, pure (a, s)⟩ @[inline] protected def bind (x : state_t σ m α) (f : α → state_t σ m β) : state_t σ m β := ⟨λ s, do (a, s') ← x.run s, (f a).run s'⟩ instance : monad (state_t σ m) := { pure := @state_t.pure _ _ _, bind := @state_t.bind _ _ _ } protected def orelse [alternative m] {α : Type u} (x₁ x₂ : state_t σ m α) : state_t σ m α := ⟨λ s, x₁.run s <|> x₂.run s⟩ protected def failure [alternative m] {α : Type u} : state_t σ m α := ⟨λ s, failure⟩ instance [alternative m] : alternative (state_t σ m) := { failure := @state_t.failure _ _ _ _, orelse := @state_t.orelse _ _ _ _ } @[inline] protected def get : state_t σ m σ := ⟨λ s, pure (s, s)⟩ @[inline] protected def put : σ → state_t σ m punit := λ s', ⟨λ s, pure (punit.star, s')⟩ @[inline] protected def modify (f : σ → σ) : state_t σ m punit := ⟨λ s, pure (punit.star, f s)⟩ @[inline] protected def lift {α : Type u} (t : m α) : state_t σ m α := ⟨λ s, do a ← t, pure (a, s)⟩ instance : has_monad_lift m (state_t σ m) := ⟨@state_t.lift σ m _⟩ @[inline] protected def monad_map {σ m m'} [monad m] [monad m'] {α} (f : Π {α}, m α → m' α) : state_t σ m α → state_t σ m' α := λ x, ⟨λ st, f (x.run st)⟩ instance (σ m m') [monad m] [monad m'] : monad_functor m m' (state_t σ m) (state_t σ m') := ⟨@state_t.monad_map σ m m' _ _⟩ protected def adapt {σ σ' σ'' α : Type u} {m : Type u → Type v} [monad m] (split : σ → σ' × σ'') (join : σ' → σ'' → σ) (x : state_t σ' m α) : state_t σ m α := ⟨λ st, do let (st, ctx) := split st, (a, st') ← x.run st, pure (a, join st' ctx)⟩ instance (ε) [monad_except ε m] : monad_except ε (state_t σ m) := { throw := λ α, state_t.lift ∘ throw, catch := λ α x c, ⟨λ s, catch (x.run s) (λ e, state_t.run (c e) s)⟩ } end end state_t /-- An implementation of [MonadState](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-State-Class.html). In contrast to the Haskell implementation, we use overlapping instances to derive instances automatically from `monad_lift`. Note: This class can be seen as a simplification of the more "principled" definition ``` class monad_state_lift (σ : out_param (Type u)) (n : Type u → Type u) := (lift {α : Type u} : (∀ {m : Type u → Type u} [monad m], state_t σ m α) → n α) ``` which better describes the intent of "we can lift a `state_t` from anywhere in the monad stack". However, by parametricity the types `∀ m [monad m], σ → m (α × σ)` and `σ → α × σ` should be equivalent because the only way to obtain an `m` is through `pure`. -/ class monad_state (σ : out_param (Type u)) (m : Type u → Type v) := (lift {α : Type u} : state σ α → m α) section variables {σ : Type u} {m : Type u → Type v} -- NOTE: The ordering of the following two instances determines that the top-most `state_t` monad layer -- will be picked first @[priority 100] instance monad_state_trans {n : Type u → Type w} [monad_state σ m] [has_monad_lift m n] : monad_state σ n := ⟨λ α x, monad_lift (monad_state.lift x : m α)⟩ instance [monad m] : monad_state σ (state_t σ m) := ⟨λ α x, ⟨λ s, pure (x.run s)⟩⟩ variables [monad m] [monad_state σ m] /-- Obtain the top-most state of a monad stack. -/ @[inline] def get : m σ := monad_state.lift state_t.get /-- Set the top-most state of a monad stack. -/ @[inline] def put (st : σ) : m punit := monad_state.lift (state_t.put st) /-- Map the top-most state of a monad stack. Note: `modify f` may be preferable to `f <$> get >>= put` because the latter does not use the state linearly (without sufficient inlining). -/ @[inline] def modify (f : σ → σ) : m punit := monad_state.lift (state_t.modify f) end /-- Adapt a monad stack, changing the type of its top-most state. This class is comparable to [Control.Lens.Zoom](https://hackage.haskell.org/package/lens-4.15.4/docs/Control-Lens-Zoom.html#t:Zoom), but does not use lenses (yet?), and is derived automatically for any transformer implementing `monad_functor`. For zooming into a part of the state, the `split` function should split σ into the part σ' and the "context" σ'' so that the potentially modified σ' and the context can be rejoined by `join` in the end. In the simplest case, the context can be chosen as the full outer state (ie. `σ'' = σ`), which makes `split` and `join` simpler to define. However, note that the state will not be used linearly in this case. Example: ``` def zoom_fst {α σ σ' : Type} : state σ α → state (σ × σ') α := adapt_state id prod.mk ``` The function can also zoom out into a "larger" state, where the new parts are supplied by `split` and discarded by `join` in the end. The state is therefore not used linearly anymore but merely affinely, which is not a practically relevant distinction in Lean. Example: ``` def with_snd {α σ σ' : Type} (snd : σ') : state (σ × σ') α → state σ α := adapt_state (λ st, ((st, snd), ())) (λ ⟨st,snd⟩ _, st) ``` Note: This class can be seen as a simplification of the more "principled" definition ``` class monad_state_functor (σ σ' : out_param (Type u)) (n n' : Type u → Type u) := (map {α : Type u} : (∀ {m : Type u → Type u} [monad m], state_t σ m α → state_t σ' m α) → n α → n' α) ``` which better describes the intent of "we can map a `state_t` anywhere in the monad stack". If we look at the unfolded type of the first argument `∀ m [monad m], (σ → m (α × σ)) → σ' → m (α × σ')`, we see that it has the lens type `∀ f [functor f], (α → f α) → β → f β` with `f` specialized to `λ σ, m (α × σ)` (exercise: show that this is a lawful functor). We can build all lenses we are insterested in from the functions `split` and `join` as ``` λ f _ st, let (st, ctx) := split st in (λ st', join st' ctx) <$> f st ``` -/ class monad_state_adapter (σ σ' : out_param (Type u)) (m m' : Type u → Type v) := (adapt_state {σ'' α : Type u} (split : σ' → σ × σ'') (join : σ → σ'' → σ') : m α → m' α) export monad_state_adapter (adapt_state) section variables {σ σ' : Type u} {m m' : Type u → Type v} @[priority 100] instance monad_state_adapter_trans {n n' : Type u → Type v} [monad_state_adapter σ σ' m m'] [monad_functor m m' n n'] : monad_state_adapter σ σ' n n' := ⟨λ σ'' α split join, monad_map (λ α, (adapt_state split join : m α → m' α))⟩ instance [monad m] : monad_state_adapter σ σ' (state_t σ m) (state_t σ' m) := ⟨λ σ'' α, state_t.adapt⟩ end instance (σ m out) [monad_run out m] : monad_run (λ α, σ → out (α × σ)) (state_t σ m) := ⟨λ α x, run ∘ (λ σ, x.run σ)⟩
80296a501d8caab6ee14ad54f6b27c297cb06567
246309748072bf9f8da313401699689ebbecd94d
/src/linear_algebra/eigenspace.lean
42d0db932bee9879ecb6e23acbf5db6373dd21b7
[ "Apache-2.0" ]
permissive
YJMD/mathlib
b703a641e5f32a996f7842f7c0043bab2b462ee2
7310eab9fa8c1b1229dca42682f1fa6bfb7dbbf9
refs/heads/master
1,670,714,479,314
1,599,035,445,000
1,599,035,445,000
292,279,930
0
0
null
1,599,050,561,000
1,599,050,560,000
null
UTF-8
Lean
false
false
11,561
lean
/- Copyright (c) 2020 Alexander Bentkamp. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Alexander Bentkamp. -/ import field_theory.algebraic_closure import linear_algebra.finsupp /-! # Eigenvectors and eigenvalues This file defines eigenspaces and eigenvalues. An eigenspace of a linear map `f` for a scalar `μ` is the kernel of the map `(f - μ • id)`. The nonzero elements of an eigenspace are eigenvectors `x`. They have the property `f x = μ • x`. If there are eigenvectors for a scalar `μ`, the scalar `μ` is called an eigenvalue. There is no consensus in the literature whether `0` is an eigenvector. Our definition of `eigenvector` permits only nonzero vectors. For an eigenvector `x` that may also be `0`, we write `x ∈ eigenspace f μ`. ## Notations The expression `algebra_map K (End K V)` appears very often, which is why we use `am` as a local notation for it. ## References * [Sheldon Axler, *Down with determinants!*, https://www.maa.org/sites/default/files/pdf/awards/Axler-Ford-1996.pdf][axler1996] * https://en.wikipedia.org/wiki/Eigenvalues_and_eigenvectors ## Tags eigenspace, eigenvector, eigenvalue, eigen -/ universes u v w namespace module namespace End open vector_space principal_ideal_ring polynomial finite_dimensional variables {K : Type v} {V : Type w} [add_comm_group V] local notation `am` := algebra_map K (End K V) /-- The submodule `eigenspace f μ` for a linear map `f` and a scalar `μ` consists of all vectors `x` such that `f x = μ • x`. -/ def eigenspace [comm_ring K] [module K V] (f : End K V) (μ : K) : submodule K V := (f - am μ).ker /-- A nonzero element of an eigenspace is an eigenvector. -/ def has_eigenvector [comm_ring K] [module K V] (f : End K V) (μ : K) (x : V) : Prop := x ≠ 0 ∧ x ∈ eigenspace f μ /-- A scalar `μ` is an eigenvalue for a linear map `f` if there are nonzero vectors `x` such that `f x = μ • x`. -/ def has_eigenvalue [comm_ring K] [module K V] (f : End K V) (a : K) : Prop := eigenspace f a ≠ ⊥ lemma mem_eigenspace_iff [comm_ring K] [module K V] {f : End K V} {μ : K} {x : V} : x ∈ eigenspace f μ ↔ f x = μ • x := by rw [eigenspace, linear_map.mem_ker, linear_map.sub_apply, algebra_map_End_apply, sub_eq_zero] lemma eigenspace_div [field K] [vector_space K V] (f : End K V) (a b : K) (hb : b ≠ 0) : eigenspace f (a / b) = (b • f - am a).ker := calc eigenspace f (a / b) = eigenspace f (b⁻¹ * a) : by { dsimp [(/)], rw mul_comm } ... = (f - (b⁻¹ * a) • linear_map.id).ker : rfl ... = (f - b⁻¹ • a • linear_map.id).ker : by rw smul_smul ... = (f - b⁻¹ • am a).ker : rfl ... = (b • (f - b⁻¹ • am a)).ker : by rw linear_map.ker_smul _ b hb ... = (b • f - am a).ker : by rw [smul_sub, smul_inv_smul' hb] lemma eigenspace_eval₂_polynomial_degree_1 [field K] [vector_space K V] (f : End K V) (q : polynomial K) (hq : degree q = 1) : eigenspace f (- q.coeff 0 / q.leading_coeff) = (eval₂ am f q).ker := calc eigenspace f (- q.coeff 0 / q.leading_coeff) = (q.leading_coeff • f - am (- q.coeff 0)).ker : by { rw eigenspace_div, intro h, rw leading_coeff_eq_zero_iff_deg_eq_bot.1 h at hq, cases hq } ... = (eval₂ am f (C q.leading_coeff * X + C (q.coeff 0))).ker : by { rw C_mul', simpa [algebra_map, algebra.to_ring_hom] } ... = (eval₂ am f q).ker : by { congr, apply (eq_X_add_C_of_degree_eq_one hq).symm } lemma ker_eval₂_ring_hom_noncomm_unit_polynomial [field K] [vector_space K V] (f : End K V) (c : units (polynomial K)) : ((eval₂_ring_hom_noncomm am (λ x y, (algebra.commutes x y).symm) f) ↑c).ker = ⊥ := begin rw polynomial.eq_C_of_degree_eq_zero (degree_coe_units c), simp only [eval₂_ring_hom_noncomm, ring_hom.of, ring_hom.coe_mk, eval₂_C], apply ker_algebra_map_End, apply coeff_coe_units_zero_ne_zero c end /-- Every linear operator on a vector space over an algebraically closed field has an eigenvalue. (Axler's Theorem 2.1.) -/ lemma exists_eigenvalue [field K] [is_alg_closed K] [vector_space K V] [finite_dimensional K V] [nontrivial V] (f : End K V) : ∃ (c : K), f.has_eigenvalue c := begin classical, -- Choose a nonzero vector `v`. obtain ⟨v, hv⟩ : ∃ v : V, v ≠ 0 := exists_ne (0 : V), -- The infinitely many vectors v, f v, f (f v), ... cannot be linearly independent -- because the vector space is finite dimensional. have h_lin_dep : ¬ linear_independent K (λ n : ℕ, (f ^ n) v), { apply not_linear_independent_of_infinite, }, -- Therefore, there must be a nonzero polynomial `p` such that `p(f) v = 0`. obtain ⟨p, h_eval_p, h_p_ne_0⟩ : ∃ p, eval₂ am f p v = 0 ∧ p ≠ 0, { simp only [not_imp.symm], exact not_forall.1 (λ h, h_lin_dep ((linear_independent_powers_iff_eval₂ f v).2 h)) }, -- Then `p(f)` is not invertible. have h_eval_p_not_unit : eval₂_ring_hom_noncomm am _ f p ∉ is_unit.submonoid (End K V), { rw [is_unit.mem_submonoid_iff, linear_map.is_unit_iff, linear_map.ker_eq_bot'], intro h, exact hv (h v h_eval_p) }, -- Hence, there must be a factor `q` of `p` such that `q(f)` is not invertible. obtain ⟨q, hq_factor, hq_nonunit⟩ : ∃ q, q ∈ factors p ∧ ¬ is_unit (eval₂ am f q), { simp only [←not_imp, (is_unit.mem_submonoid_iff _).symm], apply not_forall.1 (λ h, h_eval_p_not_unit (ring_hom_mem_submonoid_of_factors_subset_of_units_subset (eval₂_ring_hom_noncomm am (λ x y, (algebra.commutes x y).symm) f) (is_unit.submonoid (End K V)) p h_p_ne_0 h _)), simp only [is_unit.mem_submonoid_iff, linear_map.is_unit_iff], apply ker_eval₂_ring_hom_noncomm_unit_polynomial }, -- Since the field is algebraically closed, `q` has degree 1. have h_deg_q : q.degree = 1 := is_alg_closed.degree_eq_one_of_irreducible _ (ne_zero_of_mem_factors h_p_ne_0 hq_factor) ((factors_spec p h_p_ne_0).1 q hq_factor), -- Then the kernel of `q(f)` is an eigenspace. have h_eigenspace: eigenspace f (-q.coeff 0 / q.leading_coeff) = (eval₂ am f q).ker, from eigenspace_eval₂_polynomial_degree_1 f q h_deg_q, -- Since `q(f)` is not invertible, the kernel is not `⊥`, and thus there exists an eigenvalue. show ∃ (c : K), f.has_eigenvalue c, { use -q.coeff 0 / q.leading_coeff, rw [has_eigenvalue, h_eigenspace], intro h_eval_ker, exact hq_nonunit ((linear_map.is_unit_iff (eval₂ am f q)).2 h_eval_ker) } end /-- Eigenvectors corresponding to distinct eigenvalues of a linear operator are linearly independent. (Axler's Proposition 2.2) We use the eigenvalues as indexing set to ensure that there is only one eigenvector for each eigenvalue in the image of `xs`. -/ lemma eigenvectors_linear_independent [field K] [vector_space K V] (f : End K V) (μs : set K) (xs : μs → V) (h_eigenvec : ∀ μ : μs, f.has_eigenvector μ (xs μ)) : linear_independent K xs := begin classical, -- We need to show that if a linear combination `l` of the eigenvectors `xs` is `0`, then all -- its coefficients are zero. suffices : ∀ l, finsupp.total μs V K xs l = 0 → l = 0, { rw linear_independent_iff, apply this }, intros l hl, -- We apply induction on the finite set of eigenvalues whose eigenvectors have nonzero -- coefficients, i.e. on the support of `l`. induction h_l_support : l.support using finset.induction with μ₀ l_support' hμ₀ ih generalizing l, -- If the support is empty, all coefficients are zero and we are done. { exact finsupp.support_eq_empty.1 h_l_support }, -- Now assume that the support of `l` contains at least one eigenvalue `μ₀`. We define a new -- linear combination `l'` to apply the induction hypothesis on later. The linear combination `l'` -- is derived from `l` by multiplying the coefficient of the eigenvector with eigenvalue `μ` -- by `μ - μ₀`. -- To get started, we define `l'` as a function `l'_f : μs → K` with potentially infinite support. { let l'_f : μs → K := (λ μ : μs, (↑μ - ↑μ₀) * l μ), -- The support of `l'_f` is the support of `l` without `μ₀`. have h_l_support' : ∀ (μ : μs), μ ∈ l_support' ↔ l'_f μ ≠ 0 , { intro μ, suffices : μ ∈ l_support' → μ ≠ μ₀, { simp [l'_f, ← finsupp.not_mem_support_iff, h_l_support, sub_eq_zero, ←subtype.ext_iff], tauto }, rintro hμ rfl, contradiction }, -- Now we can define `l'_f` as an actual linear combination `l'` because we know that the -- support is finite. let l' : μs →₀ K := { to_fun := l'_f, support := l_support', mem_support_to_fun := h_l_support' }, -- The linear combination `l'` over `xs` adds up to `0`. have total_l' : finsupp.total μs V K xs l' = 0, { let g := f - am μ₀, have h_gμ₀: g (l μ₀ • xs μ₀) = 0, by rw [linear_map.map_smul, linear_map.sub_apply, mem_eigenspace_iff.1 (h_eigenvec _).2, algebra_map_End_apply, sub_self, smul_zero], have h_useless_filter : finset.filter (λ (a : μs), l'_f a ≠ 0) l_support' = l_support', { rw finset.filter_congr _, { apply finset.filter_true }, { apply_instance }, exact λ μ hμ, (iff_true _).mpr ((h_l_support' μ).1 hμ) }, have bodies_eq : ∀ (μ : μs), l'_f μ • xs μ = g (l μ • xs μ), { intro μ, dsimp only [g, l'_f], rw [linear_map.map_smul, linear_map.sub_apply, mem_eigenspace_iff.1 (h_eigenvec _).2, algebra_map_End_apply, ←sub_smul, smul_smul, mul_comm] }, rw [←linear_map.map_zero g, ←hl, finsupp.total_apply, finsupp.total_apply, finsupp.sum, finsupp.sum, linear_map.map_sum, h_l_support, finset.sum_insert hμ₀, h_gμ₀, zero_add], refine finset.sum_congr rfl (λ μ _, _), apply bodies_eq }, -- Therefore, by the induction hypothesis, all coefficients in `l'` are zero. have l'_eq_0 : l' = 0 := ih l' total_l' rfl, -- By the defintion of `l'`, this means that `(μ - μ₀) * l μ = 0` for all `μ`. have h_mul_eq_0 : ∀ μ : μs, (↑μ - ↑μ₀) * l μ = 0, { intro μ, calc (↑μ - ↑μ₀) * l μ = l' μ : rfl ... = 0 : by { rw [l'_eq_0], refl } }, -- Thus, the coefficients in `l` for all `μ ≠ μ₀` are `0`. have h_lμ_eq_0 : ∀ μ : μs, μ ≠ μ₀ → l μ = 0, { intros μ hμ, apply or_iff_not_imp_left.1 (mul_eq_zero.1 (h_mul_eq_0 μ)), rwa [sub_eq_zero, ←subtype.ext_iff] }, -- So if we sum over all these coefficients, we obtain `0`. have h_sum_l_support'_eq_0 : finset.sum l_support' (λ (μ : ↥μs), l μ • xs μ) = 0, { rw ←finset.sum_const_zero, apply finset.sum_congr rfl, intros μ hμ, rw h_lμ_eq_0, apply zero_smul, intro h, rw h at hμ, contradiction }, -- The only potentially nonzero coefficient in `l` is the one corresponding to `μ₀`. But since -- the overall sum is `0` by assumption, this coefficient must also be `0`. have : l μ₀ = 0, { rw [finsupp.total_apply, finsupp.sum, h_l_support, finset.sum_insert hμ₀, h_sum_l_support'_eq_0, add_zero] at hl, by_contra h, exact (h_eigenvec μ₀).1 ((smul_eq_zero.1 hl).resolve_left h) }, -- Thus, all coefficients in `l` are `0`. show l = 0, { ext μ, by_cases h_cases : μ = μ₀, { rw h_cases, assumption }, exact h_lμ_eq_0 μ h_cases } } end end End end module
1d013240ce19ae80d1273692f53f35678541ac0c
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/notation4.lean
8362f6a440ec734127245e7748c5f5c6f4e0ec0d
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
310
lean
-- open sigma inductive List (T : Type) : Type | nil {} : List | cons : T → List → List open List notation h :: t := cons h t notation `[` l:(foldr `,` (h t, cons h t) nil) `]` := l check ∃ (A : Type) (x y : A), x = y check ∃ (x : num), x = 0 check Σ' (x : num), x = 10 check Σ (A : Type), List A
60eb5a88580c5ccd6089058559df6ad6171e0625
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/tests/lean/no_confusion_type.lean
aedb431274b08377aac9a528b3816d0c49b868f0
[ "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
353
lean
import logic data.nat.basic open nat inductive vector (A : Type) : nat → Type := vnil : vector A zero, vcons : Π {n : nat}, A → vector A n → vector A (succ n) check vector.no_confusion_type constants a1 a2 : num constants v1 v2 : vector num 2 constant P : Type₁ eval vector.no_confusion_type P (vector.vcons a1 v1) (vector.vcons a2 v2)
ab8fca4951b8d387e7a9442b91540dd87715d2c5
63abd62053d479eae5abf4951554e1064a4c45b4
/src/tactic/omega/term.lean
40f6f5b4cdc48b02b1fc88b5338d137743dd1b16
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
2,690
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Seul Baek -/ /- Normalized linear integer arithmetic terms. -/ import tactic.omega.coeffs namespace omega /-- Shadow syntax of normalized terms. The first element represents the constant term and the list represents the coefficients. -/ @[derive inhabited] def term : Type := int × list int namespace term /-- Evaluate a term using the valuation v. -/ @[simp] def val (v : nat → int) : term → int | (b,as) := b + coeffs.val v as @[simp] def neg : term → term | (b,as) := (-b, list.func.neg as) @[simp] def add : term → term → term | (c1,cfs1) (c2,cfs2) := (c1+c2, list.func.add cfs1 cfs2) @[simp] def sub : term → term → term | (c1,cfs1) (c2,cfs2) := (c1 - c2, list.func.sub cfs1 cfs2) @[simp] def mul (i : int) : term → term | (b,as) := (i * b, as.map ((*) i)) @[simp] def div (i : int) : term → term | (b,as) := (b/i, as.map (λ x, x / i)) lemma val_neg {v : nat → int} {t : term} : (neg t).val v = -(t.val v) := begin cases t with b as, simp only [val, neg_add, neg, val, coeffs.val_neg] end @[simp] lemma val_sub {v : nat → int} {t1 t2 : term} : (sub t1 t2).val v = t1.val v - t2.val v := begin cases t1, cases t2, simp only [add_assoc, coeffs.val_sub, neg_add_rev, val, sub, add_comm, add_left_comm, sub_eq_add_neg] end @[simp] lemma val_add {v : nat → int} {t1 t2 : term} : (add t1 t2).val v = t1.val v + t2.val v := begin cases t1, cases t2, simp only [coeffs.val_add, add, val, add_comm, add_left_comm] end @[simp] lemma val_mul {v : nat → int} {i : int} {t : term} : val v (mul i t) = i * (val v t) := begin cases t, simp only [mul, mul_add, add_mul, list.length_map, coeffs.val, coeffs.val_between_map_mul, val, list.map] end lemma val_div {v : nat → int} {i b : int} {as : list int} : i ∣ b → (∀ x ∈ as, i ∣ x) → (div i (b,as)).val v = (val v (b,as)) / i := begin intros h1 h2, simp only [val, div, list.map], rw [int.add_div_of_dvd h1 (coeffs.dvd_val h2)], apply fun_mono_2 rfl, rw ← coeffs.val_map_div h2 end /-- Fresh de Brujin index not used by any variable ocurring in the term -/ def fresh_index (t : term) : nat := t.snd.length def to_string (t : term) : string := t.2.enum.foldr (λ ⟨i, n⟩ r, to_string n ++ " * x" ++ to_string i ++ " + " ++ r) (to_string t.1) instance : has_to_string term := ⟨to_string⟩ end term /-- Fresh de Brujin index not used by any variable ocurring in the list of terms -/ def terms.fresh_index : list term → nat | [] := 0 | (t::ts) := max t.fresh_index (terms.fresh_index ts) end omega