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
50a60b02d772c073deea3e62e0b3bac55c1f9745
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/data/real/cau_seq_completion.lean
dc4b759485a702744990a35bd17a30352d78a4f5
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
9,454
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Robert Y. Lewis Generalizes the Cauchy completion of (ℚ, abs) to the completion of a commutative ring with absolute value. -/ import data.real.cau_seq namespace cau_seq.completion open cau_seq section parameters {α : Type*} [discrete_linear_ordered_field α] parameters {β : Type*} [comm_ring β] {abv : β → α} [is_absolute_value abv] def Cauchy := @quotient (cau_seq _ abv) cau_seq.equiv def mk : cau_seq _ abv → Cauchy := quotient.mk @[simp] theorem mk_eq_mk (f) : @eq Cauchy ⟦f⟧ (mk f) := rfl theorem mk_eq {f g} : mk f = mk g ↔ f ≈ g := quotient.eq def of_rat (x : β) : Cauchy := mk (const abv x) instance : has_zero Cauchy := ⟨of_rat 0⟩ instance : has_one Cauchy := ⟨of_rat 1⟩ instance : inhabited Cauchy := ⟨0⟩ theorem of_rat_zero : of_rat 0 = 0 := rfl theorem of_rat_one : of_rat 1 = 1 := rfl @[simp] theorem mk_eq_zero {f} : mk f = 0 ↔ lim_zero f := by have : mk f = 0 ↔ lim_zero (f - 0) := quotient.eq; rwa sub_zero at this instance : has_add Cauchy := ⟨λ x y, quotient.lift_on₂ x y (λ f g, mk (f + g)) $ λ f₁ g₁ f₂ g₂ hf hg, quotient.sound $ by simpa [(≈), setoid.r, sub_eq_add_neg, add_comm, add_left_comm] using add_lim_zero hf hg⟩ @[simp] theorem mk_add (f g : cau_seq β abv) : mk f + mk g = mk (f + g) := rfl instance : has_neg Cauchy := ⟨λ x, quotient.lift_on x (λ f, mk (-f)) $ λ f₁ f₂ hf, quotient.sound $ by simpa [(≈), setoid.r] using neg_lim_zero hf⟩ @[simp] theorem mk_neg (f : cau_seq β abv) : -mk f = mk (-f) := rfl instance : has_mul Cauchy := ⟨λ x y, quotient.lift_on₂ x y (λ f g, mk (f * g)) $ λ f₁ g₁ f₂ g₂ hf hg, quotient.sound $ by simpa [(≈), setoid.r, mul_add, mul_comm, sub_eq_add_neg] using add_lim_zero (mul_lim_zero_right g₁ hf) (mul_lim_zero_right f₂ hg)⟩ @[simp] theorem mk_mul (f g : cau_seq β abv) : mk f * mk g = mk (f * g) := rfl theorem of_rat_add (x y : β) : of_rat (x + y) = of_rat x + of_rat y := congr_arg mk (const_add _ _) theorem of_rat_neg (x : β) : of_rat (-x) = -of_rat x := congr_arg mk (const_neg _) theorem of_rat_mul (x y : β) : of_rat (x * y) = of_rat x * of_rat y := congr_arg mk (const_mul _ _) private lemma zero_def : 0 = mk 0 := rfl private lemma one_def : 1 = mk 1 := rfl instance : comm_ring Cauchy := by refine { neg := has_neg.neg, add := (+), zero := 0, mul := (*), one := 1, .. }; { repeat {refine λ a, quotient.induction_on a (λ _, _)}, simp [zero_def, one_def, mul_left_comm, mul_comm, mul_add, add_comm, add_left_comm] } theorem of_rat_sub (x y : β) : of_rat (x - y) = of_rat x - of_rat y := congr_arg mk (const_sub _ _) end open_locale classical section parameters {α : Type*} [discrete_linear_ordered_field α] parameters {β : Type*} [field β] {abv : β → α} [is_absolute_value abv] local notation `Cauchy` := @Cauchy _ _ _ _ abv _ noncomputable instance : has_inv Cauchy := ⟨λ x, quotient.lift_on x (λ f, mk $ if h : lim_zero f then 0 else inv f h) $ λ f g fg, begin have := lim_zero_congr fg, by_cases hf : lim_zero f, { simp [hf, this.1 hf, setoid.refl] }, { have hg := mt this.2 hf, simp [hf, hg], have If : mk (inv f hf) * mk f = 1 := mk_eq.2 (inv_mul_cancel hf), have Ig : mk (inv g hg) * mk g = 1 := mk_eq.2 (inv_mul_cancel hg), rw [mk_eq.2 fg, ← Ig] at If, rw mul_comm at Ig, rw [← mul_one (mk (inv f hf)), ← Ig, ← mul_assoc, If, mul_assoc, Ig, mul_one] } end⟩ @[simp] theorem inv_zero : (0 : Cauchy)⁻¹ = 0 := congr_arg mk $ by rw dif_pos; [refl, exact zero_lim_zero] @[simp] theorem inv_mk {f} (hf) : (@mk α _ β _ abv _ f)⁻¹ = mk (inv f hf) := congr_arg mk $ by rw dif_neg lemma cau_seq_zero_ne_one : ¬ (0 : cau_seq _ abv) ≈ 1 := λ h, have lim_zero (1 - 0), from setoid.symm h, have lim_zero 1, by simpa, one_ne_zero $ const_lim_zero.1 this lemma zero_ne_one : (0 : Cauchy) ≠ 1 := λ h, cau_seq_zero_ne_one $ mk_eq.1 h protected theorem inv_mul_cancel {x : Cauchy} : x ≠ 0 → x⁻¹ * x = 1 := quotient.induction_on x $ λ f hf, begin simp at hf, simp [hf], exact quotient.sound (cau_seq.inv_mul_cancel hf) end noncomputable def field : field Cauchy := { inv := has_inv.inv, mul_inv_cancel := λ x x0, by rw [mul_comm, cau_seq.completion.inv_mul_cancel x0], zero_ne_one := zero_ne_one, inv_zero := inv_zero, ..cau_seq.completion.comm_ring } local attribute [instance] field theorem of_rat_inv (x : β) : of_rat (x⁻¹) = ((of_rat x)⁻¹ : Cauchy) := congr_arg mk $ by split_ifs with h; try {simp [const_lim_zero.1 h]}; refl theorem of_rat_div (x y : β) : of_rat (x / y) = (of_rat x / of_rat y : Cauchy) := by simp only [div_eq_inv_mul', of_rat_inv, of_rat_mul] end end cau_seq.completion variables {α : Type*} [discrete_linear_ordered_field α] namespace cau_seq section variables (β : Type*) [ring β] (abv : β → α) [is_absolute_value abv] class is_complete := (is_complete : ∀ s : cau_seq β abv, ∃ b : β, s ≈ const abv b) end section variables {β : Type*} [ring β] {abv : β → α} [is_absolute_value abv] variable [is_complete β abv] lemma complete : ∀ s : cau_seq β abv, ∃ b : β, s ≈ const abv b := is_complete.is_complete noncomputable def lim (s : cau_seq β abv) := classical.some (complete s) lemma equiv_lim (s : cau_seq β abv) : s ≈ const abv (lim s) := classical.some_spec (complete s) lemma eq_lim_of_const_equiv {f : cau_seq β abv} {x : β} (h : cau_seq.const abv x ≈ f) : x = lim f := const_equiv.mp $ setoid.trans h $ equiv_lim f lemma lim_eq_of_equiv_const {f : cau_seq β abv} {x : β} (h : f ≈ cau_seq.const abv x) : lim f = x := (eq_lim_of_const_equiv $ setoid.symm h).symm lemma lim_eq_lim_of_equiv {f g : cau_seq β abv} (h : f ≈ g) : lim f = lim g := lim_eq_of_equiv_const $ setoid.trans h $ equiv_lim g @[simp] lemma lim_const (x : β) : lim (const abv x) = x := lim_eq_of_equiv_const $ setoid.refl _ lemma lim_add (f g : cau_seq β abv) : lim f + lim g = lim (f + g) := eq_lim_of_const_equiv $ show lim_zero (const abv (lim f + lim g) - (f + g)), by rw [const_add, add_sub_comm]; exact add_lim_zero (setoid.symm (equiv_lim f)) (setoid.symm (equiv_lim g)) lemma lim_mul_lim (f g : cau_seq β abv) : lim f * lim g = lim (f * g) := eq_lim_of_const_equiv $ show lim_zero (const abv (lim f * lim g) - f * g), from have h : const abv (lim f * lim g) - f * g = (const abv (lim f) - f) * g + const abv (lim f) * (const abv (lim g) - g) := by simp [const_mul (lim f), mul_add, add_mul, sub_eq_add_neg, add_comm, add_left_comm], by rw h; exact add_lim_zero (mul_lim_zero_left _ (setoid.symm (equiv_lim _))) (mul_lim_zero_right _ (setoid.symm (equiv_lim _))) lemma lim_mul (f : cau_seq β abv) (x : β) : lim f * x = lim (f * const abv x) := by rw [← lim_mul_lim, lim_const] lemma lim_neg (f : cau_seq β abv) : lim (-f) = -lim f := lim_eq_of_equiv_const (show lim_zero (-f - const abv (-lim f)), by rw [const_neg, sub_neg_eq_add, add_comm]; exact setoid.symm (equiv_lim f)) lemma lim_eq_zero_iff (f : cau_seq β abv) : lim f = 0 ↔ lim_zero f := ⟨assume h, by have hf := equiv_lim f; rw h at hf; exact (lim_zero_congr hf).mpr (const_lim_zero.mpr rfl), assume h, have h₁ : f = (f - const abv 0) := ext (λ n, by simp [sub_apply, const_apply]), by rw h₁ at h; exact lim_eq_of_equiv_const h ⟩ end section variables {β : Type*} [field β] {abv : β → α} [is_absolute_value abv] [is_complete β abv] lemma lim_inv {f : cau_seq β abv} (hf : ¬ lim_zero f) : lim (inv f hf) = (lim f)⁻¹ := have hl : lim f ≠ 0 := by rwa ← lim_eq_zero_iff at hf, lim_eq_of_equiv_const $ show lim_zero (inv f hf - const abv (lim f)⁻¹), from have h₁ : ∀ (g f : cau_seq β abv) (hf : ¬ lim_zero f), lim_zero (g - f * inv f hf * g) := λ g f hf, by rw [← one_mul g, ← mul_assoc, ← sub_mul, mul_one, mul_comm, mul_comm f]; exact mul_lim_zero_right _ (setoid.symm (cau_seq.inv_mul_cancel _)), have h₂ : lim_zero ((inv f hf - const abv (lim f)⁻¹) - (const abv (lim f) - f) * (inv f hf * const abv (lim f)⁻¹)) := by rw [sub_mul, ← sub_add, sub_sub, sub_add_eq_sub_sub, sub_right_comm, sub_add]; exact show lim_zero (inv f hf - const abv (lim f) * (inv f hf * const abv (lim f)⁻¹) - (const abv (lim f)⁻¹ - f * (inv f hf * const abv (lim f)⁻¹))), from sub_lim_zero (by rw [← mul_assoc, mul_right_comm, const_inv hl]; exact h₁ _ _ _) (by rw [← mul_assoc]; exact h₁ _ _ _), (lim_zero_congr h₂).mpr $ mul_lim_zero_left _ (setoid.symm (equiv_lim f)) end section variables [is_complete α abs] lemma lim_le {f : cau_seq α abs} {x : α} (h : f ≤ cau_seq.const abs x) : lim f ≤ x := cau_seq.const_le.1 $ cau_seq.le_of_eq_of_le (setoid.symm (equiv_lim f)) h lemma le_lim {f : cau_seq α abs} {x : α} (h : cau_seq.const abs x ≤ f) : x ≤ lim f := cau_seq.const_le.1 $ cau_seq.le_of_le_of_eq h (equiv_lim f) lemma lt_lim {f : cau_seq α abs} {x : α} (h : cau_seq.const abs x < f) : x < lim f := cau_seq.const_lt.1 $ cau_seq.lt_of_lt_of_eq h (equiv_lim f) lemma lim_lt {f : cau_seq α abs} {x : α} (h : f < cau_seq.const abs x) : lim f < x := cau_seq.const_lt.1 $ cau_seq.lt_of_eq_of_lt (setoid.symm (equiv_lim f)) h end end cau_seq
168b0e155e68e4ca26c39fa80ce34ba3b68c141d
592ee40978ac7604005a4e0d35bbc4b467389241
/Library/generated/mathscheme-lean/ModularLattice.lean
3ebad548760a414289fbe4df3be288df183a833c
[]
no_license
ysharoda/Deriving-Definitions
3e149e6641fae440badd35ac110a0bd705a49ad2
dfecb27572022de3d4aa702cae8db19957523a59
refs/heads/master
1,679,127,857,700
1,615,939,007,000
1,615,939,007,000
229,785,731
4
0
null
null
null
null
UTF-8
Lean
false
false
10,377
lean
import init.data.nat.basic import init.data.fin.basic import data.vector import .Prelude open Staged open nat open fin open vector section ModularLattice structure ModularLattice (A : Type) : Type := (times : (A → (A → A))) (plus : (A → (A → A))) (commutative_times : (∀ {x y : A} , (times x y) = (times y x))) (associative_times : (∀ {x y z : A} , (times (times x y) z) = (times x (times y z)))) (idempotent_times : (∀ {x : A} , (times x x) = x)) (commutative_plus : (∀ {x y : A} , (plus x y) = (plus y x))) (associative_plus : (∀ {x y z : A} , (plus (plus x y) z) = (plus x (plus y z)))) (idempotent_plus : (∀ {x : A} , (plus x x) = x)) (leftAbsorp_times_plus : (∀ {x y : A} , (times x (plus x y)) = x)) (leftAbsorp_plus_times : (∀ {x y : A} , (plus x (times x y)) = x)) (leftModular_times_plus : (∀ {x y z : A} , (plus (times x y) (times x z)) = (times x (plus y (times x z))))) open ModularLattice structure Sig (AS : Type) : Type := (timesS : (AS → (AS → AS))) (plusS : (AS → (AS → AS))) structure Product (A : Type) : Type := (timesP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (plusP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (commutative_timesP : (∀ {xP yP : (Prod A A)} , (timesP xP yP) = (timesP yP xP))) (associative_timesP : (∀ {xP yP zP : (Prod A A)} , (timesP (timesP xP yP) zP) = (timesP xP (timesP yP zP)))) (idempotent_timesP : (∀ {xP : (Prod A A)} , (timesP xP xP) = xP)) (commutative_plusP : (∀ {xP yP : (Prod A A)} , (plusP xP yP) = (plusP yP xP))) (associative_plusP : (∀ {xP yP zP : (Prod A A)} , (plusP (plusP xP yP) zP) = (plusP xP (plusP yP zP)))) (idempotent_plusP : (∀ {xP : (Prod A A)} , (plusP xP xP) = xP)) (leftAbsorp_times_plusP : (∀ {xP yP : (Prod A A)} , (timesP xP (plusP xP yP)) = xP)) (leftAbsorp_plus_timesP : (∀ {xP yP : (Prod A A)} , (plusP xP (timesP xP yP)) = xP)) (leftModular_times_plusP : (∀ {xP yP zP : (Prod A A)} , (plusP (timesP xP yP) (timesP xP zP)) = (timesP xP (plusP yP (timesP xP zP))))) structure Hom {A1 : Type} {A2 : Type} (Mo1 : (ModularLattice A1)) (Mo2 : (ModularLattice A2)) : Type := (hom : (A1 → A2)) (pres_times : (∀ {x1 x2 : A1} , (hom ((times Mo1) x1 x2)) = ((times Mo2) (hom x1) (hom x2)))) (pres_plus : (∀ {x1 x2 : A1} , (hom ((plus Mo1) x1 x2)) = ((plus Mo2) (hom x1) (hom x2)))) structure RelInterp {A1 : Type} {A2 : Type} (Mo1 : (ModularLattice A1)) (Mo2 : (ModularLattice A2)) : Type 1 := (interp : (A1 → (A2 → Type))) (interp_times : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((times Mo1) x1 x2) ((times Mo2) y1 y2)))))) (interp_plus : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((plus Mo1) x1 x2) ((plus Mo2) y1 y2)))))) inductive ModularLatticeTerm : Type | timesL : (ModularLatticeTerm → (ModularLatticeTerm → ModularLatticeTerm)) | plusL : (ModularLatticeTerm → (ModularLatticeTerm → ModularLatticeTerm)) open ModularLatticeTerm inductive ClModularLatticeTerm (A : Type) : Type | sing : (A → ClModularLatticeTerm) | timesCl : (ClModularLatticeTerm → (ClModularLatticeTerm → ClModularLatticeTerm)) | plusCl : (ClModularLatticeTerm → (ClModularLatticeTerm → ClModularLatticeTerm)) open ClModularLatticeTerm inductive OpModularLatticeTerm (n : ℕ) : Type | v : ((fin n) → OpModularLatticeTerm) | timesOL : (OpModularLatticeTerm → (OpModularLatticeTerm → OpModularLatticeTerm)) | plusOL : (OpModularLatticeTerm → (OpModularLatticeTerm → OpModularLatticeTerm)) open OpModularLatticeTerm inductive OpModularLatticeTerm2 (n : ℕ) (A : Type) : Type | v2 : ((fin n) → OpModularLatticeTerm2) | sing2 : (A → OpModularLatticeTerm2) | timesOL2 : (OpModularLatticeTerm2 → (OpModularLatticeTerm2 → OpModularLatticeTerm2)) | plusOL2 : (OpModularLatticeTerm2 → (OpModularLatticeTerm2 → OpModularLatticeTerm2)) open OpModularLatticeTerm2 def simplifyCl {A : Type} : ((ClModularLatticeTerm A) → (ClModularLatticeTerm A)) | (timesCl x1 x2) := (timesCl (simplifyCl x1) (simplifyCl x2)) | (plusCl x1 x2) := (plusCl (simplifyCl x1) (simplifyCl x2)) | (sing x1) := (sing x1) def simplifyOpB {n : ℕ} : ((OpModularLatticeTerm n) → (OpModularLatticeTerm n)) | (timesOL x1 x2) := (timesOL (simplifyOpB x1) (simplifyOpB x2)) | (plusOL x1 x2) := (plusOL (simplifyOpB x1) (simplifyOpB x2)) | (v x1) := (v x1) def simplifyOp {n : ℕ} {A : Type} : ((OpModularLatticeTerm2 n A) → (OpModularLatticeTerm2 n A)) | (timesOL2 x1 x2) := (timesOL2 (simplifyOp x1) (simplifyOp x2)) | (plusOL2 x1 x2) := (plusOL2 (simplifyOp x1) (simplifyOp x2)) | (v2 x1) := (v2 x1) | (sing2 x1) := (sing2 x1) def evalB {A : Type} : ((ModularLattice A) → (ModularLatticeTerm → A)) | Mo (timesL x1 x2) := ((times Mo) (evalB Mo x1) (evalB Mo x2)) | Mo (plusL x1 x2) := ((plus Mo) (evalB Mo x1) (evalB Mo x2)) def evalCl {A : Type} : ((ModularLattice A) → ((ClModularLatticeTerm A) → A)) | Mo (sing x1) := x1 | Mo (timesCl x1 x2) := ((times Mo) (evalCl Mo x1) (evalCl Mo x2)) | Mo (plusCl x1 x2) := ((plus Mo) (evalCl Mo x1) (evalCl Mo x2)) def evalOpB {A : Type} {n : ℕ} : ((ModularLattice A) → ((vector A n) → ((OpModularLatticeTerm n) → A))) | Mo vars (v x1) := (nth vars x1) | Mo vars (timesOL x1 x2) := ((times Mo) (evalOpB Mo vars x1) (evalOpB Mo vars x2)) | Mo vars (plusOL x1 x2) := ((plus Mo) (evalOpB Mo vars x1) (evalOpB Mo vars x2)) def evalOp {A : Type} {n : ℕ} : ((ModularLattice A) → ((vector A n) → ((OpModularLatticeTerm2 n A) → A))) | Mo vars (v2 x1) := (nth vars x1) | Mo vars (sing2 x1) := x1 | Mo vars (timesOL2 x1 x2) := ((times Mo) (evalOp Mo vars x1) (evalOp Mo vars x2)) | Mo vars (plusOL2 x1 x2) := ((plus Mo) (evalOp Mo vars x1) (evalOp Mo vars x2)) def inductionB {P : (ModularLatticeTerm → Type)} : ((∀ (x1 x2 : ModularLatticeTerm) , ((P x1) → ((P x2) → (P (timesL x1 x2))))) → ((∀ (x1 x2 : ModularLatticeTerm) , ((P x1) → ((P x2) → (P (plusL x1 x2))))) → (∀ (x : ModularLatticeTerm) , (P x)))) | ptimesl pplusl (timesL x1 x2) := (ptimesl _ _ (inductionB ptimesl pplusl x1) (inductionB ptimesl pplusl x2)) | ptimesl pplusl (plusL x1 x2) := (pplusl _ _ (inductionB ptimesl pplusl x1) (inductionB ptimesl pplusl x2)) def inductionCl {A : Type} {P : ((ClModularLatticeTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((∀ (x1 x2 : (ClModularLatticeTerm A)) , ((P x1) → ((P x2) → (P (timesCl x1 x2))))) → ((∀ (x1 x2 : (ClModularLatticeTerm A)) , ((P x1) → ((P x2) → (P (plusCl x1 x2))))) → (∀ (x : (ClModularLatticeTerm A)) , (P x))))) | psing ptimescl ppluscl (sing x1) := (psing x1) | psing ptimescl ppluscl (timesCl x1 x2) := (ptimescl _ _ (inductionCl psing ptimescl ppluscl x1) (inductionCl psing ptimescl ppluscl x2)) | psing ptimescl ppluscl (plusCl x1 x2) := (ppluscl _ _ (inductionCl psing ptimescl ppluscl x1) (inductionCl psing ptimescl ppluscl x2)) def inductionOpB {n : ℕ} {P : ((OpModularLatticeTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((∀ (x1 x2 : (OpModularLatticeTerm n)) , ((P x1) → ((P x2) → (P (timesOL x1 x2))))) → ((∀ (x1 x2 : (OpModularLatticeTerm n)) , ((P x1) → ((P x2) → (P (plusOL x1 x2))))) → (∀ (x : (OpModularLatticeTerm n)) , (P x))))) | pv ptimesol pplusol (v x1) := (pv x1) | pv ptimesol pplusol (timesOL x1 x2) := (ptimesol _ _ (inductionOpB pv ptimesol pplusol x1) (inductionOpB pv ptimesol pplusol x2)) | pv ptimesol pplusol (plusOL x1 x2) := (pplusol _ _ (inductionOpB pv ptimesol pplusol x1) (inductionOpB pv ptimesol pplusol x2)) def inductionOp {n : ℕ} {A : Type} {P : ((OpModularLatticeTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((∀ (x1 x2 : (OpModularLatticeTerm2 n A)) , ((P x1) → ((P x2) → (P (timesOL2 x1 x2))))) → ((∀ (x1 x2 : (OpModularLatticeTerm2 n A)) , ((P x1) → ((P x2) → (P (plusOL2 x1 x2))))) → (∀ (x : (OpModularLatticeTerm2 n A)) , (P x)))))) | pv2 psing2 ptimesol2 pplusol2 (v2 x1) := (pv2 x1) | pv2 psing2 ptimesol2 pplusol2 (sing2 x1) := (psing2 x1) | pv2 psing2 ptimesol2 pplusol2 (timesOL2 x1 x2) := (ptimesol2 _ _ (inductionOp pv2 psing2 ptimesol2 pplusol2 x1) (inductionOp pv2 psing2 ptimesol2 pplusol2 x2)) | pv2 psing2 ptimesol2 pplusol2 (plusOL2 x1 x2) := (pplusol2 _ _ (inductionOp pv2 psing2 ptimesol2 pplusol2 x1) (inductionOp pv2 psing2 ptimesol2 pplusol2 x2)) def stageB : (ModularLatticeTerm → (Staged ModularLatticeTerm)) | (timesL x1 x2) := (stage2 timesL (codeLift2 timesL) (stageB x1) (stageB x2)) | (plusL x1 x2) := (stage2 plusL (codeLift2 plusL) (stageB x1) (stageB x2)) def stageCl {A : Type} : ((ClModularLatticeTerm A) → (Staged (ClModularLatticeTerm A))) | (sing x1) := (Now (sing x1)) | (timesCl x1 x2) := (stage2 timesCl (codeLift2 timesCl) (stageCl x1) (stageCl x2)) | (plusCl x1 x2) := (stage2 plusCl (codeLift2 plusCl) (stageCl x1) (stageCl x2)) def stageOpB {n : ℕ} : ((OpModularLatticeTerm n) → (Staged (OpModularLatticeTerm n))) | (v x1) := (const (code (v x1))) | (timesOL x1 x2) := (stage2 timesOL (codeLift2 timesOL) (stageOpB x1) (stageOpB x2)) | (plusOL x1 x2) := (stage2 plusOL (codeLift2 plusOL) (stageOpB x1) (stageOpB x2)) def stageOp {n : ℕ} {A : Type} : ((OpModularLatticeTerm2 n A) → (Staged (OpModularLatticeTerm2 n A))) | (sing2 x1) := (Now (sing2 x1)) | (v2 x1) := (const (code (v2 x1))) | (timesOL2 x1 x2) := (stage2 timesOL2 (codeLift2 timesOL2) (stageOp x1) (stageOp x2)) | (plusOL2 x1 x2) := (stage2 plusOL2 (codeLift2 plusOL2) (stageOp x1) (stageOp x2)) structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type := (timesT : ((Repr A) → ((Repr A) → (Repr A)))) (plusT : ((Repr A) → ((Repr A) → (Repr A)))) end ModularLattice
927d708ec280a892cfc5faa95b9350cefe20318c
2b2a05a7af89c79da194505bf88205a6c4e05d68
/src/game/world_08_advanced_addition.lean
fa0b087867a3b1c9be62e4ec66eb4cebc8d564fe
[]
no_license
lacrosse/natural_number_game
6401a11a8c965da3903ae6695f84586edf6fac85
400179cde1d3fcc9744901dabff98813ba2b544f
refs/heads/master
1,677,566,006,582
1,612,576,917,000
1,612,576,917,000
335,655,947
2
0
null
null
null
null
UTF-8
Lean
false
false
2,079
lean
import game.world_07_advanced_proposition namespace mynat theorem succ_inj' {a b : mynat} (hs : succ(a) = succ(b)) : a = b := begin[nat_num_game] exact succ_inj hs, end theorem succ_succ_inj {a b : mynat} (h : succ(succ(a)) = succ(succ(b))) : a = b := begin[nat_num_game] apply succ_inj ∘ succ_inj, exact h, end theorem succ_eq_succ_of_eq {a b : mynat} : a = b → succ(a) = succ(b) := begin[nat_num_game] intro h, rwa h, end theorem succ_eq_succ_iff (a b : mynat) : succ a = succ b ↔ a = b := begin[nat_num_game] split, exact succ_inj, exact succ_eq_succ_of_eq, end theorem add_right_cancel (a t b : mynat) : a + t = b + t → a = b := begin[nat_num_game] intro h, induction t, rwa add_zero at h, { apply t_ih, rwa [add_succ, add_succ] at h, cc } end theorem add_left_cancel (t a b : mynat) : t + a = t + b → a = b := begin[nat_num_game] rw [add_comm t, add_comm t], apply add_right_cancel, end theorem add_right_cancel_iff (t a b : mynat) : a + t = b + t ↔ a = b := begin[nat_num_game] split, apply add_right_cancel, { intro h, rwa h, } end lemma eq_zero_of_add_right_eq_self {a b : mynat} : a + b = a → b = 0 := begin[nat_num_game] intros h, induction a, { rw zero_add at h, apply h }, { apply a_ih, rw succ_add at h, apply succ_inj h } end theorem succ_ne_zero (a : mynat) : succ a ≠ 0 := begin[nat_num_game] symmetry, apply zero_ne_succ, end lemma add_left_eq_zero {{a b : mynat}} (H : a + b = 0) : b = 0 := begin[nat_num_game] cases b, refl, { exfalso, rw add_succ at H, apply succ_ne_zero, apply H } end lemma add_right_eq_zero {a b : mynat} : a + b = 0 → a = 0 := begin[nat_num_game] rw add_comm, apply add_left_eq_zero, end theorem add_one_eq_succ (d : mynat) : d + 1 = succ d := begin[nat_num_game] symmetry, apply succ_eq_add_one, end lemma ne_succ_self (n : mynat) : n ≠ succ n := begin[nat_num_game] induction n, apply zero_ne_succ, { intro h, apply n_ih, apply succ_inj, apply h } end end mynat
05fd77235a2c701df9110090e402a6b2c70e608a
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/stage0/src/Lean/ParserCompiler.lean
5b42588338a06e6294a67d25fdff60f15222e9e1
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
7,395
lean
/- Copyright (c) 2020 Sebastian Ullrich. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich -/ /-! Gadgets for compiling parser declarations into other programs, such as pretty printers. -/ import Lean.Util.ReplaceExpr import Lean.Meta.Basic import Lean.Meta.WHNF import Lean.ParserCompiler.Attribute import Lean.Parser.Extension namespace Lean namespace ParserCompiler structure Context (α : Type) where varName : Name categoryAttr : KeyedDeclsAttribute α combinatorAttr : CombinatorAttribute def Context.tyName {α} (ctx : Context α) : Name := ctx.categoryAttr.defn.valueTypeName -- replace all references of `Parser` with `tyName` def replaceParserTy {α} (ctx : Context α) (e : Expr) : Expr := e.replace fun e => -- strip `optParam` let e := if e.isOptParam then e.appFn!.appArg! else e if e.isConstOf `Lean.Parser.Parser then mkConst ctx.tyName else none section open Meta variable {α} (ctx : Context α) (force : Bool := false) in /-- Translate an expression of type `Parser` into one of type `tyName`, tagging intermediary constants with `ctx.combinatorAttr`. If `force` is `false`, refuse to do so for imported constants. -/ partial def compileParserExpr (e : Expr) : MetaM Expr := do let e ← whnfCore e match e with | e@(Expr.lam _ _ _ _) => lambdaLetTelescope e fun xs b => compileParserExpr b >>= mkLambdaFVars xs | e@(Expr.fvar _ _) => pure e | _ => do let fn := e.getAppFn let Expr.const c _ _ ← pure fn | throwError "call of unknown parser at '{e}'" let args := e.getAppArgs -- call the translated `p` with (a prefix of) the arguments of `e`, recursing for arguments -- of type `ty` (i.e. formerly `Parser`) let mkCall (p : Name) := do let ty ← inferType (mkConst p) forallTelescope ty fun params _ => do let mut p := mkConst p let args := e.getAppArgs for i in [:Nat.min params.size args.size] do let param := params[i] let arg := args[i] let paramTy ← inferType param let resultTy ← forallTelescope paramTy fun _ b => pure b let arg ← if resultTy.isConstOf ctx.tyName then compileParserExpr arg else pure arg p := mkApp p arg pure p let env ← getEnv match ctx.combinatorAttr.getDeclFor? env c with | some p => mkCall p | none => let c' := c ++ ctx.varName let cinfo ← getConstInfo c let resultTy ← forallTelescope cinfo.type fun _ b => pure b if resultTy.isConstOf `Lean.Parser.TrailingParser || resultTy.isConstOf `Lean.Parser.Parser then do -- synthesize a new `[combinatorAttr c]` let some value ← pure cinfo.value? | throwError "don't know how to generate {ctx.varName} for non-definition '{e}'" unless (env.getModuleIdxFor? c).isNone || force do throwError "refusing to generate code for imported parser declaration '{c}'; use `@[runParserAttributeHooks]` on its definition instead." let value ← compileParserExpr $ replaceParserTy ctx value let ty ← forallTelescope cinfo.type fun params _ => params.foldrM (init := mkConst ctx.tyName) fun param ty => do let paramTy ← replaceParserTy ctx <$> inferType param pure $ mkForall `_ BinderInfo.default paramTy ty let decl := Declaration.defnDecl { name := c', levelParams := [], type := ty, value := value, hints := ReducibilityHints.opaque, safety := DefinitionSafety.safe } let env ← getEnv let env ← match env.addAndCompile {} decl with | Except.ok env => pure env | Except.error kex => do throwError (← (kex.toMessageData {}).toString) setEnv $ ctx.combinatorAttr.setDeclFor env c c' mkCall c' else -- if this is a generic function, e.g. `AndThen.andthen`, it's easier to just unfold it until we are -- back to parser combinators let some e' ← unfoldDefinition? e | throwError "don't know how to generate {ctx.varName} for non-parser combinator '{e}'" compileParserExpr e' end open Core /-- Compile the given declaration into a `[(builtin)categoryAttr declName]` -/ def compileCategoryParser {α} (ctx : Context α) (declName : Name) (builtin : Bool) : AttrM Unit := do -- This will also tag the declaration as a `[combinatorParenthesizer declName]` in case the parser is used by other parsers. -- Note that simply having `[(builtin)Parenthesizer]` imply `[combinatorParenthesizer]` is not ideal since builtin -- attributes are active only in the next stage, while `[combinatorParenthesizer]` is active immediately (since we never -- call them at compile time but only reference them). let (Expr.const c' _ _) ← (compileParserExpr ctx (mkConst declName) (force := false)).run' | unreachable! -- We assume that for tagged parsers, the kind is equal to the declaration name. This is automatically true for parsers -- using `leading_parser` or `syntax`. let kind := declName let attrName := if builtin then ctx.categoryAttr.defn.builtinName else ctx.categoryAttr.defn.name -- Create syntax node for a simple attribute of the form -- `def simple := leading_parser ident >> optional (ident <|> priorityParser)` let stx := Syntax.node `Lean.Parser.Attr.simple #[ mkIdent attrName, mkNullNode #[mkIdent kind] ] Attribute.add c' attrName stx variable {α} (ctx : Context α) in def compileEmbeddedParsers : ParserDescr → MetaM Unit | ParserDescr.const _ => pure () | ParserDescr.unary _ d => compileEmbeddedParsers d | ParserDescr.binary _ d₁ d₂ => compileEmbeddedParsers d₁ *> compileEmbeddedParsers d₂ | ParserDescr.parser constName => discard $ compileParserExpr ctx (mkConst constName) (force := false) | ParserDescr.node _ _ d => compileEmbeddedParsers d | ParserDescr.nodeWithAntiquot _ _ d => compileEmbeddedParsers d | ParserDescr.sepBy p _ psep _ => compileEmbeddedParsers p *> compileEmbeddedParsers psep | ParserDescr.sepBy1 p _ psep _ => compileEmbeddedParsers p *> compileEmbeddedParsers psep | ParserDescr.trailingNode _ _ _ d => compileEmbeddedParsers d | ParserDescr.symbol _ => pure () | ParserDescr.nonReservedSymbol _ _ => pure () | ParserDescr.cat _ _ => pure () /-- Precondition: `α` must match `ctx.tyName`. -/ unsafe def registerParserCompiler {α} (ctx : Context α) : IO Unit := do Parser.registerParserAttributeHook { postAdd := fun catName constName builtin => do let info ← getConstInfo constName if info.type.isConstOf `Lean.ParserDescr || info.type.isConstOf `Lean.TrailingParserDescr then let d ← evalConstCheck ParserDescr `Lean.ParserDescr constName <|> evalConstCheck TrailingParserDescr `Lean.TrailingParserDescr constName compileEmbeddedParsers ctx d |>.run' else if catName.isAnonymous then -- `[runBuiltinParserAttributeHooks]` => force compilation even if imported, do not apply `ctx.categoryAttr`. discard (compileParserExpr ctx (mkConst constName) (force := true)).run' else compileCategoryParser ctx constName builtin } end ParserCompiler end Lean
c659602610d4d860eb35672b5db76b88cba6f8e8
7cef822f3b952965621309e88eadf618da0c8ae9
/src/algebra/category/CommRing/colimits.lean
89c8540efead3b1646a1fff4f1805328d0273fc3
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
11,903
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.category.CommRing.basic import category_theory.limits.limits /-! # The category of commutative rings has all colimits. This file uses a "pre-automated" approach, just as for `Mon/colimits.lean`. It is a very uniform approach, that conceivably could be synthesised directly by a tactic that analyses the shape of `comm_ring` and `ring_hom`. -/ universes u v open category_theory open category_theory.limits -- [ROBOT VOICE]: -- You should pretend for now that this file was automatically generated. -- It follows the same template as colimits in Mon. -- Note that this means this file does not meet documentation standards. /- `#print comm_ring` says: structure comm_ring : Type u → Type u fields: comm_ring.zero : Π (α : Type u) [c : comm_ring α], α comm_ring.one : Π (α : Type u) [c : comm_ring α], α comm_ring.neg : Π {α : Type u} [c : comm_ring α], α → α comm_ring.add : Π {α : Type u} [c : comm_ring α], α → α → α comm_ring.mul : Π {α : Type u} [c : comm_ring α], α → α → α comm_ring.zero_add : ∀ {α : Type u} [c : comm_ring α] (a : α), 0 + a = a comm_ring.add_zero : ∀ {α : Type u} [c : comm_ring α] (a : α), a + 0 = a comm_ring.one_mul : ∀ {α : Type u} [c : comm_ring α] (a : α), 1 * a = a comm_ring.mul_one : ∀ {α : Type u} [c : comm_ring α] (a : α), a * 1 = a comm_ring.add_left_neg : ∀ {α : Type u} [c : comm_ring α] (a : α), -a + a = 0 comm_ring.add_comm : ∀ {α : Type u} [c : comm_ring α] (a b : α), a + b = b + a comm_ring.mul_comm : ∀ {α : Type u} [c : comm_ring α] (a b : α), a * b = b * a comm_ring.add_assoc : ∀ {α : Type u} [c : comm_ring α] (a b c_1 : α), a + b + c_1 = a + (b + c_1) comm_ring.mul_assoc : ∀ {α : Type u} [c : comm_ring α] (a b c_1 : α), a * b * c_1 = a * (b * c_1) comm_ring.left_distrib : ∀ {α : Type u} [c : comm_ring α] (a b c_1 : α), a * (b + c_1) = a * b + a * c_1 comm_ring.right_distrib : ∀ {α : Type u} [c : comm_ring α] (a b c_1 : α), (a + b) * c_1 = a * c_1 + b * c_1 -/ namespace CommRing.colimits variables {J : Type v} [small_category J] (F : J ⥤ CommRing.{v}) inductive prequotient -- There's always `of` | of : Π (j : J) (x : F.obj j), prequotient -- Then one generator for each operation | zero {} : prequotient | one {} : prequotient | neg : prequotient → prequotient | add : prequotient → prequotient → prequotient | mul : prequotient → prequotient → prequotient open prequotient inductive relation : prequotient F → prequotient F → Prop -- Make it an equivalence relation: | refl : Π (x), relation x x | symm : Π (x y) (h : relation x y), relation y x | trans : Π (x y z) (h : relation x y) (k : relation y z), relation x z -- There's always a `map` relation | map : Π (j j' : J) (f : j ⟶ j') (x : F.obj j), relation (of j' (F.map f x)) (of j x) -- Then one relation per operation, describing the interaction with `of` | zero : Π (j), relation (of j 0) zero | one : Π (j), relation (of j 1) one | neg : Π (j) (x : F.obj j), relation (of j (-x)) (neg (of j x)) | add : Π (j) (x y : F.obj j), relation (of j (x + y)) (add (of j x) (of j y)) | mul : Π (j) (x y : F.obj j), relation (of j (x * y)) (mul (of j x) (of j y)) -- Then one relation per argument of each operation | neg_1 : Π (x x') (r : relation x x'), relation (neg x) (neg x') | add_1 : Π (x x' y) (r : relation x x'), relation (add x y) (add x' y) | add_2 : Π (x y y') (r : relation y y'), relation (add x y) (add x y') | mul_1 : Π (x x' y) (r : relation x x'), relation (mul x y) (mul x' y) | mul_2 : Π (x y y') (r : relation y y'), relation (mul x y) (mul x y') -- And one relation per axiom | zero_add : Π (x), relation (add zero x) x | add_zero : Π (x), relation (add x zero) x | one_mul : Π (x), relation (mul one x) x | mul_one : Π (x), relation (mul x one) x | add_left_neg : Π (x), relation (add (neg x) x) zero | add_comm : Π (x y), relation (add x y) (add y x) | mul_comm : Π (x y), relation (mul x y) (mul y x) | add_assoc : Π (x y z), relation (add (add x y) z) (add x (add y z)) | mul_assoc : Π (x y z), relation (mul (mul x y) z) (mul x (mul y z)) | left_distrib : Π (x y z), relation (mul x (add y z)) (add (mul x y) (mul x z)) | right_distrib : Π (x y z), relation (mul (add x y) z) (add (mul x z) (mul y z)) def colimit_setoid : setoid (prequotient F) := { r := relation F, iseqv := ⟨relation.refl, relation.symm, relation.trans⟩ } attribute [instance] colimit_setoid def colimit_type : Type v := quotient (colimit_setoid F) instance : comm_ring (colimit_type F) := { zero := begin exact quot.mk _ zero end, one := begin exact quot.mk _ one end, neg := begin fapply @quot.lift, { intro x, exact quot.mk _ (neg x) }, { intros x x' r, apply quot.sound, exact relation.neg_1 _ _ r }, end, add := begin fapply @quot.lift _ _ ((colimit_type F) → (colimit_type F)), { intro x, fapply @quot.lift, { intro y, exact quot.mk _ (add x y) }, { intros y y' r, apply quot.sound, exact relation.add_2 _ _ _ r } }, { intros x x' r, funext y, induction y, dsimp, apply quot.sound, { exact relation.add_1 _ _ _ r }, { refl } }, end, mul := begin fapply @quot.lift _ _ ((colimit_type F) → (colimit_type F)), { intro x, fapply @quot.lift, { intro y, exact quot.mk _ (mul x y) }, { intros y y' r, apply quot.sound, exact relation.mul_2 _ _ _ r } }, { intros x x' r, funext y, induction y, dsimp, apply quot.sound, { exact relation.mul_1 _ _ _ r }, { refl } }, end, zero_add := λ x, begin induction x, dsimp, apply quot.sound, apply relation.zero_add, refl, end, add_zero := λ x, begin induction x, dsimp, apply quot.sound, apply relation.add_zero, refl, end, one_mul := λ x, begin induction x, dsimp, apply quot.sound, apply relation.one_mul, refl, end, mul_one := λ x, begin induction x, dsimp, apply quot.sound, apply relation.mul_one, refl, end, add_left_neg := λ x, begin induction x, dsimp, apply quot.sound, apply relation.add_left_neg, refl, end, add_comm := λ x y, begin induction x, induction y, dsimp, apply quot.sound, apply relation.add_comm, refl, refl, end, mul_comm := λ x y, begin induction x, induction y, dsimp, apply quot.sound, apply relation.mul_comm, refl, refl, end, add_assoc := λ x y z, begin induction x, induction y, induction z, dsimp, apply quot.sound, apply relation.add_assoc, refl, refl, refl, end, mul_assoc := λ x y z, begin induction x, induction y, induction z, dsimp, apply quot.sound, apply relation.mul_assoc, refl, refl, refl, end, left_distrib := λ x y z, begin induction x, induction y, induction z, dsimp, apply quot.sound, apply relation.left_distrib, refl, refl, refl, end, right_distrib := λ x y z, begin induction x, induction y, induction z, dsimp, apply quot.sound, apply relation.right_distrib, refl, refl, refl, end, } @[simp] lemma quot_zero : quot.mk setoid.r zero = (0 : colimit_type F) := rfl @[simp] lemma quot_one : quot.mk setoid.r one = (1 : colimit_type F) := rfl @[simp] lemma quot_neg (x) : quot.mk setoid.r (neg x) = (-(quot.mk setoid.r x) : colimit_type F) := rfl @[simp] lemma quot_add (x y) : quot.mk setoid.r (add x y) = ((quot.mk setoid.r x) + (quot.mk setoid.r y) : colimit_type F) := rfl @[simp] lemma quot_mul (x y) : quot.mk setoid.r (mul x y) = ((quot.mk setoid.r x) * (quot.mk setoid.r y) : colimit_type F) := rfl def colimit : CommRing := CommRing.of (colimit_type F) def cocone_fun (j : J) (x : F.obj j) : colimit_type F := quot.mk _ (of j x) def cocone_morphism (j : J) : F.obj j ⟶ colimit F := { to_fun := cocone_fun F j, map_one' := by apply quot.sound; apply relation.one, map_mul' := by intros; apply quot.sound; apply relation.mul, map_zero' := by apply quot.sound; apply relation.zero, map_add' := by intros; apply quot.sound; apply relation.add } @[simp] lemma cocone_naturality {j j' : J} (f : j ⟶ j') : F.map f ≫ (cocone_morphism F j') = cocone_morphism F j := begin ext, apply quot.sound, apply relation.map, end @[simp] lemma cocone_naturality_components (j j' : J) (f : j ⟶ j') (x : F.obj j): (cocone_morphism F j') (F.map f x) = (cocone_morphism F j) x := by { rw ←cocone_naturality F f, refl } def colimit_cocone : cocone F := { X := colimit F, ι := { app := cocone_morphism F } }. @[simp] def desc_fun_lift (s : cocone F) : prequotient F → s.X | (of j x) := (s.ι.app j) x | zero := 0 | one := 1 | (neg x) := -(desc_fun_lift x) | (add x y) := desc_fun_lift x + desc_fun_lift y | (mul x y) := desc_fun_lift x * desc_fun_lift y def desc_fun (s : cocone F) : colimit_type F → s.X := begin fapply quot.lift, { exact desc_fun_lift F s }, { intros x y r, induction r; try { dsimp }, -- refl { refl }, -- symm { exact r_ih.symm }, -- trans { exact eq.trans r_ih_h r_ih_k }, -- map { rw cocone.naturality_concrete, }, -- zero { erw is_ring_hom.map_zero ⇑((s.ι).app r), refl }, -- one { erw is_ring_hom.map_one ⇑((s.ι).app r), refl }, -- neg { rw is_ring_hom.map_neg ⇑((s.ι).app r_j) }, -- add { rw is_ring_hom.map_add ⇑((s.ι).app r_j) }, -- mul { rw is_ring_hom.map_mul ⇑((s.ι).app r_j) }, -- neg_1 { rw r_ih, }, -- add_1 { rw r_ih, }, -- add_2 { rw r_ih, }, -- mul_1 { rw r_ih, }, -- mul_2 { rw r_ih, }, -- zero_add { rw zero_add, }, -- add_zero { rw add_zero, }, -- one_mul { rw one_mul, }, -- mul_one { rw mul_one, }, -- add_left_neg { rw add_left_neg, }, -- add_comm { rw add_comm, }, -- mul_comm { rw mul_comm, }, -- add_assoc { rw add_assoc, }, -- mul_assoc { rw mul_assoc, }, -- left_distrib { rw left_distrib, }, -- right_distrib { rw right_distrib, }, } end @[simp] def desc_morphism (s : cocone F) : colimit F ⟶ s.X := { to_fun := desc_fun F s, map_one' := rfl, map_zero' := rfl, map_add' := λ x y, by { induction x; induction y; refl }, map_mul' := λ x y, by { induction x; induction y; refl }, } def colimit_is_colimit : is_colimit (colimit_cocone F) := { desc := λ s, desc_morphism F s, uniq' := λ s m w, begin ext, induction x, induction x, { have w' := congr_fun (congr_arg (λ f : F.obj x_j ⟶ s.X, (f : F.obj x_j → s.X)) (w x_j)) x_x, erw w', refl, }, { simp only [desc_morphism, quot_zero], erw is_ring_hom.map_zero ⇑m, refl, }, { simp only [desc_morphism, quot_one], erw is_ring_hom.map_one ⇑m, refl, }, { simp only [desc_morphism, quot_neg], erw is_ring_hom.map_neg ⇑m, rw [x_ih], refl, }, { simp only [desc_morphism, quot_add], erw is_ring_hom.map_add ⇑m, rw [x_ih_a, x_ih_a_1], refl, }, { simp only [desc_morphism, quot_mul], erw is_ring_hom.map_mul ⇑m, rw [x_ih_a, x_ih_a_1], refl, }, refl end }. instance has_colimits_CommRing : has_colimits.{v} CommRing.{v} := { has_colimits_of_shape := λ J 𝒥, { has_colimit := λ F, by exactI { cocone := colimit_cocone F, is_colimit := colimit_is_colimit F } } } end CommRing.colimits
08b4c248b8e39d5d7577dfeac1975bc1bf039805
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/def4.lean
9e7e262ac85a19185b1969865130ab57c9be8561
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
265
lean
universe variable u section parameter (A : Type u) definition f : A → A := λ x, x check f check f (0:nat) -- error parameter {A} definition g : A → A := λ x, x check g check g (0:nat) -- error end check f check f _ (0:nat) check g 0
f3075526d4a93b051b6a57bf99fa3fd6b763adba
b7f22e51856f4989b970961f794f1c435f9b8f78
/hott/homotopy/homotopy_group.hlean
d6953bfc1e1c8c72c2a403fbd4120e63bbd447bc
[ "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
11,659
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, Clive Newstead -/ import .LES_of_homotopy_groups .sphere .complex_hopf open eq is_trunc trunc_index pointed algebra trunc nat is_conn fiber pointed unit namespace is_trunc -- Lemma 8.3.1 theorem trivial_homotopy_group_of_is_trunc (A : Type*) {n k : ℕ} [is_trunc n A] (H : n < k) : is_contr (π[k] A) := begin apply is_trunc_trunc_of_is_trunc, apply is_contr_loop_of_is_trunc, apply @is_trunc_of_le A n _, apply trunc_index.le_of_succ_le_succ, rewrite [succ_sub_two_succ k], exact of_nat_le_of_nat H, end theorem trivial_ghomotopy_group_of_is_trunc (A : Type*) (n k : ℕ) [is_trunc n A] (H : n ≤ k) : is_contr (πg[k+1] A) := trivial_homotopy_group_of_is_trunc A (lt_succ_of_le H) -- Lemma 8.3.2 theorem trivial_homotopy_group_of_is_conn (A : Type*) {k n : ℕ} (H : k ≤ n) [is_conn n A] : is_contr (π[k] A) := begin have H3 : is_contr (ptrunc k A), from is_conn_of_le A (of_nat_le_of_nat H), have H4 : is_contr (Ω[k](ptrunc k A)), from !is_trunc_loop_of_is_trunc, apply is_trunc_equiv_closed_rev, { apply equiv_of_pequiv (homotopy_group_pequiv_loop_ptrunc k A)} end -- Corollary 8.3.3 section open sphere sphere.ops sphere_index theorem homotopy_group_sphere_le (n k : ℕ) (H : k < n) : is_contr (π[k] (S* n)) := begin cases n with n, { exfalso, apply not_lt_zero, exact H}, { have H2 : k ≤ n, from le_of_lt_succ H, apply @(trivial_homotopy_group_of_is_conn _ H2) } end end theorem is_contr_HG_fiber_of_is_connected {A B : Type*} (k n : ℕ) (f : A →* B) [H : is_conn_fun n f] (H2 : k ≤ n) : is_contr (π[k] (pfiber f)) := @(trivial_homotopy_group_of_is_conn (pfiber f) H2) (H pt) theorem homotopy_group_trunc_of_le (A : Type*) (n k : ℕ) (H : k ≤ n) : π[k] (ptrunc n A) ≃* π[k] A := begin refine !homotopy_group_pequiv_loop_ptrunc ⬝e* _, refine loopn_pequiv_loopn _ (ptrunc_ptrunc_pequiv_left _ _) ⬝e* _, exact of_nat_le_of_nat H, exact !homotopy_group_pequiv_loop_ptrunc⁻¹ᵉ*, end /- Corollaries of the LES of homotopy groups -/ local attribute comm_group.to_group [coercion] local attribute is_equiv_tinverse [instance] open prod chain_complex group fin equiv function is_equiv lift /- Because of the construction of the LES this proof only gives us this result when A and B live in the same universe (because Lean doesn't have universe cumulativity). However, below we also proof that it holds for A and B in arbitrary universes. -/ theorem is_equiv_π_of_is_connected'.{u} {A B : pType.{u}} {n k : ℕ} (f : A →* B) (H2 : k ≤ n) [H : is_conn_fun n f] : is_equiv (π→[k] f) := begin cases k with k, { /- k = 0 -/ change (is_equiv (trunc_functor 0 f)), apply is_equiv_trunc_functor_of_is_conn_fun, refine is_conn_fun_of_le f (zero_le_of_nat n)}, { /- k > 0 -/ have H2' : k ≤ n, from le.trans !self_le_succ H2, exact @is_equiv_of_trivial _ (LES_of_homotopy_groups f) _ (is_exact_LES_of_homotopy_groups f (k, 2)) (is_exact_LES_of_homotopy_groups f (succ k, 0)) (@is_contr_HG_fiber_of_is_connected A B k n f H H2') (@is_contr_HG_fiber_of_is_connected A B (succ k) n f H H2) (@pgroup_of_group _ (group_LES_of_homotopy_groups f k 0) idp) (@pgroup_of_group _ (group_LES_of_homotopy_groups f k 1) idp) (homomorphism.struct (homomorphism_LES_of_homotopy_groups_fun f (k, 0)))}, end theorem is_equiv_π_of_is_connected.{u v} {A : pType.{u}} {B : pType.{v}} {n k : ℕ} (f : A →* B) (H2 : k ≤ n) [H : is_conn_fun n f] : is_equiv (π→[k] f) := begin have π→[k] pdown.{v u} ∘* π→[k] (plift_functor f) ∘* π→[k] pup.{u v} ~* π→[k] f, begin refine pwhisker_left _ !homotopy_group_functor_compose⁻¹* ⬝* _, refine !homotopy_group_functor_compose⁻¹* ⬝* _, apply homotopy_group_functor_phomotopy, apply plift_functor_phomotopy end, have π→[k] pdown.{v u} ∘ π→[k] (plift_functor f) ∘ π→[k] pup.{u v} ~ π→[k] f, from this, apply is_equiv.homotopy_closed, rotate 1, { exact this}, { do 2 apply is_equiv_compose, { apply is_equiv_homotopy_group_functor, apply to_is_equiv !equiv_lift}, { refine @(is_equiv_π_of_is_connected' _ H2) _, apply is_conn_fun_lift_functor}, { apply is_equiv_homotopy_group_functor, apply to_is_equiv !equiv_lift⁻¹ᵉ}} end definition π_equiv_π_of_is_connected {A B : Type*} {n k : ℕ} (f : A →* B) (H2 : k ≤ n) [H : is_conn_fun n f] : π[k] A ≃* π[k] B := pequiv_of_pmap (π→[k] f) (is_equiv_π_of_is_connected f H2) -- TODO: prove this for A and B in different universe levels theorem is_surjective_π_of_is_connected.{u} {A B : pType.{u}} (n : ℕ) (f : A →* B) [H : is_conn_fun n f] : is_surjective (π→[n + 1] f) := @is_surjective_of_trivial _ (LES_of_homotopy_groups f) _ (is_exact_LES_of_homotopy_groups f (n, 2)) (@is_contr_HG_fiber_of_is_connected A B n n f H !le.refl) /- Theorem 8.8.3: Whitehead's principle and its corollaries -/ definition whitehead_principle (n : ℕ₋₂) {A B : Type} [HA : is_trunc n A] [HB : is_trunc n B] (f : A → B) (H' : is_equiv (trunc_functor 0 f)) (H : Πa k, is_equiv (π→[k + 1] (pmap_of_map f a))) : is_equiv f := begin revert A B HA HB f H' H, induction n with n IH: intros, { apply is_equiv_of_is_contr}, have Πa, is_equiv (Ω→ (pmap_of_map f a)), begin intro a, apply IH, do 2 (esimp; exact _), { rexact H a 0}, intro p k, have is_equiv (π→[k + 1] (Ω→(pmap_of_map f a))), from is_equiv_homotopy_group_functor_ap1 (k+1) (pmap_of_map f a), have Π(b : A) (p : a = b), is_equiv (pmap.to_fun (π→[k + 1] (pmap_of_map (ap f) p))), begin intro b p, induction p, apply is_equiv.homotopy_closed, exact this, refine homotopy_group_functor_phomotopy _ _, apply ap1_pmap_of_map end, have is_equiv (homotopy_group_pequiv _ (pequiv_of_eq_pt (!idp_con⁻¹ : ap f p = Ω→ (pmap_of_map f a) p)) ∘ pmap.to_fun (π→[k + 1] (pmap_of_map (ap f) p))), begin apply is_equiv_compose, exact this a p, end, apply is_equiv.homotopy_closed, exact this, refine !homotopy_group_functor_compose⁻¹* ⬝* _, apply homotopy_group_functor_phomotopy, fapply phomotopy.mk, { esimp, intro q, refine !idp_con⁻¹}, { esimp, refine !idp_con⁻¹}, end, apply is_equiv_of_is_equiv_ap1_of_is_equiv_trunc end definition whitehead_principle_pointed (n : ℕ₋₂) {A B : Type*} [HA : is_trunc n A] [HB : is_trunc n B] [is_conn 0 A] (f : A →* B) (H : Πk, is_equiv (π→[k] f)) : is_equiv f := begin apply whitehead_principle n, rexact H 0, intro a k, revert a, apply is_conn.elim -1, have is_equiv (π→[k + 1] (pointed_eta_pequiv B ⬝e* (pequiv_of_eq_pt (respect_pt f))⁻¹ᵉ*) ∘* π→[k + 1] f ∘* π→[k + 1] (pointed_eta_pequiv A)⁻¹ᵉ*), begin apply is_equiv_compose (π→[k + 1] (pointed_eta_pequiv B ⬝e* (pequiv_of_eq_pt (respect_pt f))⁻¹ᵉ*)), apply is_equiv_compose (π→[k + 1] f), all_goals apply is_equiv_homotopy_group_functor, end, refine @(is_equiv.homotopy_closed _) _ this _, apply to_homotopy, refine pwhisker_left _ !homotopy_group_functor_compose⁻¹* ⬝* _, refine !homotopy_group_functor_compose⁻¹* ⬝* _, apply homotopy_group_functor_phomotopy, apply phomotopy_pmap_of_map end open pointed.ops definition is_contr_of_trivial_homotopy (n : ℕ₋₂) (A : Type) [is_trunc n A] [is_conn 0 A] (H : Πk a, is_contr (π[k] (pointed.MK A a))) : is_contr A := begin fapply is_trunc_is_equiv_closed_rev, { exact λa, ⋆}, apply whitehead_principle n, { apply is_equiv_trunc_functor_of_is_conn_fun, apply is_conn_fun_to_unit_of_is_conn}, intro a k, apply @is_equiv_of_is_contr, refine trivial_homotopy_group_of_is_trunc _ !zero_lt_succ, end definition is_contr_of_trivial_homotopy_nat (n : ℕ) (A : Type) [is_trunc n A] [is_conn 0 A] (H : Πk a, k ≤ n → is_contr (π[k] (pointed.MK A a))) : is_contr A := begin apply is_contr_of_trivial_homotopy n, intro k a, apply @lt_ge_by_cases _ _ n k, { intro H', exact trivial_homotopy_group_of_is_trunc _ H'}, { intro H', exact H k a H'} end definition is_contr_of_trivial_homotopy_pointed (n : ℕ₋₂) (A : Type*) [is_trunc n A] (H : Πk, is_contr (π[k] A)) : is_contr A := begin have is_conn 0 A, proof H 0 qed, fapply is_contr_of_trivial_homotopy n A, intro k, apply is_conn.elim -1, cases A with A a, exact H k end definition is_contr_of_trivial_homotopy_nat_pointed (n : ℕ) (A : Type*) [is_trunc n A] (H : Πk, k ≤ n → is_contr (π[k] A)) : is_contr A := begin have is_conn 0 A, proof H 0 !zero_le qed, fapply is_contr_of_trivial_homotopy_nat n A, intro k a H', revert a, apply is_conn.elim -1, cases A with A a, exact H k H' end definition is_conn_fun_of_equiv_on_homotopy_groups.{u} (n : ℕ) {A B : Type.{u}} (f : A → B) [is_equiv (trunc_functor 0 f)] (H1 : Πa k, k ≤ n → is_equiv (homotopy_group_functor k (pmap_of_map f a))) (H2 : Πa, is_surjective (homotopy_group_functor (succ n) (pmap_of_map f a))) : is_conn_fun n f := have H2' : Πa k, k ≤ n → is_surjective (homotopy_group_functor (succ k) (pmap_of_map f a)), begin intro a k H, cases H with n' H', { apply H2}, { apply is_surjective_of_is_equiv, apply H1, exact succ_le_succ H'} end, have H3 : Πa, is_contr (ptrunc n (pfiber (pmap_of_map f a))), begin intro a, apply is_contr_of_trivial_homotopy_nat_pointed n, { intro k H, apply is_trunc_equiv_closed_rev, exact homotopy_group_ptrunc_of_le H _, rexact @is_contr_of_is_embedding_of_is_surjective +3ℕ (LES_of_homotopy_groups (pmap_of_map f a)) (k, 0) (is_exact_LES_of_homotopy_groups _ _) proof @(is_embedding_of_is_equiv _) (H1 a k H) qed proof (H2' a k H) qed} end, show Πb, is_contr (trunc n (fiber f b)), begin intro b, note p := right_inv (trunc_functor 0 f) (tr b), revert p, induction (trunc_functor 0 f)⁻¹ (tr b), esimp, intro p, induction !tr_eq_tr_equiv p with q, rewrite -q, exact H3 a end end is_trunc open is_trunc function /- applications to infty-connected types and maps -/ namespace is_conn definition is_conn_fun_inf_of_equiv_on_homotopy_groups.{u} {A B : Type.{u}} (f : A → B) [is_equiv (trunc_functor 0 f)] (H1 : Πa k, is_equiv (homotopy_group_functor k (pmap_of_map f a))) : is_conn_fun_inf f := begin apply is_conn_fun_inf.mk_nat, intro n, apply is_conn_fun_of_equiv_on_homotopy_groups, { intro a k H, exact H1 a k}, { intro a, apply is_surjective_of_is_equiv} end definition is_equiv_trunc_functor_of_is_conn_fun_inf.{u} (n : ℕ₋₂) {A B : Type.{u}} (f : A → B) [is_conn_fun_inf f] : is_equiv (trunc_functor n f) := _ definition is_equiv_homotopy_group_functor_of_is_conn_fun_inf.{u} {A B : pType.{u}} (f : A →* B) [is_conn_fun_inf f] (a : A) (k : ℕ) : is_equiv (homotopy_group_functor k f) := is_equiv_π_of_is_connected f (le.refl k) end is_conn
a994c28c056f03fc9c2333b6eea40c20e1c6afc1
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/preadditive/generator.lean
c096257eed802aea754f2084b603bc08c5bb3911
[ "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,551
lean
/- Copyright (c) 2022 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import category_theory.generator import category_theory.preadditive.yoneda.basic /-! # Separators in preadditive categories > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file contains characterizations of separating sets and objects that are valid in all preadditive categories. -/ universes v u open category_theory opposite namespace category_theory variables {C : Type u} [category.{v} C] [preadditive C] lemma preadditive.is_separating_iff (𝒢 : set C) : is_separating 𝒢 ↔ ∀ ⦃X Y : C⦄ (f : X ⟶ Y), (∀ (G ∈ 𝒢) (h : G ⟶ X), h ≫ f = 0) → f = 0 := ⟨λ h𝒢 X Y f hf, h𝒢 _ _ (by simpa only [limits.comp_zero] using hf), λ h𝒢 X Y f g hfg, sub_eq_zero.1 $ h𝒢 _ (by simpa only [preadditive.comp_sub, sub_eq_zero] using hfg)⟩ lemma preadditive.is_coseparating_iff (𝒢 : set C) : is_coseparating 𝒢 ↔ ∀ ⦃X Y : C⦄ (f : X ⟶ Y), (∀ (G ∈ 𝒢) (h : Y ⟶ G), f ≫ h = 0) → f = 0 := ⟨λ h𝒢 X Y f hf, h𝒢 _ _ (by simpa only [limits.zero_comp] using hf), λ h𝒢 X Y f g hfg, sub_eq_zero.1 $ h𝒢 _ (by simpa only [preadditive.sub_comp, sub_eq_zero] using hfg)⟩ lemma preadditive.is_separator_iff (G : C) : is_separator G ↔ ∀ ⦃X Y : C⦄ (f : X ⟶ Y), (∀ h : G ⟶ X, h ≫ f = 0) → f = 0 := ⟨λ hG X Y f hf, hG.def _ _ (by simpa only [limits.comp_zero] using hf), λ hG, (is_separator_def _).2 $ λ X Y f g hfg, sub_eq_zero.1 $ hG _ (by simpa only [preadditive.comp_sub, sub_eq_zero] using hfg)⟩ lemma preadditive.is_coseparator_iff (G : C) : is_coseparator G ↔ ∀ ⦃X Y : C⦄ (f : X ⟶ Y), (∀ h : Y ⟶ G, f ≫ h = 0) → f = 0 := ⟨λ hG X Y f hf, hG.def _ _ (by simpa only [limits.zero_comp] using hf), λ hG, (is_coseparator_def _).2 $ λ X Y f g hfg, sub_eq_zero.1 $ hG _ (by simpa only [preadditive.sub_comp, sub_eq_zero] using hfg)⟩ lemma is_separator_iff_faithful_preadditive_coyoneda (G : C) : is_separator G ↔ faithful (preadditive_coyoneda.obj (op G)) := begin rw [is_separator_iff_faithful_coyoneda_obj, ← whiskering_preadditive_coyoneda, functor.comp_obj, whiskering_right_obj_obj], exact ⟨λ h, by exactI faithful.of_comp _ (forget AddCommGroup), λ h, by exactI faithful.comp _ _⟩ end lemma is_separator_iff_faithful_preadditive_coyoneda_obj (G : C) : is_separator G ↔ faithful (preadditive_coyoneda_obj (op G)) := begin rw [is_separator_iff_faithful_preadditive_coyoneda, preadditive_coyoneda_obj_2], exact ⟨λ h, by exactI faithful.of_comp _ (forget₂ _ AddCommGroup.{v}), λ h, by exactI faithful.comp _ _⟩ end lemma is_coseparator_iff_faithful_preadditive_yoneda (G : C) : is_coseparator G ↔ faithful (preadditive_yoneda.obj G) := begin rw [is_coseparator_iff_faithful_yoneda_obj, ← whiskering_preadditive_yoneda, functor.comp_obj, whiskering_right_obj_obj], exact ⟨λ h, by exactI faithful.of_comp _ (forget AddCommGroup), λ h, by exactI faithful.comp _ _⟩ end lemma is_coseparator_iff_faithful_preadditive_yoneda_obj (G : C) : is_coseparator G ↔ faithful (preadditive_yoneda_obj G) := begin rw [is_coseparator_iff_faithful_preadditive_yoneda, preadditive_yoneda_obj_2], exact ⟨λ h, by exactI faithful.of_comp _ (forget₂ _ AddCommGroup.{v}), λ h, by exactI faithful.comp _ _⟩ end end category_theory
9e11936ba752039ba82af9cc76df3eda372c4aeb
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/finset/preimage.lean
9613410e4aa8a0d138ab03a338e01f347b3bbcf6
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
7,638
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.set.finite import Mathlib.algebra.big_operators.basic import Mathlib.PostPort universes u v u_1 x namespace Mathlib /-! # Preimage of a `finset` under an injective map. -/ namespace finset /-- Preimage of `s : finset β` under a map `f` injective of `f ⁻¹' s` as a `finset`. -/ def preimage {α : Type u} {β : Type v} (s : finset β) (f : α → β) (hf : set.inj_on f (f ⁻¹' ↑s)) : finset α := set.finite.to_finset sorry @[simp] theorem mem_preimage {α : Type u} {β : Type v} {f : α → β} {s : finset β} {hf : set.inj_on f (f ⁻¹' ↑s)} {x : α} : x ∈ preimage s f hf ↔ f x ∈ s := set.finite.mem_to_finset @[simp] theorem coe_preimage {α : Type u} {β : Type v} {f : α → β} (s : finset β) (hf : set.inj_on f (f ⁻¹' ↑s)) : ↑(preimage s f hf) = f ⁻¹' ↑s := set.finite.coe_to_finset (preimage._proof_1 s f hf) @[simp] theorem preimage_empty {α : Type u} {β : Type v} {f : α → β} : preimage ∅ f (eq.mpr (id (Eq.trans (Eq.trans (Eq.trans ((fun (f f_1 : α → β) (e_1 : f = f_1) (s s_1 : set α) (e_2 : s = s_1) => congr (congr_arg set.inj_on e_1) e_2) f f (Eq.refl f) (f ⁻¹' ↑∅) ∅ (Eq.trans ((fun (f f_1 : α → β) (e_1 : f = f_1) (s s_1 : set β) (e_2 : s = s_1) => congr (congr_arg set.preimage e_1) e_2) f f (Eq.refl f) ↑∅ ∅ coe_empty) set.preimage_empty)) (set.inj_on.equations._eqn_1 f ∅)) (forall_congr_eq fun (x₁ : α) => Eq.trans (imp_congr_eq (set.mem_empty_eq x₁) (Eq.trans (forall_congr_eq fun (x₂ : α) => Eq.trans (imp_congr_eq (set.mem_empty_eq x₂) (Eq.refl (f x₁ = f x₂ → x₁ = x₂))) (propext (forall_prop_of_false (iff.mpr not_false_iff True.intro)))) (propext forall_true_iff))) (propext (forall_prop_of_false (iff.mpr not_false_iff True.intro))))) (propext forall_true_iff))) trivial) = ∅ := sorry @[simp] theorem preimage_univ {α : Type u} {β : Type v} {f : α → β} [fintype α] [fintype β] (hf : set.inj_on f (f ⁻¹' ↑univ)) : preimage univ f hf = univ := sorry @[simp] theorem preimage_inter {α : Type u} {β : Type v} [DecidableEq α] [DecidableEq β] {f : α → β} {s : finset β} {t : finset β} (hs : set.inj_on f (f ⁻¹' ↑s)) (ht : set.inj_on f (f ⁻¹' ↑t)) : (preimage (s ∩ t) f fun (x₁ : α) (hx₁ : x₁ ∈ f ⁻¹' ↑(s ∩ t)) (x₂ : α) (hx₂ : x₂ ∈ f ⁻¹' ↑(s ∩ t)) => hs (mem_of_mem_inter_left hx₁) (mem_of_mem_inter_left hx₂)) = preimage s f hs ∩ preimage t f ht := sorry @[simp] theorem preimage_union {α : Type u} {β : Type v} [DecidableEq α] [DecidableEq β] {f : α → β} {s : finset β} {t : finset β} (hst : set.inj_on f (f ⁻¹' ↑(s ∪ t))) : preimage (s ∪ t) f hst = (preimage s f fun (x₁ : α) (hx₁ : x₁ ∈ f ⁻¹' ↑s) (x₂ : α) (hx₂ : x₂ ∈ f ⁻¹' ↑s) => hst (mem_union_left t hx₁) (mem_union_left t hx₂)) ∪ preimage t f fun (x₁ : α) (hx₁ : x₁ ∈ f ⁻¹' ↑t) (x₂ : α) (hx₂ : x₂ ∈ f ⁻¹' ↑t) => hst (mem_union_right s hx₁) (mem_union_right s hx₂) := sorry @[simp] theorem preimage_compl {α : Type u} {β : Type v} [DecidableEq α] [DecidableEq β] [fintype α] [fintype β] {f : α → β} (s : finset β) (hf : function.injective f) : preimage (sᶜ) f (function.injective.inj_on hf (f ⁻¹' ↑(sᶜ))) = (preimage s f (function.injective.inj_on hf (f ⁻¹' ↑s))ᶜ) := sorry theorem monotone_preimage {α : Type u} {β : Type v} {f : α → β} (h : function.injective f) : monotone fun (s : finset β) => preimage s f (function.injective.inj_on h (f ⁻¹' ↑s)) := fun (s t : finset β) (hst : s ≤ t) (x : α) (hx : x ∈ (fun (s : finset β) => preimage s f (function.injective.inj_on h (f ⁻¹' ↑s))) s) => iff.mpr mem_preimage (hst (iff.mp mem_preimage hx)) theorem image_subset_iff_subset_preimage {α : Type u} {β : Type v} [DecidableEq β] {f : α → β} {s : finset α} {t : finset β} (hf : set.inj_on f (f ⁻¹' ↑t)) : image f s ⊆ t ↔ s ⊆ preimage t f hf := sorry theorem map_subset_iff_subset_preimage {α : Type u} {β : Type v} {f : α ↪ β} {s : finset α} {t : finset β} : map f s ⊆ t ↔ s ⊆ preimage t (⇑f) (function.injective.inj_on (function.embedding.injective f) (⇑f ⁻¹' ↑t)) := sorry theorem image_preimage {α : Type u} {β : Type v} [DecidableEq β] (f : α → β) (s : finset β) [(x : β) → Decidable (x ∈ set.range f)] (hf : set.inj_on f (f ⁻¹' ↑s)) : image f (preimage s f hf) = filter (fun (x : β) => x ∈ set.range f) s := sorry theorem image_preimage_of_bij {α : Type u} {β : Type v} [DecidableEq β] (f : α → β) (s : finset β) (hf : set.bij_on f (f ⁻¹' ↑s) ↑s) : image f (preimage s f (set.bij_on.inj_on hf)) = s := sorry theorem sigma_preimage_mk {α : Type u} {β : α → Type u_1} [DecidableEq α] (s : finset (sigma fun (a : α) => β a)) (t : finset α) : (finset.sigma t fun (a : α) => preimage s (sigma.mk a) (function.injective.inj_on sigma_mk_injective (sigma.mk a ⁻¹' ↑s))) = filter (fun (a : sigma fun (a : α) => β a) => sigma.fst a ∈ t) s := sorry theorem sigma_preimage_mk_of_subset {α : Type u} {β : α → Type u_1} [DecidableEq α] (s : finset (sigma fun (a : α) => β a)) {t : finset α} (ht : image sigma.fst s ⊆ t) : (finset.sigma t fun (a : α) => preimage s (sigma.mk a) (function.injective.inj_on sigma_mk_injective (sigma.mk a ⁻¹' ↑s))) = s := sorry theorem sigma_image_fst_preimage_mk {α : Type u} {β : α → Type u_1} [DecidableEq α] (s : finset (sigma fun (a : α) => β a)) : (finset.sigma (image sigma.fst s) fun (a : α) => preimage s (sigma.mk a) (function.injective.inj_on sigma_mk_injective (sigma.mk a ⁻¹' ↑s))) = s := sigma_preimage_mk_of_subset s (subset.refl (image sigma.fst s)) theorem prod_preimage' {α : Type u} {β : Type v} {γ : Type x} [comm_monoid β] (f : α → γ) [decidable_pred fun (x : γ) => x ∈ set.range f] (s : finset γ) (hf : set.inj_on f (f ⁻¹' ↑s)) (g : γ → β) : (finset.prod (preimage s f hf) fun (x : α) => g (f x)) = finset.prod (filter (fun (x : γ) => x ∈ set.range f) s) fun (x : γ) => g x := sorry theorem prod_preimage {α : Type u} {β : Type v} {γ : Type x} [comm_monoid β] (f : α → γ) (s : finset γ) (hf : set.inj_on f (f ⁻¹' ↑s)) (g : γ → β) (hg : ∀ (x : γ), x ∈ s → ¬x ∈ set.range f → g x = 1) : (finset.prod (preimage s f hf) fun (x : α) => g (f x)) = finset.prod s fun (x : γ) => g x := sorry theorem sum_preimage_of_bij {α : Type u} {β : Type v} {γ : Type x} [add_comm_monoid β] (f : α → γ) (s : finset γ) (hf : set.bij_on f (f ⁻¹' ↑s) ↑s) (g : γ → β) : (finset.sum (preimage s f (set.bij_on.inj_on hf)) fun (x : α) => g (f x)) = finset.sum s fun (x : γ) => g x := sum_preimage f s (set.bij_on.inj_on hf) g fun (x : γ) (hxs : x ∈ s) (hxf : ¬x ∈ set.range f) => false.elim (hxf (set.bij_on.subset_range hf hxs))
b2263ee2185329a91e31b5b29f0d3d7e6235fa0e
bb31430994044506fa42fd667e2d556327e18dfe
/src/data/finset/locally_finite.lean
6e3cf7f7482239fabe3d37ee4a8fbcbbcc044c9b
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
30,010
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Yaël Dillies -/ import order.locally_finite import data.set.intervals.monoid /-! # Intervals as finsets This file provides basic results about all the `finset.Ixx`, which are defined in `order.locally_finite`. ## TODO This file was originally only about `finset.Ico a b` where `a b : ℕ`. No care has yet been taken to generalize these lemmas properly and many lemmas about `Icc`, `Ioc`, `Ioo` are missing. In general, what's to do is taking the lemmas in `data.x.intervals` and abstract away the concrete structure. Complete the API. See https://github.com/leanprover-community/mathlib/pull/14448#discussion_r906109235 for some ideas. -/ open function order_dual open_locale big_operators finset_interval variables {ι α : Type*} namespace finset section preorder variables [preorder α] section locally_finite_order variables [locally_finite_order α] {a a₁ a₂ b b₁ b₂ c x : α} @[simp] lemma nonempty_Icc : (Icc a b).nonempty ↔ a ≤ b := by rw [←coe_nonempty, coe_Icc, set.nonempty_Icc] @[simp] lemma nonempty_Ico : (Ico a b).nonempty ↔ a < b := by rw [←coe_nonempty, coe_Ico, set.nonempty_Ico] @[simp] lemma nonempty_Ioc : (Ioc a b).nonempty ↔ a < b := by rw [←coe_nonempty, coe_Ioc, set.nonempty_Ioc] @[simp] lemma nonempty_Ioo [densely_ordered α] : (Ioo a b).nonempty ↔ a < b := by rw [←coe_nonempty, coe_Ioo, set.nonempty_Ioo] @[simp] lemma Icc_eq_empty_iff : Icc a b = ∅ ↔ ¬a ≤ b := by rw [←coe_eq_empty, coe_Icc, set.Icc_eq_empty_iff] @[simp] lemma Ico_eq_empty_iff : Ico a b = ∅ ↔ ¬a < b := by rw [←coe_eq_empty, coe_Ico, set.Ico_eq_empty_iff] @[simp] lemma Ioc_eq_empty_iff : Ioc a b = ∅ ↔ ¬a < b := by rw [←coe_eq_empty, coe_Ioc, set.Ioc_eq_empty_iff] @[simp] lemma Ioo_eq_empty_iff [densely_ordered α] : Ioo a b = ∅ ↔ ¬a < b := by rw [←coe_eq_empty, coe_Ioo, set.Ioo_eq_empty_iff] alias Icc_eq_empty_iff ↔ _ Icc_eq_empty alias Ico_eq_empty_iff ↔ _ Ico_eq_empty alias Ioc_eq_empty_iff ↔ _ Ioc_eq_empty @[simp] lemma Ioo_eq_empty (h : ¬a < b) : Ioo a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x hx, h ((mem_Ioo.1 hx).1.trans (mem_Ioo.1 hx).2) @[simp] lemma Icc_eq_empty_of_lt (h : b < a) : Icc a b = ∅ := Icc_eq_empty h.not_le @[simp] lemma Ico_eq_empty_of_le (h : b ≤ a) : Ico a b = ∅ := Ico_eq_empty h.not_lt @[simp] lemma Ioc_eq_empty_of_le (h : b ≤ a) : Ioc a b = ∅ := Ioc_eq_empty h.not_lt @[simp] lemma Ioo_eq_empty_of_le (h : b ≤ a) : Ioo a b = ∅ := Ioo_eq_empty h.not_lt @[simp] lemma left_mem_Icc : a ∈ Icc a b ↔ a ≤ b := by simp only [mem_Icc, true_and, le_rfl] @[simp] lemma left_mem_Ico : a ∈ Ico a b ↔ a < b := by simp only [mem_Ico, true_and, le_refl] @[simp] lemma right_mem_Icc : b ∈ Icc a b ↔ a ≤ b := by simp only [mem_Icc, and_true, le_rfl] @[simp] lemma right_mem_Ioc : b ∈ Ioc a b ↔ a < b := by simp only [mem_Ioc, and_true, le_rfl] @[simp] lemma left_not_mem_Ioc : a ∉ Ioc a b := λ h, lt_irrefl _ (mem_Ioc.1 h).1 @[simp] lemma left_not_mem_Ioo : a ∉ Ioo a b := λ h, lt_irrefl _ (mem_Ioo.1 h).1 @[simp] lemma right_not_mem_Ico : b ∉ Ico a b := λ h, lt_irrefl _ (mem_Ico.1 h).2 @[simp] lemma right_not_mem_Ioo : b ∉ Ioo a b := λ h, lt_irrefl _ (mem_Ioo.1 h).2 lemma Icc_subset_Icc (ha : a₂ ≤ a₁) (hb : b₁ ≤ b₂) : Icc a₁ b₁ ⊆ Icc a₂ b₂ := by simpa [←coe_subset] using set.Icc_subset_Icc ha hb lemma Ico_subset_Ico (ha : a₂ ≤ a₁) (hb : b₁ ≤ b₂) : Ico a₁ b₁ ⊆ Ico a₂ b₂ := by simpa [←coe_subset] using set.Ico_subset_Ico ha hb lemma Ioc_subset_Ioc (ha : a₂ ≤ a₁) (hb : b₁ ≤ b₂) : Ioc a₁ b₁ ⊆ Ioc a₂ b₂ := by simpa [←coe_subset] using set.Ioc_subset_Ioc ha hb lemma Ioo_subset_Ioo (ha : a₂ ≤ a₁) (hb : b₁ ≤ b₂) : Ioo a₁ b₁ ⊆ Ioo a₂ b₂ := by simpa [←coe_subset] using set.Ioo_subset_Ioo ha hb lemma Icc_subset_Icc_left (h : a₁ ≤ a₂) : Icc a₂ b ⊆ Icc a₁ b := Icc_subset_Icc h le_rfl lemma Ico_subset_Ico_left (h : a₁ ≤ a₂) : Ico a₂ b ⊆ Ico a₁ b := Ico_subset_Ico h le_rfl lemma Ioc_subset_Ioc_left (h : a₁ ≤ a₂) : Ioc a₂ b ⊆ Ioc a₁ b := Ioc_subset_Ioc h le_rfl lemma Ioo_subset_Ioo_left (h : a₁ ≤ a₂) : Ioo a₂ b ⊆ Ioo a₁ b := Ioo_subset_Ioo h le_rfl lemma Icc_subset_Icc_right (h : b₁ ≤ b₂) : Icc a b₁ ⊆ Icc a b₂ := Icc_subset_Icc le_rfl h lemma Ico_subset_Ico_right (h : b₁ ≤ b₂) : Ico a b₁ ⊆ Ico a b₂ := Ico_subset_Ico le_rfl h lemma Ioc_subset_Ioc_right (h : b₁ ≤ b₂) : Ioc a b₁ ⊆ Ioc a b₂ := Ioc_subset_Ioc le_rfl h lemma Ioo_subset_Ioo_right (h : b₁ ≤ b₂) : Ioo a b₁ ⊆ Ioo a b₂ := Ioo_subset_Ioo le_rfl h lemma Ico_subset_Ioo_left (h : a₁ < a₂) : Ico a₂ b ⊆ Ioo a₁ b := by { rw [←coe_subset, coe_Ico, coe_Ioo], exact set.Ico_subset_Ioo_left h } lemma Ioc_subset_Ioo_right (h : b₁ < b₂) : Ioc a b₁ ⊆ Ioo a b₂ := by { rw [←coe_subset, coe_Ioc, coe_Ioo], exact set.Ioc_subset_Ioo_right h } lemma Icc_subset_Ico_right (h : b₁ < b₂) : Icc a b₁ ⊆ Ico a b₂ := by { rw [←coe_subset, coe_Icc, coe_Ico], exact set.Icc_subset_Ico_right h } lemma Ioo_subset_Ico_self : Ioo a b ⊆ Ico a b := by { rw [←coe_subset, coe_Ioo, coe_Ico], exact set.Ioo_subset_Ico_self } lemma Ioo_subset_Ioc_self : Ioo a b ⊆ Ioc a b := by { rw [←coe_subset, coe_Ioo, coe_Ioc], exact set.Ioo_subset_Ioc_self } lemma Ico_subset_Icc_self : Ico a b ⊆ Icc a b := by { rw [←coe_subset, coe_Ico, coe_Icc], exact set.Ico_subset_Icc_self } lemma Ioc_subset_Icc_self : Ioc a b ⊆ Icc a b := by { rw [←coe_subset, coe_Ioc, coe_Icc], exact set.Ioc_subset_Icc_self } lemma Ioo_subset_Icc_self : Ioo a b ⊆ Icc a b := Ioo_subset_Ico_self.trans Ico_subset_Icc_self lemma Icc_subset_Icc_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Icc a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ := by rw [←coe_subset, coe_Icc, coe_Icc, set.Icc_subset_Icc_iff h₁] lemma Icc_subset_Ioo_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ioo a₂ b₂ ↔ a₂ < a₁ ∧ b₁ < b₂ := by rw [←coe_subset, coe_Icc, coe_Ioo, set.Icc_subset_Ioo_iff h₁] lemma Icc_subset_Ico_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ico a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ < b₂ := by rw [←coe_subset, coe_Icc, coe_Ico, set.Icc_subset_Ico_iff h₁] lemma Icc_subset_Ioc_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ioc a₂ b₂ ↔ a₂ < a₁ ∧ b₁ ≤ b₂ := (Icc_subset_Ico_iff h₁.dual).trans and.comm --TODO: `Ico_subset_Ioo_iff`, `Ioc_subset_Ioo_iff` lemma Icc_ssubset_Icc_left (hI : a₂ ≤ b₂) (ha : a₂ < a₁) (hb : b₁ ≤ b₂) : Icc a₁ b₁ ⊂ Icc a₂ b₂ := by { rw [←coe_ssubset, coe_Icc, coe_Icc], exact set.Icc_ssubset_Icc_left hI ha hb } lemma Icc_ssubset_Icc_right (hI : a₂ ≤ b₂) (ha : a₂ ≤ a₁) (hb : b₁ < b₂) : Icc a₁ b₁ ⊂ Icc a₂ b₂ := by { rw [←coe_ssubset, coe_Icc, coe_Icc], exact set.Icc_ssubset_Icc_right hI ha hb } variables (a) @[simp] lemma Ico_self : Ico a a = ∅ := Ico_eq_empty $ lt_irrefl _ @[simp] lemma Ioc_self : Ioc a a = ∅ := Ioc_eq_empty $ lt_irrefl _ @[simp] lemma Ioo_self : Ioo a a = ∅ := Ioo_eq_empty $ lt_irrefl _ variables {a} /-- A set with upper and lower bounds in a locally finite order is a fintype -/ def _root_.set.fintype_of_mem_bounds {s : set α} [decidable_pred (∈ s)] (ha : a ∈ lower_bounds s) (hb : b ∈ upper_bounds s) : fintype s := set.fintype_subset (set.Icc a b) $ λ x hx, ⟨ha hx, hb hx⟩ lemma _root_.bdd_below.finite_of_bdd_above {s : set α} (h₀ : bdd_below s) (h₁ : bdd_above s) : s.finite := let ⟨a, ha⟩ := h₀, ⟨b, hb⟩ := h₁ in by { classical, exact ⟨set.fintype_of_mem_bounds ha hb⟩ } section filter lemma Ico_filter_lt_of_le_left [decidable_pred (< c)] (hca : c ≤ a) : (Ico a b).filter (< c) = ∅ := filter_false_of_mem (λ x hx, (hca.trans (mem_Ico.1 hx).1).not_lt) lemma Ico_filter_lt_of_right_le [decidable_pred (< c)] (hbc : b ≤ c) : (Ico a b).filter (< c) = Ico a b := filter_true_of_mem (λ x hx, (mem_Ico.1 hx).2.trans_le hbc) lemma Ico_filter_lt_of_le_right [decidable_pred (< c)] (hcb : c ≤ b) : (Ico a b).filter (< c) = Ico a c := begin ext x, rw [mem_filter, mem_Ico, mem_Ico, and.right_comm], exact and_iff_left_of_imp (λ h, h.2.trans_le hcb), end lemma Ico_filter_le_of_le_left {a b c : α} [decidable_pred ((≤) c)] (hca : c ≤ a) : (Ico a b).filter ((≤) c) = Ico a b := filter_true_of_mem (λ x hx, hca.trans (mem_Ico.1 hx).1) lemma Ico_filter_le_of_right_le {a b : α} [decidable_pred ((≤) b)] : (Ico a b).filter ((≤) b) = ∅ := filter_false_of_mem (λ x hx, (mem_Ico.1 hx).2.not_le) lemma Ico_filter_le_of_left_le {a b c : α} [decidable_pred ((≤) c)] (hac : a ≤ c) : (Ico a b).filter ((≤) c) = Ico c b := begin ext x, rw [mem_filter, mem_Ico, mem_Ico, and_comm, and.left_comm], exact and_iff_right_of_imp (λ h, hac.trans h.1), end lemma Icc_filter_lt_of_lt_right {a b c : α} [decidable_pred (< c)] (h : b < c) : (Icc a b).filter (< c) = Icc a b := (finset.filter_eq_self _).2 (λ x hx, lt_of_le_of_lt (mem_Icc.1 hx).2 h) lemma Ioc_filter_lt_of_lt_right {a b c : α} [decidable_pred (< c)] (h : b < c) : (Ioc a b).filter (< c) = Ioc a b := (finset.filter_eq_self _).2 (λ x hx, lt_of_le_of_lt (mem_Ioc.1 hx).2 h) lemma Iic_filter_lt_of_lt_right {α} [preorder α] [locally_finite_order_bot α] {a c : α} [decidable_pred (< c)] (h : a < c) : (Iic a).filter (< c) = Iic a := (finset.filter_eq_self _).2 (λ x hx, lt_of_le_of_lt (mem_Iic.1 hx) h) variables (a b) [fintype α] lemma filter_lt_lt_eq_Ioo [decidable_pred (λ j, a < j ∧ j < b)] : univ.filter (λ j, a < j ∧ j < b) = Ioo a b := by { ext, simp } lemma filter_lt_le_eq_Ioc [decidable_pred (λ j, a < j ∧ j ≤ b)] : univ.filter (λ j, a < j ∧ j ≤ b) = Ioc a b := by { ext, simp } lemma filter_le_lt_eq_Ico [decidable_pred (λ j, a ≤ j ∧ j < b)] : univ.filter (λ j, a ≤ j ∧ j < b) = Ico a b := by { ext, simp } lemma filter_le_le_eq_Icc [decidable_pred (λ j, a ≤ j ∧ j ≤ b)] : univ.filter (λ j, a ≤ j ∧ j ≤ b) = Icc a b := by { ext, simp } end filter section locally_finite_order_top variables [locally_finite_order_top α] lemma Icc_subset_Ici_self : Icc a b ⊆ Ici a := by simpa [←coe_subset] using set.Icc_subset_Ici_self lemma Ico_subset_Ici_self : Ico a b ⊆ Ici a := by simpa [←coe_subset] using set.Ico_subset_Ici_self lemma Ioc_subset_Ioi_self : Ioc a b ⊆ Ioi a := by simpa [←coe_subset] using set.Ioc_subset_Ioi_self lemma Ioo_subset_Ioi_self : Ioo a b ⊆ Ioi a := by simpa [←coe_subset] using set.Ioo_subset_Ioi_self lemma Ioc_subset_Ici_self : Ioc a b ⊆ Ici a := Ioc_subset_Icc_self.trans Icc_subset_Ici_self lemma Ioo_subset_Ici_self : Ioo a b ⊆ Ici a := Ioo_subset_Ico_self.trans Ico_subset_Ici_self end locally_finite_order_top section locally_finite_order_bot variables [locally_finite_order_bot α] lemma Icc_subset_Iic_self : Icc a b ⊆ Iic b := by simpa [←coe_subset] using set.Icc_subset_Iic_self lemma Ioc_subset_Iic_self : Ioc a b ⊆ Iic b := by simpa [←coe_subset] using set.Ioc_subset_Iic_self lemma Ico_subset_Iio_self : Ico a b ⊆ Iio b := by simpa [←coe_subset] using set.Ico_subset_Iio_self lemma Ioo_subset_Iio_self : Ioo a b ⊆ Iio b := by simpa [←coe_subset] using set.Ioo_subset_Iio_self lemma Ico_subset_Iic_self : Ico a b ⊆ Iic b := Ico_subset_Icc_self.trans Icc_subset_Iic_self lemma Ioo_subset_Iic_self : Ioo a b ⊆ Iic b := Ioo_subset_Ioc_self.trans Ioc_subset_Iic_self end locally_finite_order_bot end locally_finite_order section locally_finite_order_top variables [locally_finite_order_top α] {a : α} lemma Ioi_subset_Ici_self : Ioi a ⊆ Ici a := by simpa [←coe_subset] using set.Ioi_subset_Ici_self lemma _root_.bdd_below.finite {s : set α} (hs : bdd_below s) : s.finite := let ⟨a, ha⟩ := hs in (Ici a).finite_to_set.subset $ λ x hx, mem_Ici.2 $ ha hx variables [fintype α] lemma filter_lt_eq_Ioi [decidable_pred ((<) a)] : univ.filter ((<) a) = Ioi a := by { ext, simp } lemma filter_le_eq_Ici [decidable_pred ((≤) a)] : univ.filter ((≤) a) = Ici a := by { ext, simp } end locally_finite_order_top section locally_finite_order_bot variables [locally_finite_order_bot α] {a : α} lemma Iio_subset_Iic_self : Iio a ⊆ Iic a := by simpa [←coe_subset] using set.Iio_subset_Iic_self lemma _root_.bdd_above.finite {s : set α} (hs : bdd_above s) : s.finite := hs.dual.finite variables [fintype α] lemma filter_gt_eq_Iio [decidable_pred (< a)] : univ.filter (< a) = Iio a := by { ext, simp } lemma filter_ge_eq_Iic [decidable_pred (≤ a)] : univ.filter (≤ a) = Iic a := by { ext, simp } end locally_finite_order_bot variables [locally_finite_order_top α] [locally_finite_order_bot α] lemma disjoint_Ioi_Iio (a : α) : disjoint (Ioi a) (Iio a) := disjoint_left.2 $ λ b hab hba, (mem_Ioi.1 hab).not_lt $ mem_Iio.1 hba end preorder section partial_order variables [partial_order α] [locally_finite_order α] {a b c : α} @[simp] lemma Icc_self (a : α) : Icc a a = {a} := by rw [←coe_eq_singleton, coe_Icc, set.Icc_self] @[simp] lemma Icc_eq_singleton_iff : Icc a b = {c} ↔ a = c ∧ b = c := by rw [←coe_eq_singleton, coe_Icc, set.Icc_eq_singleton_iff] lemma Ico_disjoint_Ico_consecutive (a b c : α) : disjoint (Ico a b) (Ico b c) := disjoint_left.2 $ λ x hab hbc, (mem_Ico.mp hab).2.not_le (mem_Ico.mp hbc).1 section decidable_eq variables [decidable_eq α] @[simp] lemma Icc_erase_left (a b : α) : (Icc a b).erase a = Ioc a b := by simp [←coe_inj] @[simp] lemma Icc_erase_right (a b : α) : (Icc a b).erase b = Ico a b := by simp [←coe_inj] @[simp] lemma Ico_erase_left (a b : α) : (Ico a b).erase a = Ioo a b := by simp [←coe_inj] @[simp] lemma Ioc_erase_right (a b : α) : (Ioc a b).erase b = Ioo a b := by simp [←coe_inj] @[simp] lemma Icc_diff_both (a b : α) : Icc a b \ {a, b} = Ioo a b := by simp [←coe_inj] @[simp] lemma Ico_insert_right (h : a ≤ b) : insert b (Ico a b) = Icc a b := by rw [←coe_inj, coe_insert, coe_Icc, coe_Ico, set.insert_eq, set.union_comm, set.Ico_union_right h] @[simp] lemma Ioc_insert_left (h : a ≤ b) : insert a (Ioc a b) = Icc a b := by rw [←coe_inj, coe_insert, coe_Ioc, coe_Icc, set.insert_eq, set.union_comm, set.Ioc_union_left h] @[simp] lemma Ioo_insert_left (h : a < b) : insert a (Ioo a b) = Ico a b := by rw [←coe_inj, coe_insert, coe_Ioo, coe_Ico, set.insert_eq, set.union_comm, set.Ioo_union_left h] @[simp] lemma Ioo_insert_right (h : a < b) : insert b (Ioo a b) = Ioc a b := by rw [←coe_inj, coe_insert, coe_Ioo, coe_Ioc, set.insert_eq, set.union_comm, set.Ioo_union_right h] @[simp] lemma Icc_diff_Ico_self (h : a ≤ b) : Icc a b \ Ico a b = {b} := by simp [←coe_inj, h] @[simp] lemma Icc_diff_Ioc_self (h : a ≤ b) : Icc a b \ Ioc a b = {a} := by simp [←coe_inj, h] @[simp] lemma Icc_diff_Ioo_self (h : a ≤ b) : Icc a b \ Ioo a b = {a, b} := by simp [←coe_inj, h] @[simp] lemma Ico_diff_Ioo_self (h : a < b) : Ico a b \ Ioo a b = {a} := by simp [←coe_inj, h] @[simp] lemma Ioc_diff_Ioo_self (h : a < b) : Ioc a b \ Ioo a b = {b} := by simp [←coe_inj, h] @[simp] lemma Ico_inter_Ico_consecutive (a b c : α) : Ico a b ∩ Ico b c = ∅ := (Ico_disjoint_Ico_consecutive a b c).eq_bot end decidable_eq -- Those lemmas are purposefully the other way around lemma Icc_eq_cons_Ico (h : a ≤ b) : Icc a b = (Ico a b).cons b right_not_mem_Ico := by { classical, rw [cons_eq_insert, Ico_insert_right h] } lemma Icc_eq_cons_Ioc (h : a ≤ b) : Icc a b = (Ioc a b).cons a left_not_mem_Ioc := by { classical, rw [cons_eq_insert, Ioc_insert_left h] } lemma Ico_filter_le_left {a b : α} [decidable_pred (≤ a)] (hab : a < b) : (Ico a b).filter (λ x, x ≤ a) = {a} := begin ext x, rw [mem_filter, mem_Ico, mem_singleton, and.right_comm, ←le_antisymm_iff, eq_comm], exact and_iff_left_of_imp (λ h, h.le.trans_lt hab), end lemma card_Ico_eq_card_Icc_sub_one (a b : α) : (Ico a b).card = (Icc a b).card - 1 := begin classical, by_cases h : a ≤ b, { rw [←Ico_insert_right h, card_insert_of_not_mem right_not_mem_Ico], exact (nat.add_sub_cancel _ _).symm }, { rw [Ico_eq_empty (λ h', h h'.le), Icc_eq_empty h, card_empty, zero_tsub] } end lemma card_Ioc_eq_card_Icc_sub_one (a b : α) : (Ioc a b).card = (Icc a b).card - 1 := @card_Ico_eq_card_Icc_sub_one αᵒᵈ _ _ _ _ lemma card_Ioo_eq_card_Ico_sub_one (a b : α) : (Ioo a b).card = (Ico a b).card - 1 := begin classical, by_cases h : a ≤ b, { obtain rfl | h' := h.eq_or_lt, { rw [Ioo_self, Ico_self, card_empty] }, rw [←Ioo_insert_left h', card_insert_of_not_mem left_not_mem_Ioo], exact (nat.add_sub_cancel _ _).symm }, { rw [Ioo_eq_empty (λ h', h h'.le), Ico_eq_empty (λ h', h h'.le), card_empty, zero_tsub] } end lemma card_Ioo_eq_card_Ioc_sub_one (a b : α) : (Ioo a b).card = (Ioc a b).card - 1 := @card_Ioo_eq_card_Ico_sub_one αᵒᵈ _ _ _ _ lemma card_Ioo_eq_card_Icc_sub_two (a b : α) : (Ioo a b).card = (Icc a b).card - 2 := by { rw [card_Ioo_eq_card_Ico_sub_one, card_Ico_eq_card_Icc_sub_one], refl } end partial_order section bounded_partial_order variables [partial_order α] section order_top variables [locally_finite_order_top α] @[simp] lemma Ici_erase [decidable_eq α] (a : α) : (Ici a).erase a = Ioi a := by { ext, simp_rw [finset.mem_erase, mem_Ici, mem_Ioi, lt_iff_le_and_ne, and_comm, ne_comm], } @[simp] lemma Ioi_insert [decidable_eq α] (a : α) : insert a (Ioi a) = Ici a := by { ext, simp_rw [finset.mem_insert, mem_Ici, mem_Ioi, le_iff_lt_or_eq, or_comm, eq_comm] } @[simp] lemma not_mem_Ioi_self {b : α} : b ∉ Ioi b := λ h, lt_irrefl _ (mem_Ioi.1 h) -- Purposefully written the other way around lemma Ici_eq_cons_Ioi (a : α) : Ici a = (Ioi a).cons a not_mem_Ioi_self := by { classical, rw [cons_eq_insert, Ioi_insert] } lemma card_Ioi_eq_card_Ici_sub_one (a : α) : (Ioi a).card = (Ici a).card - 1 := by rw [Ici_eq_cons_Ioi, card_cons, add_tsub_cancel_right] end order_top section order_bot variables [locally_finite_order_bot α] @[simp] lemma Iic_erase [decidable_eq α] (b : α) : (Iic b).erase b = Iio b := by { ext, simp_rw [finset.mem_erase, mem_Iic, mem_Iio, lt_iff_le_and_ne, and_comm] } @[simp] lemma Iio_insert [decidable_eq α] (b : α) : insert b (Iio b) = Iic b := by { ext, simp_rw [finset.mem_insert, mem_Iic, mem_Iio, le_iff_lt_or_eq, or_comm] } @[simp] lemma not_mem_Iio_self {b : α} : b ∉ Iio b := λ h, lt_irrefl _ (mem_Iio.1 h) -- Purposefully written the other way around lemma Iic_eq_cons_Iio (b : α) : Iic b = (Iio b).cons b not_mem_Iio_self := by { classical, rw [cons_eq_insert, Iio_insert] } lemma card_Iio_eq_card_Iic_sub_one (a : α) : (Iio a).card = (Iic a).card - 1 := by rw [Iic_eq_cons_Iio, card_cons, add_tsub_cancel_right] end order_bot end bounded_partial_order section linear_order variables [linear_order α] section locally_finite_order variables [locally_finite_order α] {a b : α} lemma Ico_subset_Ico_iff {a₁ b₁ a₂ b₂ : α} (h : a₁ < b₁) : Ico a₁ b₁ ⊆ Ico a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ := by rw [←coe_subset, coe_Ico, coe_Ico, set.Ico_subset_Ico_iff h] lemma Ico_union_Ico_eq_Ico {a b c : α} (hab : a ≤ b) (hbc : b ≤ c) : Ico a b ∪ Ico b c = Ico a c := by rw [←coe_inj, coe_union, coe_Ico, coe_Ico, coe_Ico, set.Ico_union_Ico_eq_Ico hab hbc] @[simp] lemma Ioc_union_Ioc_eq_Ioc {a b c : α} (h₁ : a ≤ b) (h₂ : b ≤ c) : Ioc a b ∪ Ioc b c = Ioc a c := by rw [←coe_inj, coe_union, coe_Ioc, coe_Ioc, coe_Ioc, set.Ioc_union_Ioc_eq_Ioc h₁ h₂] lemma Ico_subset_Ico_union_Ico {a b c : α} : Ico a c ⊆ Ico a b ∪ Ico b c := by { rw [←coe_subset, coe_union, coe_Ico, coe_Ico, coe_Ico], exact set.Ico_subset_Ico_union_Ico } lemma Ico_union_Ico' {a b c d : α} (hcb : c ≤ b) (had : a ≤ d) : Ico a b ∪ Ico c d = Ico (min a c) (max b d) := by rw [←coe_inj, coe_union, coe_Ico, coe_Ico, coe_Ico, set.Ico_union_Ico' hcb had] lemma Ico_union_Ico {a b c d : α} (h₁ : min a b ≤ max c d) (h₂ : min c d ≤ max a b) : Ico a b ∪ Ico c d = Ico (min a c) (max b d) := by rw [←coe_inj, coe_union, coe_Ico, coe_Ico, coe_Ico, set.Ico_union_Ico h₁ h₂] lemma Ico_inter_Ico {a b c d : α} : Ico a b ∩ Ico c d = Ico (max a c) (min b d) := by rw [←coe_inj, coe_inter, coe_Ico, coe_Ico, coe_Ico, ←inf_eq_min, ←sup_eq_max, set.Ico_inter_Ico] @[simp] lemma Ico_filter_lt (a b c : α) : (Ico a b).filter (λ x, x < c) = Ico a (min b c) := begin cases le_total b c, { rw [Ico_filter_lt_of_right_le h, min_eq_left h] }, { rw [Ico_filter_lt_of_le_right h, min_eq_right h] } end @[simp] lemma Ico_filter_le (a b c : α) : (Ico a b).filter (λ x, c ≤ x) = Ico (max a c) b := begin cases le_total a c, { rw [Ico_filter_le_of_left_le h, max_eq_right h] }, { rw [Ico_filter_le_of_le_left h, max_eq_left h] } end @[simp] lemma Ioo_filter_lt (a b c : α) : (Ioo a b).filter (< c) = Ioo a (min b c) := by { ext, simp [and_assoc] } @[simp] lemma Iio_filter_lt {α} [linear_order α] [locally_finite_order_bot α] (a b : α) : (Iio a).filter (< b) = Iio (min a b) := by { ext, simp [and_assoc] } @[simp] lemma Ico_diff_Ico_left (a b c : α) : (Ico a b) \ (Ico a c) = Ico (max a c) b := begin cases le_total a c, { ext x, rw [mem_sdiff, mem_Ico, mem_Ico, mem_Ico, max_eq_right h, and.right_comm, not_and, not_lt], exact and_congr_left' ⟨λ hx, hx.2 hx.1, λ hx, ⟨h.trans hx, λ _, hx⟩⟩ }, { rw [Ico_eq_empty_of_le h, sdiff_empty, max_eq_left h] } end @[simp] lemma Ico_diff_Ico_right (a b c : α) : (Ico a b) \ (Ico c b) = Ico a (min b c) := begin cases le_total b c, { rw [Ico_eq_empty_of_le h, sdiff_empty, min_eq_left h] }, { ext x, rw [mem_sdiff, mem_Ico, mem_Ico, mem_Ico, min_eq_right h, and_assoc, not_and', not_le], exact and_congr_right' ⟨λ hx, hx.2 hx.1, λ hx, ⟨hx.trans_le h, λ _, hx⟩⟩ } end end locally_finite_order variables [fintype α] [locally_finite_order_top α] [locally_finite_order_bot α] lemma Ioi_disj_union_Iio (a : α) : (Ioi a).disj_union (Iio a) (disjoint_Ioi_Iio a) = ({a} : finset α)ᶜ := by { ext, simp [eq_comm] } end linear_order section lattice variables [lattice α] [locally_finite_order α] {a a₁ a₂ b b₁ b₂ c x : α} lemma uIcc_to_dual (a b : α) : [to_dual a, to_dual b] = [a, b].map to_dual.to_embedding := Icc_to_dual _ _ @[simp] lemma uIcc_of_le (h : a ≤ b) : [a, b] = Icc a b := by rw [uIcc, inf_eq_left.2 h, sup_eq_right.2 h] @[simp] lemma uIcc_of_ge (h : b ≤ a) : [a, b] = Icc b a := by rw [uIcc, inf_eq_right.2 h, sup_eq_left.2 h] lemma uIcc_comm (a b : α) : [a, b] = [b, a] := by rw [uIcc, uIcc, inf_comm, sup_comm] @[simp] lemma uIcc_self : [a, a] = {a} := by simp [uIcc] @[simp] lemma nonempty_uIcc : finset.nonempty [a, b] := nonempty_Icc.2 inf_le_sup lemma Icc_subset_uIcc : Icc a b ⊆ [a, b] := Icc_subset_Icc inf_le_left le_sup_right lemma Icc_subset_uIcc' : Icc b a ⊆ [a, b] := Icc_subset_Icc inf_le_right le_sup_left @[simp] lemma left_mem_uIcc : a ∈ [a, b] := mem_Icc.2 ⟨inf_le_left, le_sup_left⟩ @[simp] lemma right_mem_uIcc : b ∈ [a, b] := mem_Icc.2 ⟨inf_le_right, le_sup_right⟩ lemma mem_uIcc_of_le (ha : a ≤ x) (hb : x ≤ b) : x ∈ [a, b] := Icc_subset_uIcc $ mem_Icc.2 ⟨ha, hb⟩ lemma mem_uIcc_of_ge (hb : b ≤ x) (ha : x ≤ a) : x ∈ [a, b] := Icc_subset_uIcc' $ mem_Icc.2 ⟨hb, ha⟩ lemma uIcc_subset_uIcc (h₁ : a₁ ∈ [a₂, b₂]) (h₂ : b₁ ∈ [a₂, b₂]) : [a₁, b₁] ⊆ [a₂, b₂] := by { rw mem_uIcc at h₁ h₂, exact Icc_subset_Icc (le_inf h₁.1 h₂.1) (sup_le h₁.2 h₂.2) } lemma uIcc_subset_Icc (ha : a₁ ∈ Icc a₂ b₂) (hb : b₁ ∈ Icc a₂ b₂) : [a₁, b₁] ⊆ Icc a₂ b₂ := by { rw mem_Icc at ha hb, exact Icc_subset_Icc (le_inf ha.1 hb.1) (sup_le ha.2 hb.2) } lemma uIcc_subset_uIcc_iff_mem : [a₁, b₁] ⊆ [a₂, b₂] ↔ a₁ ∈ [a₂, b₂] ∧ b₁ ∈ [a₂, b₂] := ⟨λ h, ⟨h left_mem_uIcc, h right_mem_uIcc⟩, λ h, uIcc_subset_uIcc h.1 h.2⟩ lemma uIcc_subset_uIcc_iff_le' : [a₁, b₁] ⊆ [a₂, b₂] ↔ a₂ ⊓ b₂ ≤ a₁ ⊓ b₁ ∧ a₁ ⊔ b₁ ≤ a₂ ⊔ b₂ := Icc_subset_Icc_iff inf_le_sup lemma uIcc_subset_uIcc_right (h : x ∈ [a, b]) : [x, b] ⊆ [a, b] := uIcc_subset_uIcc h right_mem_uIcc lemma uIcc_subset_uIcc_left (h : x ∈ [a, b]) : [a, x] ⊆ [a, b] := uIcc_subset_uIcc left_mem_uIcc h end lattice section distrib_lattice variables [distrib_lattice α] [locally_finite_order α] {a a₁ a₂ b b₁ b₂ c x : α} lemma eq_of_mem_uIcc_of_mem_uIcc : a ∈ [b, c] → b ∈ [a, c] → a = b := by { simp_rw mem_uIcc, exact set.eq_of_mem_uIcc_of_mem_uIcc } lemma eq_of_mem_uIcc_of_mem_uIcc' : b ∈ [a, c] → c ∈ [a, b] → b = c := by { simp_rw mem_uIcc, exact set.eq_of_mem_uIcc_of_mem_uIcc' } lemma uIcc_injective_right (a : α) : injective (λ b, [b, a]) := λ b c h, by { rw ext_iff at h, exact eq_of_mem_uIcc_of_mem_uIcc ((h _).1 left_mem_uIcc) ((h _).2 left_mem_uIcc) } lemma uIcc_injective_left (a : α) : injective (uIcc a) := by simpa only [uIcc_comm] using uIcc_injective_right a end distrib_lattice section linear_order variables [linear_order α] [locally_finite_order α] {a a₁ a₂ b b₁ b₂ c x : α} lemma Icc_min_max : Icc (min a b) (max a b) = [a, b] := rfl lemma uIcc_of_not_le (h : ¬ a ≤ b) : [a, b] = Icc b a := uIcc_of_ge $ le_of_not_ge h lemma uIcc_of_not_ge (h : ¬ b ≤ a) : [a, b] = Icc a b := uIcc_of_le $ le_of_not_ge h lemma uIcc_eq_union : [a, b] = Icc a b ∪ Icc b a := coe_injective $ by { push_cast, exact set.uIcc_eq_union } lemma mem_uIcc' : a ∈ [b, c] ↔ b ≤ a ∧ a ≤ c ∨ c ≤ a ∧ a ≤ b := by simp [uIcc_eq_union] lemma not_mem_uIcc_of_lt : c < a → c < b → c ∉ [a, b] := by { rw mem_uIcc, exact set.not_mem_uIcc_of_lt } lemma not_mem_uIcc_of_gt : a < c → b < c → c ∉ [a, b] := by { rw mem_uIcc, exact set.not_mem_uIcc_of_gt } lemma uIcc_subset_uIcc_iff_le : [a₁, b₁] ⊆ [a₂, b₂] ↔ min a₂ b₂ ≤ min a₁ b₁ ∧ max a₁ b₁ ≤ max a₂ b₂ := uIcc_subset_uIcc_iff_le' /-- A sort of triangle inequality. -/ lemma uIcc_subset_uIcc_union_uIcc : [a, c] ⊆ [a, b] ∪ [b, c] := coe_subset.1 $ by { push_cast, exact set.uIcc_subset_uIcc_union_uIcc } end linear_order section ordered_cancel_add_comm_monoid variables [ordered_cancel_add_comm_monoid α] [has_exists_add_of_le α] [locally_finite_order α] @[simp] lemma map_add_left_Icc (a b c : α) : (Icc a b).map (add_left_embedding c) = Icc (c + a) (c + b) := by { rw [← coe_inj, coe_map, coe_Icc, coe_Icc], exact set.image_const_add_Icc _ _ _ } @[simp] lemma map_add_right_Icc (a b c : α) : (Icc a b).map (add_right_embedding c) = Icc (a + c) (b + c) := by { rw [← coe_inj, coe_map, coe_Icc, coe_Icc], exact set.image_add_const_Icc _ _ _ } @[simp] lemma map_add_left_Ico (a b c : α) : (Ico a b).map (add_left_embedding c) = Ico (c + a) (c + b) := by { rw [← coe_inj, coe_map, coe_Ico, coe_Ico], exact set.image_const_add_Ico _ _ _ } @[simp] lemma map_add_right_Ico (a b c : α) : (Ico a b).map (add_right_embedding c) = Ico (a + c) (b + c) := by { rw [← coe_inj, coe_map, coe_Ico, coe_Ico], exact set.image_add_const_Ico _ _ _ } @[simp] lemma map_add_left_Ioc (a b c : α) : (Ioc a b).map (add_left_embedding c) = Ioc (c + a) (c + b) := by { rw [← coe_inj, coe_map, coe_Ioc, coe_Ioc], exact set.image_const_add_Ioc _ _ _ } @[simp] lemma map_add_right_Ioc (a b c : α) : (Ioc a b).map (add_right_embedding c) = Ioc (a + c) (b + c) := by { rw [← coe_inj, coe_map, coe_Ioc, coe_Ioc], exact set.image_add_const_Ioc _ _ _ } @[simp] lemma map_add_left_Ioo (a b c : α) : (Ioo a b).map (add_left_embedding c) = Ioo (c + a) (c + b) := by { rw [← coe_inj, coe_map, coe_Ioo, coe_Ioo], exact set.image_const_add_Ioo _ _ _ } @[simp] lemma map_add_right_Ioo (a b c : α) : (Ioo a b).map (add_right_embedding c) = Ioo (a + c) (b + c) := by { rw [← coe_inj, coe_map, coe_Ioo, coe_Ioo], exact set.image_add_const_Ioo _ _ _ } variables [decidable_eq α] @[simp] lemma image_add_left_Icc (a b c : α) : (Icc a b).image ((+) c) = Icc (c + a) (c + b) := by { rw [← map_add_left_Icc, map_eq_image], refl } @[simp] lemma image_add_left_Ico (a b c : α) : (Ico a b).image ((+) c) = Ico (c + a) (c + b) := by { rw [← map_add_left_Ico, map_eq_image], refl } @[simp] lemma image_add_left_Ioc (a b c : α) : (Ioc a b).image ((+) c) = Ioc (c + a) (c + b) := by { rw [← map_add_left_Ioc, map_eq_image], refl } @[simp] lemma image_add_left_Ioo (a b c : α) : (Ioo a b).image ((+) c) = Ioo (c + a) (c + b) := by { rw [← map_add_left_Ioo, map_eq_image], refl } @[simp] lemma image_add_right_Icc (a b c : α) : (Icc a b).image (+ c) = Icc (a + c) (b + c) := by { rw [← map_add_right_Icc, map_eq_image], refl } lemma image_add_right_Ico (a b c : α) : (Ico a b).image (+ c) = Ico (a + c) (b + c) := by { rw [← map_add_right_Ico, map_eq_image], refl } lemma image_add_right_Ioc (a b c : α) : (Ioc a b).image (+ c) = Ioc (a + c) (b + c) := by { rw [← map_add_right_Ioc, map_eq_image], refl } lemma image_add_right_Ioo (a b c : α) : (Ioo a b).image (+ c) = Ioo (a + c) (b + c) := by { rw [← map_add_right_Ioo, map_eq_image], refl } end ordered_cancel_add_comm_monoid @[to_additive] lemma prod_prod_Ioi_mul_eq_prod_prod_off_diag [fintype ι] [linear_order ι] [locally_finite_order_top ι] [locally_finite_order_bot ι] [comm_monoid α] (f : ι → ι → α) : ∏ i, ∏ j in Ioi i, f j i * f i j = ∏ i, ∏ j in {i}ᶜ, f j i := begin simp_rw [←Ioi_disj_union_Iio, prod_disj_union, prod_mul_distrib], congr' 1, rw [prod_sigma', prod_sigma'], refine prod_bij' (λ i hi, ⟨i.2, i.1⟩) _ _ (λ i hi, ⟨i.2, i.1⟩) _ _ _; simp, end end finset
47ad68d72265922921ddafbd20b5bcfe62a2ada2
7fc0ec5c526f706107537a6e2e34ac4cdf88d232
/src/linear_algebra/group_star_algebra.lean
fe548a01b0cd8b785440a51351d47bff7312acd3
[ "Apache-2.0" ]
permissive
fpvandoorn/group-representations
7440a81f2ac9e0d2defa44dc1643c3167f7a2d99
bd9d72311749187d3bd4f542d5eab83e8341856c
refs/heads/master
1,684,128,141,684
1,623,338,135,000
1,623,338,135,000
256,117,709
0
2
null
null
null
null
UTF-8
Lean
false
false
6,130
lean
/- Group algebras considered as star algebras. This is formally parallel to monoid_algebra, but instead of taking finite formal combinations of the generators, we take L^1 combinations. In this file we define `group_star_algebra k G := G →₁ k`, and `add_monoid_star_algebra k G` in the same way, and then define the convolution product on these. Instead of Haar measure this version uses counting measure Another way to go: define the co-product G → G × G as a measure on G × G with the same integrable functions as the product measure. This has the advantage that we could do it for simple functions. Note that Haar measure on G × G might not be the product of Haar measures but rather its completion. -/ import data.monoid_algebra import linear_algebra.star_algebra import topology.bases import measure_theory.measure_space measure_theory.l1_space measure_theory.bochner_integration import group_theory.presented_group group_theory.order_of_element import group_theory.free_abelian_group import algebra.group.hom algebra.group_power import group_theory.group_action import group_theory.representation.basic noncomputable theory open_locale classical topological_space open set filter topological_space ennreal emetric measure_theory open finset finsupp universes u₁ u₂ u₃ variables (k : Type u₁) (G : Type u₂) class discrete_group2 (G : Type u₂) extends group G instance discrete_group2.measurable_space [discrete_group2 G] : measurable_space G := ⊤ instance discrete_group2.measure_space [discrete_group2 G] : measure_space G := ⟨ measure.count ⟩ def discrete_group (G : Type u₂) : Type u₂ := G instance : measurable_space (discrete_group G) := ⊤ instance : measure_space (discrete_group G) := ⟨ measure.count ⟩ #print discrete_group.measurable_space -- basic group example is ℤ^n (free abelian group with n generators) with the counting measure inductive generator : Type | x variables a b : generator def zgroup := discrete_group (free_abelian_group generator) def zgroup2 : discrete_group2 (multiplicative (free_abelian_group generator)) := { } #print zgroup2.measurable_space def gx := free_abelian_group.of generator.x --def s1 := { g : zgroup2 | g = gx } section -- normed_group should be inferable from normed_star_ring variables [normed_star_ring k] [second_countable_topology k] [measurable_space k] [borel_space k] [opens_measurable_space k] variables [complete_space k] lemma measure_insert [discrete_group2 G] (μ : measure G) (s : set G) (hs : is_measurable s) (g : G) (hg: g ∉ s) : μ (insert g s) = μ s + μ {g} := begin have h1 : is_measurable ({g} : set G) := trivial, have hh : disjoint s {g} := by simp [set.disjoint_right,hg], have hz : ((insert g s) = (s ∪ {g})) := by simp, rw hz, apply measure_union hh hs h1, end @[simp] lemma measure_sum {ι : Type*} {α : Type*} [measurable_space α] (f : ι → measure α) (s : set α) (hs : is_measurable s): (measure.sum f) s = ∑' i, f i s := by simp only [hs, measure.sum, to_measure_apply, outer_measure.sum_apply, to_outer_measure_apply] lemma dirac_simp {α : Type*} [discrete_group2 α] (x g : α) : ite (x = g) 1 0 = (measure.dirac x) {g} := begin have h1 : is_measurable ({g} : set α) := trivial, simp [h1], by_cases x = g, simp [h], simp [h], end lemma check_count [discrete_group2 G] (s : finset G) : ( ↑ s.card = measure.count (↑s : set G)) := begin unfold measure.count, apply finset.induction_on s, simp, intros g s' hs heq, simp only [*, coe_insert, card_insert_of_not_mem, nat.cast_add, not_false_iff, nat.cast_one], rw measure_insert _ _ ↑ s' , congr, rw measure_sum, have hh : (∑' i, ite (i=g) (1:ennreal) 0) = ∑' i : G, (measure.dirac i) {g} , { congr, ext1, apply dirac_simp }, rw [← hh,tsum_ite_eq], repeat {trivial}, end lemma hn : normed_space ℝ k := begin sorry end def right_invariant_measure2 [discrete_group2 G] (f : G →₁ k) (a : G) (hn : normed_space ℝ k) : Prop := (∫ x : G, f.to_fun x) = ∫ x : G, f.to_fun (x*a) variable {G} def right_invariant_measure [discrete_group2 G] (μ : measure G) : Prop := ∀ g : G, ∀ s : set G, μ s = μ ((λ h,h*g)⁻¹' s) lemma discrete_measure_is_right_invariant [discrete_group2 G] : right_invariant_measure (measure.count : measure G) := begin unfold right_invariant_measure, unfold measure.count, intros, have hs : is_measurable s := trivial, let s' := ((λ (h : G), h * g) ⁻¹' s), have hs' : is_measurable s' := trivial, simp [hs,hs'], symmetry, exact @@tsum_equiv _ _ _ (λ i, ⨆(h : i ∈ s), (1 : ennreal)) (equiv.mul_right g), end -- @[derive [star_algebra]] def group_star_algebra : Type (max u₁ u₂) := G →₁ k namespace group_star_algebra variables {k G} local attribute [reducible] group_star_algebra section variables [normed_star_ring k] [second_countable_topology k] [measurable_space k] [borel_space k] [opens_measurable_space k] [group G] [measure_space G] def nntimes (a b : nnreal) : ennreal := ennreal.of_real (a * b) /-- The product of `f g : group_star_algebra k G` is the ℓ^1 function whose value at `a` is the sum of `f x * g y` over all pairs `x, y` such that `x * y = a`. (Think of the group ring of a group.) -/ lemma mul_measurable (f g : G →₁ k) : measurable (λ a : G, (∫ x : G, nnreal.to_real_hom ((nnnorm (f.to_fun x)) * (nnnorm (g.to_fun (x⁻¹ * a)))))) := begin dunfold measurable, end lemma mul_integrable (f g : G →₁ k) : integrable (λ a : G, (∫ x : G, nnreal.to_real_hom ((nnnorm (f.to_fun x)) * (nnnorm (g.to_fun (x⁻¹ * a)))))) := begin end -- lemma mul_convergence (f g : G →₁ k) : (∫ a : G, (∫ x, ((nnnorm (f.to_fun x)) * (nnnorm (g.to_fun (x⁻¹ * a)))))) < := -- begin -- -- use Fubini -- -- use Haar measure to change variables a → x * a -- end instance : has_mul (group_star_algebra k G) := ⟨λf g : G →ₘ k, (λ a : G, (∫ x, (f.to_fun x) * (g.to_fun (x⁻¹ * a)))) lemma mul_def {f g : group_star_algebra k G} : f * g = (λ a : G, (∫⁻ x, (f.to_fun x) * (g.to_fun (x⁻¹ * a))) := rfl
08fb0dfc4669caff3d342e2ee6b980f6fa79dcfd
01ae0d022f2e2fefdaaa898938c1ac1fbce3b3ab
/categories/universal/comparisons/equalizers.lean
4214cf892c13062f12c82b50d00bc80427c1ba55
[]
no_license
PatrickMassot/lean-category-theory
0f56a83464396a253c28a42dece16c93baf8ad74
ef239978e91f2e1c3b8e88b6e9c64c155dc56c99
refs/heads/master
1,629,739,187,316
1,512,422,659,000
1,512,422,659,000
113,098,786
0
0
null
1,512,424,022,000
1,512,424,022,000
null
UTF-8
Lean
false
false
1,034
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Stephen Morgan, Scott Morrison import ...isomorphism import ...natural_transformation import ...equivalence import ..comma_categories import ..universal open categories open categories.functor open categories.natural_transformation open categories.isomorphism open categories.equivalence open categories.universal namespace categories.universal -- definition comma_Equalizer_to_Equalizer { C : Category } { X Y : C.Obj } { f g : C.Hom X Y } ( equalizer : comma.Equalizer f g ) : Equalizer f g := sorry -- definition Equalizer_to_comma_Equalizer { C : Category } { X Y : C.Obj } { f g : C.Hom X Y } ( equalizer : Equalizer f g ) : comma.Equalizer f g := sorry -- definition Equalizers_agree { C : Category } { X Y : C.Obj } ( f g : C.Hom X Y ) : Isomorphism CategoryOfTypes (comma.Equalizer f g) (Equalizer f g) := sorry -- PROJECT prove equalizers are unique end categories.universal
d62ebbd961cd792ddfb24e2607a328318f67a9c9
9dc8cecdf3c4634764a18254e94d43da07142918
/src/tactic/abel.lean
8f7581d983617b1a15c8d27ef973c7bdad363970
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
16,770
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import tactic.norm_num /-! # The `abel` tactic Evaluate expressions in the language of additive, commutative monoids and groups. -/ namespace tactic namespace abel /-- The `context` for a call to `abel`. Stores a few options for this call, and caches some common subexpressions such as typeclass instances and `0 : α`. -/ meta structure context := (red : transparency) (α : expr) (univ : level) (α0 : expr) (is_group : bool) (inst : expr) /-- Populate a `context` object for evaluating `e`, up to reducibility level `red`. -/ meta def mk_context (red : transparency) (e : expr) : tactic context := do α ← infer_type e, c ← mk_app ``add_comm_monoid [α] >>= mk_instance, cg ← try_core (mk_app ``add_comm_group [α] >>= mk_instance), u ← mk_meta_univ, infer_type α >>= unify (expr.sort (level.succ u)), u ← get_univ_assignment u, α0 ← expr.of_nat α 0, match cg with | (some cg) := return ⟨red, α, u, α0, tt, cg⟩ | _ := return ⟨red, α, u, α0, ff, c⟩ end /-- Apply the function `n : ∀ {α} [inst : add_whatever α], _` to the implicit parameters in the context, and the given list of arguments. -/ meta def context.app (c : context) (n : name) (inst : expr) : list expr → expr := (@expr.const tt n [c.univ] c.α inst).mk_app /-- Apply the function `n : ∀ {α} [inst α], _` to the implicit parameters in the context, and the given list of arguments. Compared to `context.app`, this takes the name of the typeclass, rather than an inferred typeclass instance. -/ meta def context.mk_app (c : context) (n inst : name) (l : list expr) : tactic expr := do m ← mk_instance ((expr.const inst [c.univ] : expr) c.α), return $ c.app n m l /-- Add the letter "g" to the end of the name, e.g. turning `term` into `termg`. This is used to choose between declarations taking `add_comm_monoid` and those taking `add_comm_group` instances. -/ meta def add_g : name → name | (name.mk_string s p) := name.mk_string (s ++ "g") p | n := n /-- Apply the function `n : ∀ {α} [add_comm_{monoid,group} α]` to the given list of arguments. Will use the `add_comm_{monoid,group}` instance that has been cached in the context. -/ meta def context.iapp (c : context) (n : name) : list expr → expr := c.app (if c.is_group then add_g n else n) c.inst def term {α} [add_comm_monoid α] (n : ℕ) (x a : α) : α := n • x + a def termg {α} [add_comm_group α] (n : ℤ) (x a : α) : α := n • x + a /-- Evaluate a term with coefficient `n`, atom `x` and successor terms `a`. -/ meta def context.mk_term (c : context) (n x a : expr) : expr := c.iapp ``term [n, x, a] /-- Interpret an integer as a coefficient to a term. -/ meta def context.int_to_expr (c : context) (n : ℤ) : tactic expr := expr.of_int (if c.is_group then `(ℤ) else `(ℕ)) n meta inductive normal_expr : Type | zero (e : expr) : normal_expr | nterm (e : expr) (n : expr × ℤ) (x : expr) (a : normal_expr) : normal_expr meta def normal_expr.e : normal_expr → expr | (normal_expr.zero e) := e | (normal_expr.nterm e _ _ _) := e meta instance : has_coe normal_expr expr := ⟨normal_expr.e⟩ meta instance : has_coe_to_fun normal_expr (λ _, expr → expr) := ⟨λ e, ⇑(e : expr)⟩ meta def normal_expr.term' (c : context) (n : expr × ℤ) (x : expr) (a : normal_expr) : normal_expr := normal_expr.nterm (c.mk_term n.1 x a) n x a meta def normal_expr.zero' (c : context) : normal_expr := normal_expr.zero c.α0 meta def normal_expr.to_list : normal_expr → list (ℤ × expr) | (normal_expr.zero _) := [] | (normal_expr.nterm _ (_, n) x a) := (n, x) :: a.to_list open normal_expr meta def normal_expr.to_string (e : normal_expr) : string := " + ".intercalate $ (to_list e).map $ λ ⟨n, e⟩, to_string n ++ " • (" ++ to_string e ++ ")" meta def normal_expr.pp (e : normal_expr) : tactic format := do l ← (to_list e).mmap (λ ⟨n, e⟩, do pe ← pp e, return (to_fmt n ++ " • (" ++ pe ++ ")")), return $ format.join $ l.intersperse ↑" + " meta instance : has_to_tactic_format normal_expr := ⟨normal_expr.pp⟩ meta def normal_expr.refl_conv (e : normal_expr) : tactic (normal_expr × expr) := do p ← mk_eq_refl e, return (e, p) theorem const_add_term {α} [add_comm_monoid α] (k n x a a') (h : k + a = a') : k + @term α _ n x a = term n x a' := by simp [h.symm, term]; ac_refl theorem const_add_termg {α} [add_comm_group α] (k n x a a') (h : k + a = a') : k + @termg α _ n x a = termg n x a' := by simp [h.symm, termg]; ac_refl theorem term_add_const {α} [add_comm_monoid α] (n x a k a') (h : a + k = a') : @term α _ n x a + k = term n x a' := by simp [h.symm, term, add_assoc] theorem term_add_constg {α} [add_comm_group α] (n x a k a') (h : a + k = a') : @termg α _ n x a + k = termg n x a' := by simp [h.symm, termg, add_assoc] theorem term_add_term {α} [add_comm_monoid α] (n₁ x a₁ n₂ a₂ n' a') (h₁ : n₁ + n₂ = n') (h₂ : a₁ + a₂ = a') : @term α _ n₁ x a₁ + @term α _ n₂ x a₂ = term n' x a' := by simp [h₁.symm, h₂.symm, term, add_nsmul]; ac_refl theorem term_add_termg {α} [add_comm_group α] (n₁ x a₁ n₂ a₂ n' a') (h₁ : n₁ + n₂ = n') (h₂ : a₁ + a₂ = a') : @termg α _ n₁ x a₁ + @termg α _ n₂ x a₂ = termg n' x a' := by simp [h₁.symm, h₂.symm, termg, add_zsmul]; ac_refl theorem zero_term {α} [add_comm_monoid α] (x a) : @term α _ 0 x a = a := by simp [term, zero_nsmul, one_nsmul] theorem zero_termg {α} [add_comm_group α] (x a) : @termg α _ 0 x a = a := by simp [termg] meta def eval_add (c : context) : normal_expr → normal_expr → tactic (normal_expr × expr) | (zero _) e₂ := do p ← mk_app ``zero_add [e₂], return (e₂, p) | e₁ (zero _) := do p ← mk_app ``add_zero [e₁], return (e₁, p) | he₁@(nterm e₁ n₁ x₁ a₁) he₂@(nterm e₂ n₂ x₂ a₂) := (do is_def_eq x₁ x₂ c.red, (n', h₁) ← mk_app ``has_add.add [n₁.1, n₂.1] >>= norm_num.eval_field, (a', h₂) ← eval_add a₁ a₂, let k := n₁.2 + n₂.2, let p₁ := c.iapp ``term_add_term [n₁.1, x₁, a₁, n₂.1, a₂, n', a', h₁, h₂], if k = 0 then do p ← mk_eq_trans p₁ (c.iapp ``zero_term [x₁, a']), return (a', p) else return (term' c (n', k) x₁ a', p₁)) <|> if expr.lex_lt x₁ x₂ then do (a', h) ← eval_add a₁ he₂, return (term' c n₁ x₁ a', c.iapp ``term_add_const [n₁.1, x₁, a₁, e₂, a', h]) else do (a', h) ← eval_add he₁ a₂, return (term' c n₂ x₂ a', c.iapp ``const_add_term [e₁, n₂.1, x₂, a₂, a', h]) theorem term_neg {α} [add_comm_group α] (n x a n' a') (h₁ : -n = n') (h₂ : -a = a') : -@termg α _ n x a = termg n' x a' := by simp [h₂.symm, h₁.symm, termg]; ac_refl meta def eval_neg (c : context) : normal_expr → tactic (normal_expr × expr) | (zero e) := do p ← c.mk_app ``neg_zero ``subtraction_monoid [], return (zero' c, p) | (nterm e n x a) := do (n', h₁) ← mk_app ``has_neg.neg [n.1] >>= norm_num.eval_field, (a', h₂) ← eval_neg a, return (term' c (n', -n.2) x a', c.app ``term_neg c.inst [n.1, x, a, n', a', h₁, h₂]) def smul {α} [add_comm_monoid α] (n : ℕ) (x : α) : α := n • x def smulg {α} [add_comm_group α] (n : ℤ) (x : α) : α := n • x theorem zero_smul {α} [add_comm_monoid α] (c) : smul c (0 : α) = 0 := by simp [smul, nsmul_zero] theorem zero_smulg {α} [add_comm_group α] (c) : smulg c (0 : α) = 0 := by simp [smulg, zsmul_zero] theorem term_smul {α} [add_comm_monoid α] (c n x a n' a') (h₁ : c * n = n') (h₂ : smul c a = a') : smul c (@term α _ n x a) = term n' x a' := by simp [h₂.symm, h₁.symm, term, smul, nsmul_add, mul_nsmul] theorem term_smulg {α} [add_comm_group α] (c n x a n' a') (h₁ : c * n = n') (h₂ : smulg c a = a') : smulg c (@termg α _ n x a) = termg n' x a' := by simp [h₂.symm, h₁.symm, termg, smulg, zsmul_add, mul_zsmul] meta def eval_smul (c : context) (k : expr × ℤ) : normal_expr → tactic (normal_expr × expr) | (zero _) := return (zero' c, c.iapp ``zero_smul [k.1]) | (nterm e n x a) := do (n', h₁) ← mk_app ``has_mul.mul [k.1, n.1] >>= norm_num.eval_field, (a', h₂) ← eval_smul a, return (term' c (n', k.2 * n.2) x a', c.iapp ``term_smul [k.1, n.1, x, a, n', a', h₁, h₂]) theorem term_atom {α} [add_comm_monoid α] (x : α) : x = term 1 x 0 := by simp [term] theorem term_atomg {α} [add_comm_group α] (x : α) : x = termg 1 x 0 := by simp [termg] meta def eval_atom (c : context) (e : expr) : tactic (normal_expr × expr) := do n1 ← c.int_to_expr 1, return (term' c (n1, 1) e (zero' c), c.iapp ``term_atom [e]) lemma unfold_sub {α} [subtraction_monoid α] (a b c : α) (h : a + -b = c) : a - b = c := by rw [sub_eq_add_neg, h] theorem unfold_smul {α} [add_comm_monoid α] (n) (x y : α) (h : smul n x = y) : n • x = y := h theorem unfold_smulg {α} [add_comm_group α] (n : ℕ) (x y : α) (h : smulg (int.of_nat n) x = y) : (n : ℤ) • x = y := h theorem unfold_zsmul {α} [add_comm_group α] (n : ℤ) (x y : α) (h : smulg n x = y) : n • x = y := h lemma subst_into_smul {α} [add_comm_monoid α] (l r tl tr t) (prl : l = tl) (prr : r = tr) (prt : @smul α _ tl tr = t) : smul l r = t := by simp [prl, prr, prt] lemma subst_into_smulg {α} [add_comm_group α] (l r tl tr t) (prl : l = tl) (prr : r = tr) (prt : @smulg α _ tl tr = t) : smulg l r = t := by simp [prl, prr, prt] lemma subst_into_smul_upcast {α} [add_comm_group α] (l r tl zl tr t) (prl₁ : l = tl) (prl₂ : ↑tl = zl) (prr : r = tr) (prt : @smulg α _ zl tr = t) : smul l r = t := by simp [← prt, prl₁, ← prl₂, prr, smul, smulg] /-- Normalize a term `orig` of the form `smul e₁ e₂` or `smulg e₁ e₂`. Normalized terms use `smul` for monoids and `smulg` for groups, so there are actually four cases to handle: * Using `smul` in a monoid just simplifies the pieces using `subst_into_smul` * Using `smulg` in a group just simplifies the pieces using `subst_into_smulg` * Using `smul a b` in a group requires converting `a` from a nat to an int and then simplifying `smulg ↑a b` using `subst_into_smul_upcast` * Using `smulg` in a monoid is impossible (or at least out of scope), because you need a group argument to write a `smulg` term -/ meta def eval_smul' (c : context) (eval : expr → tactic (normal_expr × expr)) (is_smulg : bool) (orig e₁ e₂ : expr) : tactic (normal_expr × expr) := do (e₁', p₁) ← norm_num.derive e₁ <|> refl_conv e₁, match if is_smulg then e₁'.to_int else coe <$> e₁'.to_nat with | some n := do (e₂', p₂) ← eval e₂, if c.is_group = is_smulg then do (e', p) ← eval_smul c (e₁', n) e₂', return (e', c.iapp ``subst_into_smul [e₁, e₂, e₁', e₂', e', p₁, p₂, p]) else do guardb c.is_group, ic ← mk_instance_cache `(ℤ), nc ← mk_instance_cache `(ℕ), (ic, zl) ← ic.of_int n, (_, _, _, p₁') ← norm_num.prove_nat_uncast ic nc zl, (e', p) ← eval_smul c (zl, n) e₂', return (e', c.app ``subst_into_smul_upcast c.inst [e₁, e₂, e₁', zl, e₂', e', p₁, p₁', p₂, p]) | none := eval_atom c orig end meta def eval (c : context) : expr → tactic (normal_expr × expr) | `(%%e₁ + %%e₂) := do (e₁', p₁) ← eval e₁, (e₂', p₂) ← eval e₂, (e', p') ← eval_add c e₁' e₂', p ← c.mk_app ``norm_num.subst_into_add ``has_add [e₁, e₂, e₁', e₂', e', p₁, p₂, p'], return (e', p) | `(%%e₁ - %%e₂) := do e₂' ← mk_app ``has_neg.neg [e₂], e ← mk_app ``has_add.add [e₁, e₂'], (e', p) ← eval e, p' ← c.mk_app ``unfold_sub ``subtraction_monoid [e₁, e₂, e', p], return (e', p') | `(- %%e) := do (e₁, p₁) ← eval e, (e₂, p₂) ← eval_neg c e₁, p ← c.mk_app ``norm_num.subst_into_neg ``has_neg [e, e₁, e₂, p₁, p₂], return (e₂, p) | `(add_monoid.nsmul %%e₁ %%e₂) := do n ← if c.is_group then mk_app ``int.of_nat [e₁] else return e₁, (e', p) ← eval $ c.iapp ``smul [n, e₂], return (e', c.iapp ``unfold_smul [e₁, e₂, e', p]) | `(sub_neg_monoid.zsmul %%e₁ %%e₂) := do guardb c.is_group, (e', p) ← eval $ c.iapp ``smul [e₁, e₂], return (e', c.app ``unfold_zsmul c.inst [e₁, e₂, e', p]) | e@`(@has_smul.smul nat _ add_monoid.has_smul_nat %%e₁ %%e₂) := eval_smul' c eval ff e e₁ e₂ | e@`(@has_smul.smul int _ sub_neg_monoid.has_smul_int %%e₁ %%e₂) := eval_smul' c eval tt e e₁ e₂ | e@`(smul %%e₁ %%e₂) := eval_smul' c eval ff e e₁ e₂ | e@`(smulg %%e₁ %%e₂) := eval_smul' c eval tt e e₁ e₂ | e@`(@has_zero.zero _ _) := mcond (succeeds (is_def_eq e c.α0)) (mk_eq_refl c.α0 >>= λ p, pure (zero' c, p)) (eval_atom c e) | e := eval_atom c e meta def eval' (c : context) (e : expr) : tactic (expr × expr) := do (e', p) ← eval c e, return (e', p) @[derive has_reflect] inductive normalize_mode | raw | term instance : inhabited normalize_mode := ⟨normalize_mode.term⟩ meta def normalize (red : transparency) (mode := normalize_mode.term) (e : expr) : tactic (expr × expr) := do pow_lemma ← simp_lemmas.mk.add_simp ``pow_one, let lemmas := match mode with | normalize_mode.term := [``term.equations._eqn_1, ``termg.equations._eqn_1, ``add_zero, ``one_nsmul, ``one_zsmul, ``zsmul_zero] | _ := [] end, lemmas ← lemmas.mfoldl simp_lemmas.add_simp simp_lemmas.mk, (_, e', pr) ← ext_simplify_core () {} simp_lemmas.mk (λ _, failed) (λ _ _ _ _ e, do c ← mk_context red e, (new_e, pr) ← match mode with | normalize_mode.raw := eval' c | normalize_mode.term := trans_conv (eval' c) (λ e, do (e', prf, _) ← simplify lemmas [] e, return (e', prf)) end e, guard (¬ new_e =ₐ e), return ((), new_e, some pr, ff)) (λ _ _ _ _ _, failed) `eq e, return (e', pr) end abel namespace interactive open tactic.abel setup_tactic_parser /-- Tactic for solving equations in the language of *additive*, commutative monoids and groups. This version of `abel` fails if the target is not an equality that is provable by the axioms of commutative monoids/groups. `abel1!` will use a more aggressive reducibility setting to identify atoms. This can prove goals that `abel` cannot, but is more expensive. -/ meta def abel1 (red : parse (tk "!")?) : tactic unit := do `(%%e₁ = %%e₂) ← target, c ← mk_context (if red.is_some then semireducible else reducible) e₁, (e₁', p₁) ← eval c e₁, (e₂', p₂) ← eval c e₂, is_def_eq e₁' e₂', p ← mk_eq_symm p₂ >>= mk_eq_trans p₁, tactic.exact p meta def abel.mode : lean.parser abel.normalize_mode := with_desc "(raw|term)?" $ do mode ← ident?, match mode with | none := return abel.normalize_mode.term | some `term := return abel.normalize_mode.term | some `raw := return abel.normalize_mode.raw | _ := failed end /-- Evaluate expressions in the language of *additive*, commutative monoids and groups. It attempts to prove the goal outright if there is no `at` specifier and the target is an equality, but if this fails, it falls back to rewriting all monoid expressions into a normal form. If there is an `at` specifier, it rewrites the given target into a normal form. `abel!` will use a more aggressive reducibility setting to identify atoms. This can prove goals that `abel` cannot, but is more expensive. ```lean example {α : Type*} {a b : α} [add_comm_monoid α] : a + (b + a) = a + a + b := by abel example {α : Type*} {a b : α} [add_comm_group α] : (a + b) - ((b + a) + a) = -a := by abel example {α : Type*} {a b : α} [add_comm_group α] (hyp : a + a - a = b - b) : a = 0 := by { abel at hyp, exact hyp } example {α : Type*} {a b : α} [add_comm_group α] : (a + b) - (id a + b) = 0 := by abel! ``` -/ meta def abel (red : parse (tk "!")?) (SOP : parse abel.mode) (loc : parse location) : tactic unit := match loc with | interactive.loc.ns [none] := abel1 red | _ := failed end <|> do ns ← loc.get_locals, let red := if red.is_some then semireducible else reducible, tt ← tactic.replace_at (normalize red SOP) ns loc.include_goal | fail "abel failed to simplify", when loc.include_goal $ try tactic.reflexivity add_tactic_doc { name := "abel", category := doc_category.tactic, decl_names := [`tactic.interactive.abel], tags := ["arithmetic", "decision procedure"] } end interactive end tactic
4afab67b27d28650b89f9098c89c2e6e58d54e0f
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/Fintype.lean
d19ae84779111728a3f93945a9e065586a6ddee0
[]
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
4,658
lean
/- Copyright (c) 2020 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta, Adam Topaz -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.fintype.basic import Mathlib.data.fin import Mathlib.category_theory.concrete_category.bundled import Mathlib.category_theory.concrete_category.default import Mathlib.category_theory.full_subcategory import Mathlib.category_theory.skeletal import Mathlib.PostPort universes u_1 namespace Mathlib /-! # The category of finite types. We define the category of finite types, denoted `Fintype` as (bundled) types with a `fintype` instance. We also define `Fintype.skeleton`, the standard skeleton of `Fintype` whose objects are `fin n` for `n : ℕ`. We prove that the obvious inclusion functor `Fintype.skeleton ⥤ Fintype` is an equivalence of categories in `Fintype.skeleton.equivalence`. We prove that `Fintype.skeleton` is a skeleton of `Fintype` in `Fintype.is_skeleton`. -/ /-- The category of finite types. -/ def Fintype := category_theory.bundled fintype namespace Fintype /-- Construct a bundled `Fintype` from the underlying type and typeclass. -/ def of (X : Type u_1) [fintype X] : Fintype := category_theory.bundled.of X protected instance inhabited : Inhabited Fintype := { default := category_theory.bundled.mk pempty } protected instance fintype {X : Fintype} : fintype ↥X := category_theory.bundled.str X protected instance category_theory.category : category_theory.category Fintype := category_theory.induced_category.category category_theory.bundled.α /-- The fully faithful embedding of `Fintype` into the category of types. -/ @[simp] theorem incl_map (x : category_theory.induced_category (Type u_1) category_theory.bundled.α) (y : category_theory.induced_category (Type u_1) category_theory.bundled.α) (f : x ⟶ y) : ∀ (ᾰ : category_theory.bundled.α x), category_theory.functor.map incl f ᾰ = f ᾰ := fun (ᾰ : category_theory.bundled.α x) => Eq.refl (f ᾰ) protected instance category_theory.concrete_category : category_theory.concrete_category Fintype := category_theory.concrete_category.mk incl /-- The "standard" skeleton for `Fintype`. This is the full subcategory of `Fintype` spanned by objects of the form `fin n` for `n : ℕ`. We parameterize the objects of `Fintype.skeleton` directly as `ℕ`, as the type `fin m ≃ fin n` is nonempty if and only if `n = m`. -/ def skeleton := ℕ namespace skeleton /-- Given any natural number `n`, this creates the associated object of `Fintype.skeleton`. -/ def mk : ℕ → skeleton := id protected instance inhabited : Inhabited skeleton := { default := mk 0 } /-- Given any object of `Fintype.skeleton`, this returns the associated natural number. -/ def to_nat : skeleton → ℕ := id protected instance category_theory.category : category_theory.category skeleton := category_theory.category.mk theorem is_skeletal : category_theory.skeletal skeleton := sorry /-- The canonical fully faithful embedding of `Fintype.skeleton` into `Fintype`. -/ def incl : skeleton ⥤ Fintype := category_theory.functor.mk (fun (X : skeleton) => of (fin X)) fun (_x _x_1 : skeleton) (f : _x ⟶ _x_1) => f protected instance incl.category_theory.full : category_theory.full incl := category_theory.full.mk fun (_x _x_1 : skeleton) (f : category_theory.functor.obj incl _x ⟶ category_theory.functor.obj incl _x_1) => f protected instance incl.category_theory.faithful : category_theory.faithful incl := category_theory.faithful.mk protected instance incl.category_theory.ess_surj : category_theory.ess_surj incl := category_theory.ess_surj.mk fun (X : Fintype) => let F : ↥X ≃ fin (fintype.card ↥X) := trunc.out (fintype.equiv_fin ↥X); Exists.intro (fintype.card ↥X) (Nonempty.intro (category_theory.iso.mk ⇑(equiv.symm F) ⇑F)) protected instance incl.category_theory.is_equivalence : category_theory.is_equivalence incl := category_theory.equivalence.equivalence_of_fully_faithfully_ess_surj incl /-- The equivalence between `Fintype.skeleton` and `Fintype`. -/ def equivalence : skeleton ≌ Fintype := category_theory.functor.as_equivalence incl @[simp] theorem incl_mk_nat_card (n : ℕ) : fintype.card ↥(category_theory.functor.obj incl (mk n)) = n := finset.card_fin n end skeleton /-- `Fintype.skeleton` is a skeleton of `Fintype`. -/ def is_skeleton : category_theory.is_skeleton_of Fintype skeleton skeleton.incl := category_theory.is_skeleton_of.mk skeleton.is_skeletal skeleton.incl.category_theory.is_equivalence
e0bebe591d1ed7d6ceaf450409e229a1483fedf5
f3a5af2927397cf346ec0e24312bfff077f00425
/src/game/world4/level8.lean
2eddf2bf959430064de7261376c56a15e58039b4
[ "Apache-2.0" ]
permissive
ImperialCollegeLondon/natural_number_game
05c39e1586408cfb563d1a12e1085a90726ab655
f29b6c2884299fc63fdfc81ae5d7daaa3219f9fd
refs/heads/master
1,688,570,964,990
1,636,908,242,000
1,636,908,242,000
195,403,790
277
84
Apache-2.0
1,694,547,955,000
1,562,328,792,000
Lean
UTF-8
Lean
false
false
3,201
lean
import game.world4.level7 -- hide -- incantation for importing ring into framework -- hide import tactic.ring -- hide meta def nat_num_game.interactive.ring := tactic.interactive.ring -- hide namespace mynat -- hide def two_eq_succ_one : (2 : mynat) = succ 1 := rfl -- hide /- # Power World -/ /- ## Level 8: `add_squared` [final boss music] You see something written on the stone dungeon wall: ``` begin rw two_eq_succ_one, rw one_eq_succ_zero, repeat {rw pow_succ}, ... ``` and you can't make out the last two lines because there's a kind of thing in the way that will magically disappear but only when you've beaten the boss. -/ /- Theorem For all naturals $a$ and $b$, we have $$(a+b)^2=a^2+b^2+2ab.$$ -/ lemma add_squared (a b : mynat) : (a + b) ^ (2 : mynat) = a ^ (2 : mynat) + b ^ (2 : mynat) + 2 * a * b := begin [nat_num_game] rw two_eq_succ_one, rw one_eq_succ_zero, repeat {rw pow_succ}, repeat {rw pow_zero}, ring, end /- As the boss lies smouldering, you notice on the dungeon wall that <a href="https://twitter.com/XenaProject/status/1190453646904958976?s=20/" target="blank"> two more lines of code are now visible under the first three...</a> (Twitter.com) I just beat this level with 27 single rewrites followed by a `refl`. Can you do any better? (The current rewrite record is 25 -- see <a href="https://leanprover.zulipchat.com/#narrow/stream/113488-general/topic/function.20with.20random.20definition/near/179723073" target="blank">here</a> (needs zulip login)). If you beat it then well done! Do you fancy doing $(a+b)^3$ now? You might want to read <a href="https://xenaproject.wordpress.com/2018/06/13/ab3/" target="blank"> this Xena Project blog post</a> before you start though. -/ /- If you got this far -- very well done! If you only learnt the three tactics `rw`, `induction` and `refl` then there are now more tactics to learn; go back to the main menu and choose Function World. The main thing we really want to impress upon people is that we believe that *all of pure mathematics* can be done in this new way. A system called Coq (which is very like Lean) has <a href="https://hal.inria.fr/hal-00816699" target="blank"> checked the proof of the Feit-Thompson theorem</a> (hundreds of pages of group theory) and Lean has a <a href="https://leanprover-community.github.io/lean-perfectoid-spaces/" target="blank"> definition of perfectoid spaces</a> (a very complex modern mathematical structure). I believe that these systems will one day cause a paradigm shift in the way mathematics is done, but first we need to build what we know, or at least build enough to state what we mathematicians believe. If you want to get involved, come and join us at the <a href="https://leanprover.zulipchat.com" target="blank">Zulip Lean chat</a>. The #new members stream is a great place to start asking questions. To come (possibly): the real number game, the group theory game, the integer game, the natural number game 2,... . Alternatively see <a href="http://wwwf.imperial.ac.uk/~buzzard/xena/natural_number_game/FAQ.html" target="blank">the FAQ</a> for some more ideas about what to do next. -/ end mynat -- hide
53a33e108ddad619d02b636f85d624b5cec45f84
618003631150032a5676f229d13a079ac875ff77
/src/geometry/manifold/manifold.lean
d11d6678861964bc78d6425c172a6daa5c04f002
[ "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
27,180
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import topology.local_homeomorph /-! # Manifolds A manifold is a topological space M locally modelled on a model space H, i.e., the manifold is covered by open subsets on which there are local homeomorphisms (the charts) going to H. If the changes of charts satisfy some additional property (for instance if they are smooth), then M inherits additional structure (it makes sense to talk about smooth manifolds). There are therefore two different ingredients in a manifold: * the set of charts, which is data * the fact that changes of charts belong to some group (in fact groupoid), which is additional Prop. We separate these two parts in the definition: the manifold structure is just the set of charts, and then the different smoothness requirements (smooth manifold, orientable manifold, contact manifold, and so on) are additional properties of these charts. These properties are formalized through the notion of structure groupoid, i.e., a set of local homeomorphisms stable under composition and inverse, to which the change of coordinates should belong. ## Main definitions * `structure_groupoid H` : a subset of local homeomorphisms of `H` stable under composition, inverse and restriction (ex: local diffeos) * `pregroupoid H` : a subset of local homeomorphisms of `H` stable under composition and restriction, but not inverse (ex: smooth maps) * `groupoid_of_pregroupoid`: construct a groupoid from a pregroupoid, by requiring that a map and its inverse both belong to the pregroupoid (ex: construct diffeos from smooth maps) * `continuous_groupoid H` : the groupoid of all local homeomorphisms of `H` * `manifold H M` : manifold structure on `M` modelled on `H`, given by an atlas of local homeomorphisms from `M` to `H` whose sources cover `M`. This is a type class. * `has_groupoid M G` : when `G` is a structure groupoid on `H` and `M` is a manifold modelled on `H`, require that all coordinate changes belong to `G`. This is a type class * `atlas H M` : when `M` is a manifold modelled on `H`, the atlas of this manifold structure, i.e., the set of charts * `structomorph G M M'` : the set of diffeomorphisms between the manifolds `M` and `M'` for the groupoid `G`. We avoid the word diffeomorphisms, keeping it for the smooth category. As a basic example, we give the instance `instance manifold_model_space (H : Type*) [topological_space H] : manifold H H` saying that a topological space is a manifold over itself, with the identity as unique chart. This manifold structure is compatible with any groupoid. ## Implementation notes The atlas in a manifold is *not* a maximal atlas in general: the notion of maximality depends on the groupoid one considers, and changing groupoids changes the maximal atlas. With the current formalization, it makes sense first to choose the atlas, and then to ask whether this precise atlas defines a smooth manifold, an orientable manifold, and so on. A consequence is that structomorphisms between M and M' do *not* induce a bijection between the atlases of M and M': the definition is only that, read in charts, the structomorphism locally belongs to the groupoid under consideration. (This is equivalent to inducing a bijection between elements of the maximal atlas). A consequence is that the invariance under structomorphisms of properties defined in terms of the atlas is not obvious in general, and could require some work in theory (amounting to the fact that these properties only depend on the maximal atlas, for instance). In practice, this does not create any real difficulty. We use the letter `H` for the model space thinking of the case of manifolds with boundary, where the model space is a half space. Manifolds are sometimes defined as topological spaces with an atlas of local diffeomorphisms, and sometimes as spaces with an atlas from which a topology is deduced. We use the former approach: otherwise, there would be an instance from manifolds to topological spaces, which means that any instance search for topological spaces would try to find manifold structures involving a yet unknown model space, leading to problems. However, we also introduce the latter approach, through a structure `manifold_core` making it possible to construct a topology out of a set of local equivs with compatibility conditions (but we do not register it as an instance). In the definition of a manifold, the model space is written as an explicit parameter as there can be several model spaces for a given topological space. For instance, a complex manifold (modelled over ℂ^n) will also be seen sometimes as a real manifold modelled over ℝ^(2n). -/ noncomputable theory local attribute [instance, priority 0] classical.decidable_inhabited classical.prop_decidable universes u variables {H : Type u} {M : Type*} {M' : Type*} {M'' : Type*} /- Notational shortcut for the composition of local homeomorphisms, i.e., `local_homeomorph.trans`. Note that, as is usual for equivs, the composition is from left to right, hence the direction of the arrow. -/ local infixr ` ≫ₕ `:100 := local_homeomorph.trans open set local_homeomorph section groupoid /- One could add to the definition of a structure groupoid the fact that the restriction of an element of the groupoid to any open set still belongs to the groupoid. (This is in Kobayashi-Nomizu.) I am not sure I want this, for instance on H × E where E is a vector space, and the groupoid is made of functions respecting the fibers and linear in the fibers (so that a manifold over this groupoid is naturally a vector bundle) I prefer that the members of the groupoid are always defined on sets of the form s × E The only nontrivial requirement is locality: if a local homeomorphism belongs to the groupoid around each point in its domain of definition, then it belongs to the groupoid. Without this requirement, the composition of diffeomorphisms does not have to be a diffeomorphism. Note that this implies that a local homeomorphism with empty source belongs to any structure groupoid, as it trivially satisfies this condition. There is also a technical point, related to the fact that a local homeomorphism is by definition a global map which is a homeomorphism when restricted to its source subset (and its values outside of the source are not relevant). Therefore, we also require that being a member of the groupoid only depends on the values on the source. -/ /-- A structure groupoid is a set of local homeomorphisms of a topological space stable under composition and inverse. They appear in the definition of the smoothness class of a manifold. -/ structure structure_groupoid (H : Type u) [topological_space H] := (members : set (local_homeomorph H H)) (comp : ∀e e' : local_homeomorph H H, e ∈ members → e' ∈ members → e ≫ₕ e' ∈ members) (inv : ∀e : local_homeomorph H H, e ∈ members → e.symm ∈ members) (id_mem : local_homeomorph.refl H ∈ members) (locality : ∀e : local_homeomorph H H, (∀x ∈ e.source, ∃s, is_open s ∧ x ∈ s ∧ e.restr s ∈ members) → e ∈ members) (eq_on_source : ∀ e e' : local_homeomorph H H, e ∈ members → e' ≈ e → e' ∈ members) variable [topological_space H] @[reducible] instance : has_mem (local_homeomorph H H) (structure_groupoid H) := ⟨λ(e : local_homeomorph H H) (G : structure_groupoid H), e ∈ G.members⟩ /-- Partial order on the set of groupoids, given by inclusion of the members of the groupoid -/ instance structure_groupoid.partial_order : partial_order (structure_groupoid H) := partial_order.lift structure_groupoid.members (λa b h, by { cases a, cases b, dsimp at h, induction h, refl }) (by apply_instance) /-- The trivial groupoid, containing only the identity (and maps with empty source, as this is necessary from the definition) -/ def id_groupoid (H : Type u) [topological_space H] : structure_groupoid H := { members := {local_homeomorph.refl H} ∪ {e : local_homeomorph H H | e.source = ∅}, comp := λe e' he he', begin cases he; simp at he he', { simpa [he] }, { have : (e ≫ₕ e').source ⊆ e.source := sep_subset _ _, rw he at this, have : (e ≫ₕ e') ∈ {e : local_homeomorph H H | e.source = ∅} := disjoint_iff.1 this, exact (mem_union _ _ _).2 (or.inr this) }, end, inv := λe he, begin cases (mem_union _ _ _).1 he with E E, { finish }, { right, simpa [e.to_local_equiv.image_source_eq_target.symm] using E }, end, id_mem := mem_union_left _ rfl, locality := λe he, begin cases e.source.eq_empty_or_nonempty with h h, { right, exact h }, { left, rcases h with ⟨x, hx⟩, rcases he x hx with ⟨s, open_s, xs, hs⟩, have x's : x ∈ (e.restr s).source, { rw [restr_source, interior_eq_of_open open_s], exact ⟨hx, xs⟩ }, cases hs, { replace hs : local_homeomorph.restr e s = local_homeomorph.refl H, by simpa using hs, have : (e.restr s).source = univ, by { rw hs, simp }, change (e.to_local_equiv).source ∩ interior s = univ at this, have : univ ⊆ interior s, by { rw ← this, exact inter_subset_right _ _ }, have : s = univ, by rwa [interior_eq_of_open open_s, univ_subset_iff] at this, simpa [this, restr_univ] using hs }, { exfalso, rw mem_set_of_eq at hs, rwa hs at x's } }, end, eq_on_source := λe e' he he'e, begin cases he, { left, have : e = e', { refine eq_of_eq_on_source_univ (setoid.symm he'e) _ _; rw set.mem_singleton_iff.1 he ; refl }, rwa ← this }, { right, change (e.to_local_equiv).source = ∅ at he, rwa [set.mem_set_of_eq, he'e.source_eq] } end } /-- Every structure groupoid contains the identity groupoid -/ instance : order_bot (structure_groupoid H) := { bot := id_groupoid H, bot_le := begin assume u f hf, change f ∈ {local_homeomorph.refl H} ∪ {e : local_homeomorph H H | e.source = ∅} at hf, simp only [singleton_union, mem_set_of_eq, mem_insert_iff] at hf, cases hf, { rw hf, apply u.id_mem }, { apply u.locality, assume x hx, rw [hf, mem_empty_eq] at hx, exact hx.elim } end, ..structure_groupoid.partial_order } instance (H : Type u) [topological_space H] : inhabited (structure_groupoid H) := ⟨id_groupoid H⟩ /-- To construct a groupoid, one may consider classes of local homeos such that both the function and its inverse have some property. If this property is stable under composition, one gets a groupoid. `pregroupoid` bundles the properties needed for this construction, with the groupoid of smooth functions with smooth inverses as an application. -/ structure pregroupoid (H : Type*) [topological_space H] := (property : (H → H) → (set H) → Prop) (comp : ∀{f g u v}, property f u → property g v → is_open u → is_open v → is_open (u ∩ f ⁻¹' v) → property (g ∘ f) (u ∩ f ⁻¹' v)) (id_mem : property id univ) (locality : ∀{f u}, is_open u → (∀x∈u, ∃v, is_open v ∧ x ∈ v ∧ property f (u ∩ v)) → property f u) (congr : ∀{f g : H → H} {u}, is_open u → (∀x∈u, g x = f x) → property f u → property g u) /-- Construct a groupoid of local homeos for which the map and its inverse have some property, from a pregroupoid asserting that this property is stable under composition. -/ def pregroupoid.groupoid (PG : pregroupoid H) : structure_groupoid H := { members := {e : local_homeomorph H H | PG.property e e.source ∧ PG.property e.symm e.target}, comp := λe e' he he', begin split, { apply PG.comp he.1 he'.1 e.open_source e'.open_source, apply e.continuous_to_fun.preimage_open_of_open e.open_source e'.open_source }, { apply PG.comp he'.2 he.2 e'.open_target e.open_target, apply e'.continuous_inv_fun.preimage_open_of_open e'.open_target e.open_target } end, inv := λe he, ⟨he.2, he.1⟩, id_mem := ⟨PG.id_mem, PG.id_mem⟩, locality := λe he, begin split, { apply PG.locality e.open_source (λx xu, _), rcases he x xu with ⟨s, s_open, xs, hs⟩, refine ⟨s, s_open, xs, _⟩, convert hs.1, exact (interior_eq_of_open s_open).symm }, { apply PG.locality e.open_target (λx xu, _), rcases he (e.symm x) (e.map_target xu) with ⟨s, s_open, xs, hs⟩, refine ⟨e.target ∩ e.symm ⁻¹' s, _, ⟨xu, xs⟩, _⟩, { exact continuous_on.preimage_open_of_open e.continuous_inv_fun e.open_target s_open }, { rw [← inter_assoc, inter_self], convert hs.2, exact (interior_eq_of_open s_open).symm } }, end, eq_on_source := λe e' he ee', begin split, { apply PG.congr e'.open_source ee'.2, simp only [ee'.1, he.1] }, { have A := ee'.symm', apply PG.congr e'.symm.open_source A.2, convert he.2, rw A.1, refl } end } lemma mem_groupoid_of_pregroupoid (PG : pregroupoid H) (e : local_homeomorph H H) : e ∈ PG.groupoid ↔ PG.property e e.source ∧ PG.property e.symm e.target := iff.rfl lemma groupoid_of_pregroupoid_le (PG₁ PG₂ : pregroupoid H) (h : ∀f s, PG₁.property f s → PG₂.property f s) : PG₁.groupoid ≤ PG₂.groupoid := begin assume e he, rw mem_groupoid_of_pregroupoid at he ⊢, exact ⟨h _ _ he.1, h _ _ he.2⟩ end lemma mem_pregroupoid_of_eq_on_source (PG : pregroupoid H) {e e' : local_homeomorph H H} (he' : e ≈ e') (he : PG.property e e.source) : PG.property e' e'.source := begin rw ← he'.1, exact PG.congr e.open_source he'.eq_on.symm he, end /-- The pregroupoid of all local maps on a topological space H -/ @[reducible] def continuous_pregroupoid (H : Type*) [topological_space H] : pregroupoid H := { property := λf s, true, comp := λf g u v hf hg hu hv huv, trivial, id_mem := trivial, locality := λf u u_open h, trivial, congr := λf g u u_open hcongr hf, trivial } instance (H : Type*) [topological_space H] : inhabited (pregroupoid H) := ⟨continuous_pregroupoid H⟩ /-- The groupoid of all local homeomorphisms on a topological space H -/ def continuous_groupoid (H : Type*) [topological_space H] : structure_groupoid H := pregroupoid.groupoid (continuous_pregroupoid H) /-- Every structure groupoid is contained in the groupoid of all local homeomorphisms -/ instance : order_top (structure_groupoid H) := { top := continuous_groupoid H, le_top := λ u f hf, by { split; exact dec_trivial }, ..structure_groupoid.partial_order } end groupoid /-- A manifold is a topological space endowed with an atlas, i.e., a set of local homeomorphisms taking value in a model space `H`, called charts, such that the domains of the charts cover the whole space. We express the covering property by chosing for each x a member `chart_at x` of the atlas containing `x` in its source: in the smooth case, this is convenient to construct the tangent bundle in an efficient way. The model space is written as an explicit parameter as there can be several model spaces for a given topological space. For instance, a complex manifold (modelled over `ℂ^n`) will also be seen sometimes as a real manifold over `ℝ^(2n)`. -/ class manifold (H : Type*) [topological_space H] (M : Type*) [topological_space M] := (atlas [] : set (local_homeomorph M H)) (chart_at [] : M → local_homeomorph M H) (mem_chart_source [] : ∀x, x ∈ (chart_at x).source) (chart_mem_atlas [] : ∀x, chart_at x ∈ atlas) export manifold attribute [simp] mem_chart_source chart_mem_atlas section manifold /-- Any space is a manifold modelled over itself, by just using the identity chart -/ instance manifold_model_space (H : Type*) [topological_space H] : manifold H H := { atlas := {local_homeomorph.refl H}, chart_at := λx, local_homeomorph.refl H, mem_chart_source := λx, mem_univ x, chart_mem_atlas := λx, mem_singleton _ } /-- In the trivial manifold structure of a space modelled over itself through the identity, the atlas members are just the identity -/ @[simp] lemma model_space_atlas {H : Type*} [topological_space H] {e : local_homeomorph H H} : e ∈ atlas H H ↔ e = local_homeomorph.refl H := by simp [atlas, manifold.atlas] /-- In the model space, chart_at is always the identity -/ @[simp] lemma chart_at_model_space_eq {H : Type*} [topological_space H] {x : H} : chart_at H x = local_homeomorph.refl H := by simpa using chart_mem_atlas H x end manifold /-- Sometimes, one may want to construct a manifold structure on a space which does not yet have a topological structure, where the topology would come from the charts. For this, one needs charts that are only local equivs, and continuity properties for their composition. This is formalised in `manifold_core`. -/ @[nolint has_inhabited_instance] structure manifold_core (H : Type*) [topological_space H] (M : Type*) := (atlas : set (local_equiv M H)) (chart_at : M → local_equiv M H) (mem_chart_source : ∀x, x ∈ (chart_at x).source) (chart_mem_atlas : ∀x, chart_at x ∈ atlas) (open_source : ∀e e' : local_equiv M H, e ∈ atlas → e' ∈ atlas → is_open (e.symm.trans e').source) (continuous_to_fun : ∀e e' : local_equiv M H, e ∈ atlas → e' ∈ atlas → continuous_on (e.symm.trans e') (e.symm.trans e').source) namespace manifold_core variables [topological_space H] (c : manifold_core H M) {e : local_equiv M H} /-- Topology generated by a set of charts on a Type. -/ protected def to_topological_space : topological_space M := topological_space.generate_from $ ⋃ (e : local_equiv M H) (he : e ∈ c.atlas) (s : set H) (s_open : is_open s), {e ⁻¹' s ∩ e.source} lemma open_source' (he : e ∈ c.atlas) : @is_open M c.to_topological_space e.source := begin apply topological_space.generate_open.basic, simp only [exists_prop, mem_Union, mem_singleton_iff], refine ⟨e, he, univ, is_open_univ, _⟩, simp only [set.univ_inter, set.preimage_univ] end lemma open_target (he : e ∈ c.atlas) : is_open e.target := begin have E : e.target ∩ e.symm ⁻¹' e.source = e.target := subset.antisymm (inter_subset_left _ _) (λx hx, ⟨hx, local_equiv.target_subset_preimage_source _ hx⟩), simpa [local_equiv.trans_source, E] using c.open_source e e he he end /-- An element of the atlas in a manifold without topology becomes a local homeomorphism for the topology constructed from this atlas. The `local_homeomorph` version is given in this definition. -/ def local_homeomorph (e : local_equiv M H) (he : e ∈ c.atlas) : @local_homeomorph M H c.to_topological_space _ := { open_source := by convert c.open_source' he, open_target := by convert c.open_target he, continuous_to_fun := begin letI : topological_space M := c.to_topological_space, rw continuous_on_open_iff (c.open_source' he), assume s s_open, rw inter_comm, apply topological_space.generate_open.basic, simp only [exists_prop, mem_Union, mem_singleton_iff], exact ⟨e, he, ⟨s, s_open, rfl⟩⟩ end, continuous_inv_fun := begin letI : topological_space M := c.to_topological_space, apply continuous_on_open_of_generate_from (c.open_target he), assume t ht, simp only [exists_prop, mem_Union, mem_singleton_iff] at ht, rcases ht with ⟨e', e'_atlas, s, s_open, ts⟩, rw ts, let f := e.symm.trans e', have : is_open (f ⁻¹' s ∩ f.source), by simpa [inter_comm] using (continuous_on_open_iff (c.open_source e e' he e'_atlas)).1 (c.continuous_to_fun e e' he e'_atlas) s s_open, have A : e' ∘ e.symm ⁻¹' s ∩ (e.target ∩ e.symm ⁻¹' e'.source) = e.target ∩ (e' ∘ e.symm ⁻¹' s ∩ e.symm ⁻¹' e'.source), by { rw [← inter_assoc, ← inter_assoc], congr' 1, exact inter_comm _ _ }, simpa [local_equiv.trans_source, preimage_inter, preimage_comp.symm, A] using this end, ..e } /-- Given a manifold without topology, endow it with a genuine manifold structure with respect to the topology constructed from the atlas. -/ def to_manifold : @manifold H _ M c.to_topological_space := { atlas := ⋃ (e : local_equiv M H) (he : e ∈ c.atlas), {c.local_homeomorph e he}, chart_at := λx, c.local_homeomorph (c.chart_at x) (c.chart_mem_atlas x), mem_chart_source := λx, c.mem_chart_source x, chart_mem_atlas := λx, begin simp only [mem_Union, mem_singleton_iff], exact ⟨c.chart_at x, c.chart_mem_atlas x, rfl⟩, end } end manifold_core section has_groupoid variables [topological_space H] [topological_space M] [manifold H M] /-- A manifold has an atlas in a groupoid G if the change of coordinates belong to the groupoid -/ class has_groupoid {H : Type*} [topological_space H] (M : Type*) [topological_space M] [manifold H M] (G : structure_groupoid H) : Prop := (compatible [] : ∀{e e' : local_homeomorph M H}, e ∈ atlas H M → e' ∈ atlas H M → e.symm ≫ₕ e' ∈ G) lemma has_groupoid_of_le {G₁ G₂ : structure_groupoid H} (h : has_groupoid M G₁) (hle : G₁ ≤ G₂) : has_groupoid M G₂ := ⟨ λ e e' he he', hle ((h.compatible : _) he he') ⟩ lemma has_groupoid_of_pregroupoid (PG : pregroupoid H) (h : ∀{e e' : local_homeomorph M H}, e ∈ atlas H M → e' ∈ atlas H M → PG.property (e.symm ≫ₕ e') (e.symm ≫ₕ e').source) : has_groupoid M (PG.groupoid) := ⟨assume e e' he he', (mem_groupoid_of_pregroupoid PG _).mpr ⟨h he he', h he' he⟩⟩ /-- The trivial manifold structure on the model space is compatible with any groupoid -/ instance has_groupoid_model_space (H : Type*) [topological_space H] (G : structure_groupoid H) : has_groupoid H G := { compatible := λe e' he he', begin replace he : e ∈ atlas H H := he, replace he' : e' ∈ atlas H H := he', rw model_space_atlas at he he', simp [he, he', structure_groupoid.id_mem] end } /-- Any manifold structure is compatible with the groupoid of all local homeomorphisms -/ instance has_groupoid_continuous_groupoid : has_groupoid M (continuous_groupoid H) := ⟨begin assume e e' he he', rw [continuous_groupoid, mem_groupoid_of_pregroupoid], simp only [and_self] end⟩ /-- A G-diffeomorphism between two manifolds is a homeomorphism which, when read in the charts, belongs to G. We avoid the word diffeomorph as it is too related to the smooth category, and use structomorph instead. -/ @[nolint has_inhabited_instance] structure structomorph (G : structure_groupoid H) (M : Type*) (M' : Type*) [topological_space M] [topological_space M'] [manifold H M] [manifold H M'] extends homeomorph M M' := (mem_groupoid : ∀c : local_homeomorph M H, ∀c' : local_homeomorph M' H, c ∈ atlas H M → c' ∈ atlas H M' → c.symm ≫ₕ to_homeomorph.to_local_homeomorph ≫ₕ c' ∈ G) variables [topological_space M'] [topological_space M''] {G : structure_groupoid H} [manifold H M'] [manifold H M''] /-- The identity is a diffeomorphism of any manifold, for any groupoid. -/ def structomorph.refl (M : Type*) [topological_space M] [manifold H M] [has_groupoid M G] : structomorph G M M := { mem_groupoid := λc c' hc hc', begin change (local_homeomorph.symm c) ≫ₕ (local_homeomorph.refl M) ≫ₕ c' ∈ G, rw local_homeomorph.refl_trans, exact has_groupoid.compatible G hc hc' end, ..homeomorph.refl M } /-- The inverse of a structomorphism is a structomorphism -/ def structomorph.symm (e : structomorph G M M') : structomorph G M' M := { mem_groupoid := begin assume c c' hc hc', have : (c'.symm ≫ₕ e.to_homeomorph.to_local_homeomorph ≫ₕ c).symm ∈ G := G.inv _ (e.mem_groupoid c' c hc' hc), simp at this, rwa [trans_symm_eq_symm_trans_symm, trans_symm_eq_symm_trans_symm, symm_symm, trans_assoc] at this, end, ..e.to_homeomorph.symm} /-- The composition of structomorphisms is a structomorphism -/ def structomorph.trans (e : structomorph G M M') (e' : structomorph G M' M'') : structomorph G M M'' := { mem_groupoid := begin /- Let c and c' be two charts in M and M''. We want to show that e' ∘ e is smooth in these charts, around any point x. For this, let y = e (c⁻¹ x), and consider a chart g around y. Then g ∘ e ∘ c⁻¹ and c' ∘ e' ∘ g⁻¹ are both smooth as e and e' are structomorphisms, so their composition is smooth, and it coincides with c' ∘ e' ∘ e ∘ c⁻¹ around x. -/ assume c c' hc hc', refine G.locality _ (λx hx, _), let f₁ := e.to_homeomorph.to_local_homeomorph, let f₂ := e'.to_homeomorph.to_local_homeomorph, let f := (e.to_homeomorph.trans e'.to_homeomorph).to_local_homeomorph, have feq : f = f₁ ≫ₕ f₂ := homeomorph.trans_to_local_homeomorph _ _, -- define the atlas g around y let y := (c.symm ≫ₕ f₁) x, let g := chart_at H y, have hg₁ := chart_mem_atlas H y, have hg₂ := mem_chart_source H y, let s := (c.symm ≫ₕ f₁).source ∩ (c.symm ≫ₕ f₁) ⁻¹' g.source, have open_s : is_open s, by apply (c.symm ≫ₕ f₁).continuous_to_fun.preimage_open_of_open; apply open_source, have : x ∈ s, { split, { simp only [trans_source, preimage_univ, inter_univ, homeomorph.to_local_homeomorph_source], rw trans_source at hx, exact hx.1 }, { exact hg₂ } }, refine ⟨s, open_s, ⟨this, _⟩⟩, let F₁ := (c.symm ≫ₕ f₁ ≫ₕ g) ≫ₕ (g.symm ≫ₕ f₂ ≫ₕ c'), have A : F₁ ∈ G := G.comp _ _ (e.mem_groupoid c g hc hg₁) (e'.mem_groupoid g c' hg₁ hc'), let F₂ := (c.symm ≫ₕ f ≫ₕ c').restr s, have : F₁ ≈ F₂ := calc F₁ ≈ c.symm ≫ₕ f₁ ≫ₕ (g ≫ₕ g.symm) ≫ₕ f₂ ≫ₕ c' : by simp [F₁, trans_assoc] ... ≈ c.symm ≫ₕ f₁ ≫ₕ (of_set g.source g.open_source) ≫ₕ f₂ ≫ₕ c' : by simp [eq_on_source.trans', trans_self_symm g] ... ≈ ((c.symm ≫ₕ f₁) ≫ₕ (of_set g.source g.open_source)) ≫ₕ (f₂ ≫ₕ c') : by simp [trans_assoc] ... ≈ ((c.symm ≫ₕ f₁).restr s) ≫ₕ (f₂ ≫ₕ c') : by simp [s, trans_of_set'] ... ≈ ((c.symm ≫ₕ f₁) ≫ₕ (f₂ ≫ₕ c')).restr s : by simp [restr_trans] ... ≈ (c.symm ≫ₕ (f₁ ≫ₕ f₂) ≫ₕ c').restr s : by simp [eq_on_source.restr, trans_assoc] ... ≈ F₂ : by simp [F₂, feq], have : F₂ ∈ G := G.eq_on_source F₁ F₂ A (setoid.symm this), exact this end, ..homeomorph.trans e.to_homeomorph e'.to_homeomorph } end has_groupoid
6d753d9f389cfaa70d445a1fa651c66e90a02b9f
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/tactic/subtype_instance.lean
2e67e74b1d7a3c2707d66049cae0ab79f125344e
[ "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
2,462
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon Provides a `subtype_instance` tactic which builds instances for algebraic substructures (sub-groups, sub-rings...). -/ import data.string.basic open tactic expr name list namespace tactic open tactic.interactive (get_current_field refine_struct) open lean lean.parser open interactive /-- makes the substructure axiom name from field name, by postfacing with `_mem`-/ def mk_mem_name (sub : name) : name → name | (mk_string n _) := mk_string (n ++ "_mem") sub | n := n meta def derive_field_subtype : tactic unit := do field ← get_current_field, b ← target >>= is_prop, if b then do `[simp [subtype.ext_iff_val], dsimp [set.set_coe_eq_subtype]], intros, applyc field; assumption else do s ← find_local ``(set _), `(set %%α) ← infer_type s, e ← mk_const field, expl_arity ← get_expl_arity $ e α, xs ← (iota expl_arity).mmap $ λ _, intro1, args ← xs.mmap $ λ x, mk_app `subtype.val [x], hyps ← xs.mmap $ λ x, mk_app `subtype.property [x], val ← mk_app field args, subname ← local_context >>= list.mfirst (λ h, do (expr.const n _, args) ← get_app_fn_args <$> infer_type h, is_def_eq s args.ilast reducible, return n), mem_field ← resolve_constant $ mk_mem_name subname field, val_mem ← mk_app mem_field hyps, `(coe_sort %%s) <- target >>= instantiate_mvars, tactic.refine ``(@subtype.mk _ %%s %%val %%val_mem) namespace interactive /-- builds instances for algebraic substructures Example: ```lean variables {α : Type*} [monoid α] {s : set α} class is_submonoid (s : set α) : Prop := (one_mem : (1:α) ∈ s) (mul_mem {a b} : a ∈ s → b ∈ s → a * b ∈ s) instance subtype.monoid {s : set α} [is_submonoid s] : monoid s := by subtype_instance ``` -/ meta def subtype_instance := do t ← target, let cl := t.get_app_fn.const_name, src ← find_ancestors cl t.app_arg, let inst := pexpr.mk_structure_instance { struct := cl, field_values := [], field_names := [], sources := src.map to_pexpr }, refine_struct inst ; derive_field_subtype add_tactic_doc { name := "subtype_instance", category := doc_category.tactic, decl_names := [``subtype_instance], tags := ["type class", "structures"] } end interactive end tactic
d893150cd4197904a40e1f5ddc5026a768cb5b19
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/category_theory/groupoid.lean
1ada193dd2e32f7922b9a4b10edafc8864d0f757
[ "Apache-2.0" ]
permissive
agjftucker/mathlib
d634cd0d5256b6325e3c55bb7fb2403548371707
87fe50de17b00af533f72a102d0adefe4a2285e8
refs/heads/master
1,625,378,131,941
1,599,166,526,000
1,599,166,526,000
160,748,509
0
0
Apache-2.0
1,544,141,789,000
1,544,141,789,000
null
UTF-8
Lean
false
false
2,170
lean
/- Copyright (c) 2018 Reid Barton All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Scott Morrison, David Wärn -/ import category_theory.epi_mono namespace category_theory universes v v₂ u u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation section prio set_option default_priority 100 -- see Note [default priority] /-- A `groupoid` is a category such that all morphisms are isomorphisms. -/ class groupoid (obj : Type u) extends category.{v} obj : Type (max u (v+1)) := (inv : Π {X Y : obj}, (X ⟶ Y) → (Y ⟶ X)) (inv_comp' : ∀ {X Y : obj} (f : X ⟶ Y), comp (inv f) f = id Y . obviously) (comp_inv' : ∀ {X Y : obj} (f : X ⟶ Y), comp f (inv f) = id X . obviously) end prio restate_axiom groupoid.inv_comp' restate_axiom groupoid.comp_inv' attribute [simp] groupoid.inv_comp groupoid.comp_inv abbreviation large_groupoid (C : Type (u+1)) : Type (u+1) := groupoid.{u} C abbreviation small_groupoid (C : Type u) : Type (u+1) := groupoid.{u} C section variables {C : Type u} [groupoid.{v} C] {X Y : C} @[priority 100] -- see Note [lower instance priority] instance is_iso.of_groupoid (f : X ⟶ Y) : is_iso f := { inv := groupoid.inv f } variables (X Y) /-- In a groupoid, isomorphisms are equivalent to morphisms. -/ def groupoid.iso_equiv_hom : (X ≅ Y) ≃ (X ⟶ Y) := { to_fun := iso.hom, inv_fun := λ f, as_iso f, left_inv := λ i, iso.ext rfl, right_inv := λ f, rfl } end section variables {C : Type u} [category.{v} C] /-- A category where every morphism `is_iso` is a groupoid. -/ def groupoid.of_is_iso (all_is_iso : ∀ {X Y : C} (f : X ⟶ Y), is_iso f) : groupoid.{v} C := { inv := λ X Y f, (all_is_iso f).inv } /-- A category where every morphism has a `trunc` retraction is computably a groupoid. -/ def groupoid.of_trunc_split_mono (all_split_mono : ∀ {X Y : C} (f : X ⟶ Y), trunc (split_mono f)) : groupoid.{v} C := begin apply groupoid.of_is_iso, intros X Y f, trunc_cases all_split_mono f, trunc_cases all_split_mono (retraction f), apply is_iso.of_mono_retraction, end end end category_theory
53a93bdd10e4b64cd085344880bde4be496a82d9
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/test/noncomm_ring.lean
a53d395ca98bf530f92c38047099ba9e0601f59d
[ "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
2,803
lean
import tactic.noncomm_ring local notation `⁅`a`,` b`⁆` := a * b - b * a local infix ` ⚬ `:70 := λ a b, a * b + b * a variables {R : Type*} [ring R] variables (a b c : R) example : 0 = 0 := by noncomm_ring example : a = a := by noncomm_ring example : (a + b) * c = a * c + b * c := by noncomm_ring example : a * (b + c) = a * b + a * c := by noncomm_ring example : a - b = a + -b := by noncomm_ring example : a * b * c = a * (b * c) := by noncomm_ring example : a + a = a * 2 := by noncomm_ring example : a + a = 2 * a := by noncomm_ring example : -a = (-1) * a := by noncomm_ring example : a + a + a = 3 * a := by noncomm_ring example : a ^ 2 = a * a := by noncomm_ring example : a ^ 3 = a * a * a := by noncomm_ring example : (-a) * b = -(a * b) := by noncomm_ring example : a * (-b) = -(a * b) := by noncomm_ring example : a * (b + c + b + c - 2*b) = 2*a*c := by noncomm_ring example : (a + b)^2 = a^2 + a*b + b*a + b^2 := by noncomm_ring example : (a - b)^2 = a^2 - a*b - b*a + b^2 := by noncomm_ring example : (a + b)^3 = a^3 + a^2*b + a*b*a + a*b^2 + b*a^2 + b*a*b + b^2*a + b^3 := by noncomm_ring example : (a - b)^3 = a^3 - a^2*b - a*b*a + a*b^2 - b*a^2 + b*a*b + b^2*a - b^3 := by noncomm_ring example : ⁅a, a⁆ = 0 := by noncomm_ring example : ⁅a, b⁆ = -⁅b, a⁆ := by noncomm_ring example : ⁅a + b, c⁆ = ⁅a, c⁆ + ⁅b, c⁆ := by noncomm_ring example : ⁅a, b + c⁆ = ⁅a, b⁆ + ⁅a, c⁆ := by noncomm_ring example : ⁅a, ⁅b, c⁆⁆ + ⁅b, ⁅c, a⁆⁆ + ⁅c, ⁅a, b⁆⁆ = 0 := by noncomm_ring example : ⁅⁅a, b⁆, c⁆ + ⁅⁅b, c⁆, a⁆ + ⁅⁅c, a⁆, b⁆ = 0 := by noncomm_ring example : ⁅a, ⁅b, c⁆⁆ = ⁅⁅a, b⁆, c⁆ + ⁅b, ⁅a, c⁆⁆ := by noncomm_ring example : ⁅⁅a, b⁆, c⁆ = ⁅⁅a, c⁆, b⁆ + ⁅a, ⁅b, c⁆⁆ := by noncomm_ring example : ⁅a * b, c⁆ = a * ⁅b, c⁆ + ⁅a, c⁆ * b := by noncomm_ring example : ⁅a, b * c⁆ = ⁅a, b⁆ * c + b * ⁅a, c⁆ := by noncomm_ring example : ⁅3 * a, a⁆ = 0 := by noncomm_ring example : ⁅a * -5, a⁆ = 0 := by noncomm_ring example : ⁅a^3, a⁆ = 0 := by noncomm_ring example : a ⚬ a = 2*a^2 := by noncomm_ring example : (2 * a) ⚬ a = 4*a^2 := by noncomm_ring example : a ⚬ b = b ⚬ a := by noncomm_ring example : a ⚬ (b + c) = a ⚬ b + a ⚬ c := by noncomm_ring example : (a + b) ⚬ c = a ⚬ c + b ⚬ c := by noncomm_ring example : (a ⚬ b) ⚬ (a ⚬ a) = a ⚬ (b ⚬ (a ⚬ a)) := by noncomm_ring example : ⁅a, b ⚬ c⁆ = ⁅a, b⁆ ⚬ c + b ⚬ ⁅a, c⁆ := by noncomm_ring example : ⁅a ⚬ b, c⁆ = a ⚬ ⁅b, c⁆ + ⁅a, c⁆ ⚬ b := by noncomm_ring example : (a ⚬ b) ⚬ c - a ⚬ (b ⚬ c) = -⁅⁅a, b⁆, c⁆ + ⁅a, ⁅b, c⁆⁆ := by noncomm_ring example : a + -b = -b + a := by noncomm_ring
67b49b73023c76bed89abbd4a1371651d3fc008b
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/eqTheoremForVec.lean
56c8910a6d5801aeb91af9ab2d2d7e396e1efbb8
[ "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
402
lean
inductive Vector (α : Type u): Nat → Type u where | nil : Vector α 0 | cons (head : α) (tail : Vector α n) : Vector α (n+1) theorem Nat.lt_of_add_lt_add_right {a b c : Nat} (h : a + b < c + b) : a < c := sorry def Vector.nth : ∀{n}, Vector α n → Fin n → α | n+1, Vector.cons x xs, ⟨ 0, _⟩ => x | n+1, Vector.cons x xs, ⟨k+1, h⟩ => xs.nth ⟨k, Nat.lt_of_add_lt_add_right h⟩
db9ad3459b31b3abb0f31a06ccde29c04a85fdd0
7cef822f3b952965621309e88eadf618da0c8ae9
/src/tactic/linarith.lean
e7852760effd5da18a7fd6d4717be961bc2a2197
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
33,039
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Robert Y. Lewis -/ import tactic.ring data.nat.gcd data.list.basic meta.rb_map data.tree /-! A tactic for discharging linear arithmetic goals using Fourier-Motzkin elimination. `linarith` is (in principle) complete for ℚ and ℝ. It is not complete for non-dense orders, i.e. ℤ. @TODO: investigate storing comparisons in a list instead of a set, for possible efficiency gains @TODO: delay proofs of denominator normalization and nat casting until after contradiction is found -/ meta def nat.to_pexpr : ℕ → pexpr | 0 := ``(0) | 1 := ``(1) | n := if n % 2 = 0 then ``(bit0 %%(nat.to_pexpr (n/2))) else ``(bit1 %%(nat.to_pexpr (n/2))) open native namespace linarith section lemmas lemma int.coe_nat_bit0 (n : ℕ) : (↑(bit0 n : ℕ) : ℤ) = bit0 (↑n : ℤ) := by simp [bit0] lemma int.coe_nat_bit1 (n : ℕ) : (↑(bit1 n : ℕ) : ℤ) = bit1 (↑n : ℤ) := by simp [bit1, bit0] lemma int.coe_nat_bit0_mul (n : ℕ) (x : ℕ) : (↑(bit0 n * x) : ℤ) = (↑(bit0 n) : ℤ) * (↑x : ℤ) := by simp lemma int.coe_nat_bit1_mul (n : ℕ) (x : ℕ) : (↑(bit1 n * x) : ℤ) = (↑(bit1 n) : ℤ) * (↑x : ℤ) := by simp lemma int.coe_nat_one_mul (x : ℕ) : (↑(1 * x) : ℤ) = 1 * (↑x : ℤ) := by simp lemma int.coe_nat_zero_mul (x : ℕ) : (↑(0 * x) : ℤ) = 0 * (↑x : ℤ) := by simp lemma int.coe_nat_mul_bit0 (n : ℕ) (x : ℕ) : (↑(x * bit0 n) : ℤ) = (↑x : ℤ) * (↑(bit0 n) : ℤ) := by simp lemma int.coe_nat_mul_bit1 (n : ℕ) (x : ℕ) : (↑(x * bit1 n) : ℤ) = (↑x : ℤ) * (↑(bit1 n) : ℤ) := by simp lemma int.coe_nat_mul_one (x : ℕ) : (↑(x * 1) : ℤ) = (↑x : ℤ) * 1 := by simp lemma int.coe_nat_mul_zero (x : ℕ) : (↑(x * 0) : ℤ) = (↑x : ℤ) * 0 := by simp lemma nat_eq_subst {n1 n2 : ℕ} {z1 z2 : ℤ} (hn : n1 = n2) (h1 : ↑n1 = z1) (h2 : ↑n2 = z2) : z1 = z2 := by simpa [eq.symm h1, eq.symm h2, int.coe_nat_eq_coe_nat_iff] lemma nat_le_subst {n1 n2 : ℕ} {z1 z2 : ℤ} (hn : n1 ≤ n2) (h1 : ↑n1 = z1) (h2 : ↑n2 = z2) : z1 ≤ z2 := by simpa [eq.symm h1, eq.symm h2, int.coe_nat_le] lemma nat_lt_subst {n1 n2 : ℕ} {z1 z2 : ℤ} (hn : n1 < n2) (h1 : ↑n1 = z1) (h2 : ↑n2 = z2) : z1 < z2 := by simpa [eq.symm h1, eq.symm h2, int.coe_nat_lt] lemma eq_of_eq_of_eq {α} [ordered_semiring α] {a b : α} (ha : a = 0) (hb : b = 0) : a + b = 0 := by simp * lemma le_of_eq_of_le {α} [ordered_semiring α] {a b : α} (ha : a = 0) (hb : b ≤ 0) : a + b ≤ 0 := by simp * lemma lt_of_eq_of_lt {α} [ordered_semiring α] {a b : α} (ha : a = 0) (hb : b < 0) : a + b < 0 := by simp * lemma le_of_le_of_eq {α} [ordered_semiring α] {a b : α} (ha : a ≤ 0) (hb : b = 0) : a + b ≤ 0 := by simp * lemma lt_of_lt_of_eq {α} [ordered_semiring α] {a b : α} (ha : a < 0) (hb : b = 0) : a + b < 0 := by simp * lemma mul_neg {α} [ordered_ring α] {a b : α} (ha : a < 0) (hb : b > 0) : b * a < 0 := have (-b)*a > 0, from mul_pos_of_neg_of_neg (neg_neg_of_pos hb) ha, neg_of_neg_pos (by simpa) lemma mul_nonpos {α} [ordered_ring α] {a b : α} (ha : a ≤ 0) (hb : b > 0) : b * a ≤ 0 := have (-b)*a ≥ 0, from mul_nonneg_of_nonpos_of_nonpos (le_of_lt (neg_neg_of_pos hb)) ha, (by simpa) lemma mul_eq {α} [ordered_semiring α] {a b : α} (ha : a = 0) (hb : b > 0) : b * a = 0 := by simp * lemma eq_of_not_lt_of_not_gt {α} [linear_order α] (a b : α) (h1 : ¬ a < b) (h2 : ¬ b < a) : a = b := le_antisymm (le_of_not_gt h2) (le_of_not_gt h1) lemma add_subst {α} [ring α] {n e1 e2 t1 t2 : α} (h1 : n * e1 = t1) (h2 : n * e2 = t2) : n * (e1 + e2) = t1 + t2 := by simp [left_distrib, *] lemma sub_subst {α} [ring α] {n e1 e2 t1 t2 : α} (h1 : n * e1 = t1) (h2 : n * e2 = t2) : n * (e1 - e2) = t1 - t2 := by simp [left_distrib, *] lemma neg_subst {α} [ring α] {n e t : α} (h1 : n * e = t) : n * (-e) = -t := by simp * private meta def apnn : tactic unit := `[norm_num] lemma mul_subst {α} [comm_ring α] {n1 n2 k e1 e2 t1 t2 : α} (h1 : n1 * e1 = t1) (h2 : n2 * e2 = t2) (h3 : n1*n2 = k . apnn) : k * (e1 * e2) = t1 * t2 := have h3 : n1 * n2 = k, from h3, by rw [←h3, mul_comm n1, mul_assoc n2, ←mul_assoc n1, h1, ←mul_assoc n2, mul_comm n2, mul_assoc, h2] -- OUCH lemma div_subst {α} [field α] {n1 n2 k e1 e2 t1 : α} (h1 : n1 * e1 = t1) (h2 : n2 / e2 = 1) (h3 : n1*n2 = k) : k * (e1 / e2) = t1 := by rw [←h3, mul_assoc, mul_div_comm, h2, ←mul_assoc, h1, mul_comm, one_mul] end lemmas section datatypes @[derive decidable_eq] inductive ineq | eq | le | lt open ineq def ineq.max : ineq → ineq → ineq | eq a := a | le a := a | lt a := lt def ineq.is_lt : ineq → ineq → bool | eq le := tt | eq lt := tt | le lt := tt | _ _ := ff def ineq.to_string : ineq → string | eq := "=" | le := "≤" | lt := "<" instance : has_to_string ineq := ⟨ineq.to_string⟩ /-- The main datatype for FM elimination. Variables are represented by natural numbers, each of which has an integer coefficient. Index 0 is reserved for constants, i.e. `coeffs.find 0` is the coefficient of 1. The represented term is coeffs.keys.sum (λ i, coeffs.find i * Var[i]). str determines the direction of the comparison -- is it < 0, ≤ 0, or = 0? -/ meta structure comp := (str : ineq) (coeffs : rb_map ℕ int) meta instance : inhabited comp := ⟨⟨ineq.eq, mk_rb_map⟩⟩ meta inductive comp_source | assump : ℕ → comp_source | add : comp_source → comp_source → comp_source | scale : ℕ → comp_source → comp_source meta def comp_source.flatten : comp_source → rb_map ℕ ℕ | (comp_source.assump n) := mk_rb_map.insert n 1 | (comp_source.add c1 c2) := (comp_source.flatten c1).add (comp_source.flatten c2) | (comp_source.scale n c) := (comp_source.flatten c).map (λ v, v * n) meta def comp_source.to_string : comp_source → string | (comp_source.assump e) := to_string e | (comp_source.add c1 c2) := comp_source.to_string c1 ++ " + " ++ comp_source.to_string c2 | (comp_source.scale n c) := to_string n ++ " * " ++ comp_source.to_string c meta instance comp_source.has_to_format : has_to_format comp_source := ⟨λ a, comp_source.to_string a⟩ meta structure pcomp := (c : comp) (src : comp_source) meta def map_lt (m1 m2 : rb_map ℕ int) : bool := list.lex (prod.lex (<) (<)) m1.to_list m2.to_list -- make more efficient meta def comp.lt (c1 c2 : comp) : bool := (c1.str.is_lt c2.str) || (c1.str = c2.str) && map_lt c1.coeffs c2.coeffs meta instance comp.has_lt : has_lt comp := ⟨λ a b, comp.lt a b⟩ meta instance pcomp.has_lt : has_lt pcomp := ⟨λ p1 p2, p1.c < p2.c⟩ -- short-circuit type class inference meta instance pcomp.has_lt_dec : decidable_rel ((<) : pcomp → pcomp → Prop) := by apply_instance meta def comp.coeff_of (c : comp) (a : ℕ) : ℤ := c.coeffs.zfind a meta def comp.scale (c : comp) (n : ℕ) : comp := { c with coeffs := c.coeffs.map ((*) (n : ℤ)) } meta def comp.add (c1 c2 : comp) : comp := ⟨c1.str.max c2.str, c1.coeffs.add c2.coeffs⟩ meta def pcomp.scale (c : pcomp) (n : ℕ) : pcomp := ⟨c.c.scale n, comp_source.scale n c.src⟩ meta def pcomp.add (c1 c2 : pcomp) : pcomp := ⟨c1.c.add c2.c, comp_source.add c1.src c2.src⟩ meta instance pcomp.to_format : has_to_format pcomp := ⟨λ p, to_fmt p.c.coeffs ++ to_string p.c.str ++ "0"⟩ meta instance comp.to_format : has_to_format comp := ⟨λ p, to_fmt p.coeffs⟩ end datatypes section fm_elim /-- If c1 and c2 both contain variable a with opposite coefficients, produces v1, v2, and c such that a has been cancelled in c := v1*c1 + v2*c2 -/ meta def elim_var (c1 c2 : comp) (a : ℕ) : option (ℕ × ℕ × comp) := let v1 := c1.coeff_of a, v2 := c2.coeff_of a in if v1 * v2 < 0 then let vlcm := nat.lcm v1.nat_abs v2.nat_abs, v1' := vlcm / v1.nat_abs, v2' := vlcm / v2.nat_abs in some ⟨v1', v2', comp.add (c1.scale v1') (c2.scale v2')⟩ else none meta def pelim_var (p1 p2 : pcomp) (a : ℕ) : option pcomp := do (n1, n2, c) ← elim_var p1.c p2.c a, return ⟨c, comp_source.add (p1.src.scale n1) (p2.src.scale n2)⟩ meta def comp.is_contr (c : comp) : bool := c.coeffs.empty ∧ c.str = ineq.lt meta def pcomp.is_contr (p : pcomp) : bool := p.c.is_contr meta def elim_with_set (a : ℕ) (p : pcomp) (comps : rb_set pcomp) : rb_set pcomp := if ¬ p.c.coeffs.contains a then mk_rb_set.insert p else comps.fold mk_rb_set $ λ pc s, match pelim_var p pc a with | some pc := s.insert pc | none := s end /-- The state for the elimination monad. vars: the set of variables present in comps comps: a set of comparisons inputs: a set of pairs of exprs (t, pf), where t is a term and pf is a proof that t {<, ≤, =} 0, indexed by ℕ. has_false: stores a pcomp of 0 < 0 if one has been found TODO: is it more efficient to store comps as a list, to avoid comparisons? -/ meta structure linarith_structure := (vars : rb_set ℕ) (comps : rb_set pcomp) @[reducible] meta def linarith_monad := state_t linarith_structure (except_t pcomp id) meta instance : monad linarith_monad := state_t.monad meta instance : monad_except pcomp linarith_monad := state_t.monad_except pcomp meta def get_vars : linarith_monad (rb_set ℕ) := linarith_structure.vars <$> get meta def get_var_list : linarith_monad (list ℕ) := rb_set.to_list <$> get_vars meta def get_comps : linarith_monad (rb_set pcomp) := linarith_structure.comps <$> get meta def validate : linarith_monad unit := do ⟨_, comps⟩ ← get, match comps.to_list.find (λ p : pcomp, p.is_contr) with | none := return () | some c := throw c end meta def update (vars : rb_set ℕ) (comps : rb_set pcomp) : linarith_monad unit := state_t.put ⟨vars, comps⟩ >> validate meta def monad.elim_var (a : ℕ) : linarith_monad unit := do vs ← get_vars, when (vs.contains a) $ do comps ← get_comps, let cs' := comps.fold mk_rb_set (λ p s, s.union (elim_with_set a p comps)), update (vs.erase a) cs' meta def elim_all_vars : linarith_monad unit := get_var_list >>= list.mmap' monad.elim_var end fm_elim section parse open ineq tactic meta def map_of_expr_mul_aux (c1 c2 : rb_map ℕ ℤ) : option (rb_map ℕ ℤ) := match c1.keys, c2.keys with | [0], _ := some $ c2.scale (c1.zfind 0) | _, [0] := some $ c1.scale (c2.zfind 0) | [], _ := some mk_rb_map | _, [] := some mk_rb_map | _, _ := none end meta def list.mfind {α} (tac : α → tactic unit) : list α → tactic α | [] := failed | (h::t) := tac h >> return h <|> list.mfind t meta def rb_map.find_defeq (red : transparency) {v} (m : expr_map v) (e : expr) : tactic v := prod.snd <$> list.mfind (λ p, is_def_eq e p.1 red) m.to_list /-- Turns an expression into a map from ℕ to ℤ, for use in a comp object. The expr_map ℕ argument identifies which expressions have already been assigned numbers. Returns a new map. -/ meta def map_of_expr (red : transparency) : expr_map ℕ → expr → tactic (expr_map ℕ × rb_map ℕ ℤ) | m e@`(%%e1 * %%e2) := (do (m', comp1) ← map_of_expr m e1, (m', comp2) ← map_of_expr m' e2, mp ← map_of_expr_mul_aux comp1 comp2, return (m', mp)) <|> (do k ← rb_map.find_defeq red m e, return (m, mk_rb_map.insert k 1)) <|> (let n := m.size + 1 in return (m.insert e n, mk_rb_map.insert n 1)) | m `(%%e1 + %%e2) := do (m', comp1) ← map_of_expr m e1, (m', comp2) ← map_of_expr m' e2, return (m', comp1.add comp2) | m `(%%e1 - %%e2) := do (m', comp1) ← map_of_expr m e1, (m', comp2) ← map_of_expr m' e2, return (m', comp1.add (comp2.scale (-1))) | m `(-%%e) := do (m', comp) ← map_of_expr m e, return (m', comp.scale (-1)) | m e := match e.to_int with | some 0 := return ⟨m, mk_rb_map⟩ | some z := return ⟨m, mk_rb_map.insert 0 z⟩ | none := (do k ← rb_map.find_defeq red m e, return (m, mk_rb_map.insert k 1)) <|> (let n := m.size + 1 in return (m.insert e n, mk_rb_map.insert n 1)) end meta def parse_into_comp_and_expr : expr → option (ineq × expr) | `(%%e < 0) := (ineq.lt, e) | `(%%e ≤ 0) := (ineq.le, e) | `(%%e = 0) := (ineq.eq, e) | _ := none meta def to_comp (red : transparency) (e : expr) (m : expr_map ℕ) : tactic (comp × expr_map ℕ) := do (iq, e) ← parse_into_comp_and_expr e, (m', comp') ← map_of_expr red m e, return ⟨⟨iq, comp'⟩, m'⟩ meta def to_comp_fold (red : transparency) : expr_map ℕ → list expr → tactic (list (option comp) × expr_map ℕ) | m [] := return ([], m) | m (h::t) := (do (c, m') ← to_comp red h m, (l, mp) ← to_comp_fold m' t, return (c::l, mp)) <|> (do (l, mp) ← to_comp_fold m t, return (none::l, mp)) /-- Takes a list of proofs of props of the form t {<, ≤, =} 0, and creates a linarith_structure. -/ meta def mk_linarith_structure (red : transparency) (l : list expr) : tactic (linarith_structure × rb_map ℕ (expr × expr)) := do pftps ← l.mmap infer_type, (l', map) ← to_comp_fold red mk_rb_map pftps, let lz := list.enum $ ((l.zip pftps).zip l').filter_map (λ ⟨a, b⟩, prod.mk a <$> b), let prmap := rb_map.of_list $ lz.map (λ ⟨n, x⟩, (n, x.1)), let vars : rb_set ℕ := rb_map.set_of_list $ list.range map.size.succ, let pc : rb_set pcomp := rb_map.set_of_list $ lz.map (λ ⟨n, x⟩, ⟨x.2, comp_source.assump n⟩), return (⟨vars, pc⟩, prmap) meta def linarith_monad.run (red : transparency) {α} (tac : linarith_monad α) (l : list expr) : tactic ((pcomp ⊕ α) × rb_map ℕ (expr × expr)) := do (struct, inputs) ← mk_linarith_structure red l, match (state_t.run (validate >> tac) struct).run with | (except.ok (a, _)) := return (sum.inr a, inputs) | (except.error contr) := return (sum.inl contr, inputs) end end parse section prove open ineq tactic meta def get_rel_sides : expr → tactic (expr × expr) | `(%%a < %%b) := return (a, b) | `(%%a ≤ %%b) := return (a, b) | `(%%a = %%b) := return (a, b) | `(%%a ≥ %%b) := return (a, b) | `(%%a > %%b) := return (a, b) | _ := failed meta def mul_expr (n : ℕ) (e : expr) : pexpr := if n = 1 then ``(%%e) else ``(%%(nat.to_pexpr n) * %%e) meta def add_exprs_aux : pexpr → list pexpr → pexpr | p [] := p | p [a] := ``(%%p + %%a) | p (h::t) := add_exprs_aux ``(%%p + %%h) t meta def add_exprs : list pexpr → pexpr | [] := ``(0) | (h::t) := add_exprs_aux h t meta def find_contr (m : rb_set pcomp) : option pcomp := m.keys.find (λ p, p.c.is_contr) meta def ineq_const_mul_nm : ineq → name | lt := ``mul_neg | le := ``mul_nonpos | eq := ``mul_eq meta def ineq_const_nm : ineq → ineq → (name × ineq) | eq eq := (``eq_of_eq_of_eq, eq) | eq le := (``le_of_eq_of_le, le) | eq lt := (``lt_of_eq_of_lt, lt) | le eq := (``le_of_le_of_eq, le) | le le := (`add_nonpos, le) | le lt := (`add_neg_of_nonpos_of_neg, lt) | lt eq := (``lt_of_lt_of_eq, lt) | lt le := (`add_neg_of_neg_of_nonpos, lt) | lt lt := (`add_neg, lt) meta def mk_single_comp_zero_pf (c : ℕ) (h : expr) : tactic (ineq × expr) := do tp ← infer_type h, some (iq, e) ← return $ parse_into_comp_and_expr tp, if c = 0 then do e' ← mk_app ``zero_mul [e], return (eq, e') else if c = 1 then return (iq, h) else do nm ← resolve_name (ineq_const_mul_nm iq), tp ← (prod.snd <$> (infer_type h >>= get_rel_sides)) >>= infer_type, cpos ← to_expr ``((%%c.to_pexpr : %%tp) > 0), (_, ex) ← solve_aux cpos `[norm_num, done], -- e' ← mk_app (ineq_const_mul_nm iq) [h, ex], -- this takes many seconds longer in some examples! why? e' ← to_expr ``(%%nm %%h %%ex) ff, return (iq, e') meta def mk_lt_zero_pf_aux (c : ineq) (pf npf : expr) (coeff : ℕ) : tactic (ineq × expr) := do (iq, h') ← mk_single_comp_zero_pf coeff npf, let (nm, niq) := ineq_const_nm c iq, n ← resolve_name nm, e' ← to_expr ``(%%n %%pf %%h'), return (niq, e') /-- Takes a list of coefficients [c] and list of expressions, of equal length. Each expression is a proof of a prop of the form t {<, ≤, =} 0. Produces a proof that the sum of (c*t) {<, ≤, =} 0, where the comp is as strong as possible. -/ meta def mk_lt_zero_pf : list ℕ → list expr → tactic expr | _ [] := fail "no linear hypotheses found" | [c] [h] := prod.snd <$> mk_single_comp_zero_pf c h | (c::ct) (h::t) := do (iq, h') ← mk_single_comp_zero_pf c h, prod.snd <$> (ct.zip t).mfoldl (λ pr ce, mk_lt_zero_pf_aux pr.1 pr.2 ce.2 ce.1) (iq, h') | _ _ := fail "not enough args to mk_lt_zero_pf" meta def term_of_ineq_prf (prf : expr) : tactic expr := do (lhs, _) ← infer_type prf >>= get_rel_sides, return lhs meta structure linarith_config := (discharger : tactic unit := `[ring]) (restrict_type : option Type := none) (restrict_type_reflect : reflected restrict_type . apply_instance) (exfalso : bool := tt) (transparency : transparency := reducible) meta def ineq_pf_tp (pf : expr) : tactic expr := do (_, z) ← infer_type pf >>= get_rel_sides, infer_type z meta def mk_neg_one_lt_zero_pf (tp : expr) : tactic expr := to_expr ``((neg_neg_of_pos zero_lt_one : -1 < (0 : %%tp))) /-- Assumes e is a proof that t = 0. Creates a proof that -t = 0. -/ meta def mk_neg_eq_zero_pf (e : expr) : tactic expr := to_expr ``(neg_eq_zero.mpr %%e) meta def add_neg_eq_pfs : list expr → tactic (list expr) | [] := return [] | (h::t) := do some (iq, tp) ← parse_into_comp_and_expr <$> infer_type h, match iq with | ineq.eq := do nep ← mk_neg_eq_zero_pf h, tl ← add_neg_eq_pfs t, return $ h::nep::tl | _ := list.cons h <$> add_neg_eq_pfs t end /-- Takes a list of proofs of propositions of the form t {<, ≤, =} 0, and tries to prove the goal `false`. -/ meta def prove_false_by_linarith1 (cfg : linarith_config) : list expr → tactic unit | [] := fail "no args to linarith" | l@(h::t) := do l' ← add_neg_eq_pfs l, hz ← ineq_pf_tp h >>= mk_neg_one_lt_zero_pf, (sum.inl contr, inputs) ← elim_all_vars.run cfg.transparency (hz::l') | fail "linarith failed to find a contradiction", let coeffs := inputs.keys.map (λ k, (contr.src.flatten.ifind k)), let pfs : list expr := inputs.keys.map (λ k, (inputs.ifind k).1), let zip := (coeffs.zip pfs).filter (λ pr, pr.1 ≠ 0), let (coeffs, pfs) := zip.unzip, mls ← zip.mmap (λ pr, do e ← term_of_ineq_prf pr.2, return (mul_expr pr.1 e)), sm ← to_expr $ add_exprs mls, tgt ← to_expr ``(%%sm = 0), (a, b) ← solve_aux tgt (cfg.discharger >> done), pf ← mk_lt_zero_pf coeffs pfs, pftp ← infer_type pf, (_, nep, _) ← rewrite_core b pftp, pf' ← mk_eq_mp nep pf, mk_app `lt_irrefl [pf'] >>= exact end prove section normalize open tactic set_option eqn_compiler.max_steps 50000 meta def rem_neg (prf : expr) : expr → tactic expr | `(_ ≤ _) := to_expr ``(lt_of_not_ge %%prf) | `(_ < _) := to_expr ``(le_of_not_gt %%prf) | `(_ > _) := to_expr ``(le_of_not_gt %%prf) | `(_ ≥ _) := to_expr ``(lt_of_not_ge %%prf) | e := failed meta def rearr_comp : expr → expr → tactic expr | prf `(%%a ≤ 0) := return prf | prf `(%%a < 0) := return prf | prf `(%%a = 0) := return prf | prf `(%%a ≥ 0) := to_expr ``(neg_nonpos.mpr %%prf) | prf `(%%a > 0) := to_expr ``(neg_neg_of_pos %%prf) | prf `(0 ≥ %%a) := to_expr ``(show %%a ≤ 0, from %%prf) | prf `(0 > %%a) := to_expr ``(show %%a < 0, from %%prf) | prf `(0 = %%a) := to_expr ``(eq.symm %%prf) | prf `(0 ≤ %%a) := to_expr ``(neg_nonpos.mpr %%prf) | prf `(0 < %%a) := to_expr ``(neg_neg_of_pos %%prf) | prf `(%%a ≤ %%b) := to_expr ``(sub_nonpos.mpr %%prf) | prf `(%%a < %%b) := to_expr ``(sub_neg_of_lt %%prf) | prf `(%%a = %%b) := to_expr ``(sub_eq_zero.mpr %%prf) | prf `(%%a > %%b) := to_expr ``(sub_neg_of_lt %%prf) | prf `(%%a ≥ %%b) := to_expr ``(sub_nonpos.mpr %%prf) | prf `(¬ %%t) := do nprf ← rem_neg prf t, tp ← infer_type nprf, rearr_comp nprf tp | prf _ := fail "couldn't rearrange comp" meta def is_numeric : expr → option ℚ | `(%%e1 + %%e2) := (+) <$> is_numeric e1 <*> is_numeric e2 | `(%%e1 - %%e2) := has_sub.sub <$> is_numeric e1 <*> is_numeric e2 | `(%%e1 * %%e2) := (*) <$> is_numeric e1 <*> is_numeric e2 | `(%%e1 / %%e2) := (/) <$> is_numeric e1 <*> is_numeric e2 | `(-%%e) := rat.neg <$> is_numeric e | e := e.to_rat meta def find_cancel_factor : expr → ℕ × tree ℕ | `(%%e1 + %%e2) := let (v1, t1) := find_cancel_factor e1, (v2, t2) := find_cancel_factor e2, lcm := v1.lcm v2 in (lcm, tree.node lcm t1 t2) | `(%%e1 - %%e2) := let (v1, t1) := find_cancel_factor e1, (v2, t2) := find_cancel_factor e2, lcm := v1.lcm v2 in (lcm, tree.node lcm t1 t2) | `(%%e1 * %%e2) := match is_numeric e1, is_numeric e2 with | none, none := (1, tree.node 1 tree.nil tree.nil) | _, _ := let (v1, t1) := find_cancel_factor e1, (v2, t2) := find_cancel_factor e2, pd := v1*v2 in (pd, tree.node pd t1 t2) end | `(%%e1 / %%e2) := match is_numeric e2 with | some q := let (v1, t1) := find_cancel_factor e1, n := v1.lcm q.num.nat_abs in (n, tree.node n t1 (tree.node q.num.nat_abs tree.nil tree.nil)) | none := (1, tree.node 1 tree.nil tree.nil) end | `(-%%e) := find_cancel_factor e | _ := (1, tree.node 1 tree.nil tree.nil) open tree meta def mk_prod_prf : ℕ → tree ℕ → expr → tactic expr | v (node _ lhs rhs) `(%%e1 + %%e2) := do v1 ← mk_prod_prf v lhs e1, v2 ← mk_prod_prf v rhs e2, mk_app ``add_subst [v1, v2] | v (node _ lhs rhs) `(%%e1 - %%e2) := do v1 ← mk_prod_prf v lhs e1, v2 ← mk_prod_prf v rhs e2, mk_app ``sub_subst [v1, v2] | v (node n lhs@(node ln _ _) rhs) `(%%e1 * %%e2) := do tp ← infer_type e1, v1 ← mk_prod_prf ln lhs e1, v2 ← mk_prod_prf (v/ln) rhs e2, ln' ← tp.of_nat ln, vln' ← tp.of_nat (v/ln), v' ← tp.of_nat v, ntp ← to_expr ``(%%ln' * %%vln' = %%v'), (_, npf) ← solve_aux ntp `[norm_num, done], mk_app ``mul_subst [v1, v2, npf] | v (node n lhs rhs@(node rn _ _)) `(%%e1 / %%e2) := do tp ← infer_type e1, v1 ← mk_prod_prf (v/rn) lhs e1, rn' ← tp.of_nat rn, vrn' ← tp.of_nat (v/rn), n' ← tp.of_nat n, v' ← tp.of_nat v, ntp ← to_expr ``(%%rn' / %%e2 = 1), (_, npf) ← solve_aux ntp `[norm_num, done], ntp2 ← to_expr ``(%%vrn' * %%n' = %%v'), (_, npf2) ← solve_aux ntp2 `[norm_num, done], mk_app ``div_subst [v1, npf, npf2] | v t `(-%%e) := do v' ← mk_prod_prf v t e, mk_app ``neg_subst [v'] | v _ e := do tp ← infer_type e, v' ← tp.of_nat v, e' ← to_expr ``(%%v' * %%e), mk_app `eq.refl [e'] /-- e is a term with rational division. produces a natural number n and a proof that n*e = e', where e' has no division. -/ meta def kill_factors (e : expr) : tactic (ℕ × expr) := let (n, t) := find_cancel_factor e in do e' ← mk_prod_prf n t e, return (n, e') open expr meta def expr_contains (n : name) : expr → bool | (const nm _) := nm = n | (lam _ _ _ bd) := expr_contains bd | (pi _ _ _ bd) := expr_contains bd | (app e1 e2) := expr_contains e1 || expr_contains e2 | _ := ff lemma sub_into_lt {α} [ordered_semiring α] {a b : α} (he : a = b) (hl : a ≤ 0) : b ≤ 0 := by rwa he at hl meta def norm_hyp_aux (h' lhs : expr) : tactic expr := do (v, lhs') ← kill_factors lhs, if v = 1 then return h' else do (ih, h'') ← mk_single_comp_zero_pf v h', (_, nep, _) ← infer_type h'' >>= rewrite_core lhs', mk_eq_mp nep h'' meta def norm_hyp (h : expr) : tactic expr := do htp ← infer_type h, h' ← rearr_comp h htp, some (c, lhs) ← parse_into_comp_and_expr <$> infer_type h', if expr_contains `has_div.div lhs then norm_hyp_aux h' lhs else return h' meta def get_contr_lemma_name : expr → option name | `(%%a < %%b) := return `lt_of_not_ge | `(%%a ≤ %%b) := return `le_of_not_gt | `(%%a = %%b) := return ``eq_of_not_lt_of_not_gt | `(%%a ≠ %%b) := return `not.intro | `(%%a ≥ %%b) := return `le_of_not_gt | `(%%a > %%b) := return `lt_of_not_ge | `(¬ %%a < %%b) := return `not.intro | `(¬ %%a ≤ %%b) := return `not.intro | `(¬ %%a = %%b) := return `not.intro | `(¬ %%a ≥ %%b) := return `not.intro | `(¬ %%a > %%b) := return `not.intro | _ := none -- assumes the input t is of type ℕ. Produces t' of type ℤ such that ↑t = t' and a proof of equality meta def cast_expr (e : expr) : tactic (expr × expr) := do s ← [`int.coe_nat_add, `int.coe_nat_zero, `int.coe_nat_one, ``int.coe_nat_bit0_mul, ``int.coe_nat_bit1_mul, ``int.coe_nat_zero_mul, ``int.coe_nat_one_mul, ``int.coe_nat_mul_bit0, ``int.coe_nat_mul_bit1, ``int.coe_nat_mul_zero, ``int.coe_nat_mul_one, ``int.coe_nat_bit0, ``int.coe_nat_bit1].mfoldl simp_lemmas.add_simp simp_lemmas.mk, ce ← to_expr ``(↑%%e : ℤ), simplify s [] ce {fail_if_unchanged := ff} meta def is_nat_int_coe : expr → option expr | `((↑(%%n : ℕ) : ℤ)) := some n | _ := none meta def mk_coe_nat_nonneg_prf (e : expr) : tactic expr := mk_app `int.coe_nat_nonneg [e] meta def get_nat_comps : expr → list expr | `(%%a + %%b) := (get_nat_comps a).append (get_nat_comps b) | `(%%a * %%b) := (get_nat_comps a).append (get_nat_comps b) | e := match is_nat_int_coe e with | some e' := [e'] | none := [] end meta def mk_coe_nat_nonneg_prfs (e : expr) : tactic (list expr) := (get_nat_comps e).mmap mk_coe_nat_nonneg_prf meta def mk_cast_eq_and_nonneg_prfs (pf a b : expr) (ln : name) : tactic (list expr) := do (a', prfa) ← cast_expr a, (b', prfb) ← cast_expr b, la ← mk_coe_nat_nonneg_prfs a', lb ← mk_coe_nat_nonneg_prfs b', pf' ← mk_app ln [pf, prfa, prfb], return $ pf'::(la.append lb) meta def mk_int_pfs_of_nat_pf (pf : expr) : tactic (list expr) := do tp ← infer_type pf, match tp with | `(%%a = %%b) := mk_cast_eq_and_nonneg_prfs pf a b ``nat_eq_subst | `(%%a ≤ %%b) := mk_cast_eq_and_nonneg_prfs pf a b ``nat_le_subst | `(%%a < %%b) := mk_cast_eq_and_nonneg_prfs pf a b ``nat_lt_subst | `(%%a ≥ %%b) := mk_cast_eq_and_nonneg_prfs pf b a ``nat_le_subst | `(%%a > %%b) := mk_cast_eq_and_nonneg_prfs pf b a ``nat_lt_subst | `(¬ %%a ≤ %%b) := do pf' ← mk_app ``lt_of_not_ge [pf], mk_cast_eq_and_nonneg_prfs pf' b a ``nat_lt_subst | `(¬ %%a < %%b) := do pf' ← mk_app ``le_of_not_gt [pf], mk_cast_eq_and_nonneg_prfs pf' b a ``nat_le_subst | `(¬ %%a ≥ %%b) := do pf' ← mk_app ``lt_of_not_ge [pf], mk_cast_eq_and_nonneg_prfs pf' a b ``nat_lt_subst | `(¬ %%a > %%b) := do pf' ← mk_app ``le_of_not_gt [pf], mk_cast_eq_and_nonneg_prfs pf' a b ``nat_le_subst | _ := fail "mk_int_pfs_of_nat_pf failed: proof is not an inequality" end meta def mk_non_strict_int_pf_of_strict_int_pf (pf : expr) : tactic expr := do tp ← infer_type pf, match tp with | `(%%a < %%b) := to_expr ``(@cast (%%a < %%b) (%%a + 1 ≤ %%b) (by refl) %%pf) | `(%%a > %%b) := to_expr ``(@cast (%%a > %%b) (%%a ≥ %%b + 1) (by refl) %%pf) | `(¬ %%a ≤ %%b) := to_expr ``(@cast (%%a > %%b) (%%a ≥ %%b + 1) (by refl) (lt_of_not_ge %%pf)) | `(¬ %%a ≥ %%b) := to_expr ``(@cast (%%a < %%b) (%%a + 1 ≤ %%b) (by refl) (lt_of_not_ge %%pf)) | _ := fail "mk_non_strict_int_pf_of_strict_int_pf failed: proof is not an inequality" end meta def guard_is_nat_prop : expr → tactic unit | `(%%a = _) := infer_type a >>= unify `(ℕ) | `(%%a ≤ _) := infer_type a >>= unify `(ℕ) | `(%%a < _) := infer_type a >>= unify `(ℕ) | `(%%a ≥ _) := infer_type a >>= unify `(ℕ) | `(%%a > _) := infer_type a >>= unify `(ℕ) | `(¬ %%p) := guard_is_nat_prop p | _ := failed meta def guard_is_strict_int_prop : expr → tactic unit | `(%%a < _) := infer_type a >>= unify `(ℤ) | `(%%a > _) := infer_type a >>= unify `(ℤ) | `(¬ %%a ≤ _) := infer_type a >>= unify `(ℤ) | `(¬ %%a ≥ _) := infer_type a >>= unify `(ℤ) | _ := failed meta def replace_nat_pfs : list expr → tactic (list expr) | [] := return [] | (h::t) := (do infer_type h >>= guard_is_nat_prop, ls ← mk_int_pfs_of_nat_pf h, list.append ls <$> replace_nat_pfs t) <|> list.cons h <$> replace_nat_pfs t meta def replace_strict_int_pfs : list expr → tactic (list expr) | [] := return [] | (h::t) := (do infer_type h >>= guard_is_strict_int_prop, l ← mk_non_strict_int_pf_of_strict_int_pf h, list.cons l <$> replace_strict_int_pfs t) <|> list.cons h <$> replace_strict_int_pfs t meta def partition_by_type_aux : rb_lmap expr expr → list expr → tactic (rb_lmap expr expr) | m [] := return m | m (h::t) := do tp ← ineq_pf_tp h, partition_by_type_aux (m.insert tp h) t meta def partition_by_type (l : list expr) : tactic (rb_lmap expr expr) := partition_by_type_aux mk_rb_map l private meta def try_linarith_on_lists (cfg : linarith_config) (ls : list (list expr)) : tactic unit := (first $ ls.map $ prove_false_by_linarith1 cfg) <|> fail "linarith failed" /-- Takes a list of proofs of propositions. Filters out the proofs of linear (in)equalities, and tries to use them to prove `false`. If pref_type is given, starts by working over this type -/ meta def prove_false_by_linarith (cfg : linarith_config) (pref_type : option expr) (l : list expr) : tactic unit := do l' ← replace_nat_pfs l, l'' ← replace_strict_int_pfs l', ls ← list.reduce_option <$> l''.mmap (λ h, (do s ← norm_hyp h, return (some s)) <|> return none) >>= partition_by_type, pref_type ← (unify pref_type.iget `(ℕ) >> return (some `(ℤ) : option expr)) <|> return pref_type, match cfg.restrict_type, ls.values, pref_type with | some rtp, _, _ := do m ← mk_mvar, unify `(some %%m : option Type) cfg.restrict_type_reflect, m ← instantiate_mvars m, prove_false_by_linarith1 cfg (ls.ifind m) | none, [ls'], _ := prove_false_by_linarith1 cfg ls' | none, ls', none := try_linarith_on_lists cfg ls' | none, _, (some t) := prove_false_by_linarith1 cfg (ls.ifind t) <|> try_linarith_on_lists cfg (ls.erase t).values end end normalize end linarith section open tactic linarith open lean lean.parser interactive tactic interactive.types local postfix `?`:9001 := optional local postfix *:9001 := many meta def linarith.elab_arg_list : option (list pexpr) → tactic (list expr) | none := return [] | (some l) := l.mmap i_to_expr meta def linarith.preferred_type_of_goal : option expr → tactic (option expr) | none := return none | (some e) := some <$> ineq_pf_tp e /-- linarith.interactive_aux cfg o_goal restrict_hyps args: * cfg is a linarith_config object * o_goal : option expr is the local constant corresponding to the former goal, if there was one * restrict_hyps : bool is tt if `linarith only [...]` was used * args : option (list pexpr) is the optional list of arguments in `linarith [...]` -/ meta def linarith.interactive_aux (cfg : linarith_config) : option expr → bool → option (list pexpr) → tactic unit | none tt none := fail "linarith only called with no arguments" | none tt (some l) := l.mmap i_to_expr >>= prove_false_by_linarith cfg none | (some e) tt l := do tp ← ineq_pf_tp e, list.cons e <$> linarith.elab_arg_list l >>= prove_false_by_linarith cfg (some tp) | oe ff l := do otp ← linarith.preferred_type_of_goal oe, list.append <$> local_context <*> (list.filter (λ a, bnot $ expr.is_local_constant a) <$> linarith.elab_arg_list l) >>= prove_false_by_linarith cfg otp /-- Tries to prove a goal of `false` by linear arithmetic on hypotheses. If the goal is a linear (in)equality, tries to prove it by contradiction. If the goal is not `false` or an inequality, applies `exfalso` and tries linarith on the hypotheses. `linarith` will use all relevant hypotheses in the local context. `linarith [t1, t2, t3]` will add proof terms t1, t2, t3 to the local context. `linarith only [h1, h2, h3, t1, t2, t3]` will use only the goal (if relevant), local hypotheses h1, h2, h3, and proofs t1, t2, t3. It will ignore the rest of the local context. `linarith!` will use a stronger reducibility setting to identify atoms. Config options: `linarith {exfalso := ff}` will fail on a goal that is neither an inequality nor `false` `linarith {restrict_type := T}` will run only on hypotheses that are inequalities over `T` `linarith {discharger := tac}` will use `tac` instead of `ring` for normalization. Options: `ring2`, `ring SOP`, `simp` -/ meta def tactic.interactive.linarith (red : parse ((tk "!")?)) (restr : parse ((tk "only")?)) (hyps : parse pexpr_list?) (cfg : linarith_config := {}) : tactic unit := let cfg := if red.is_some then {cfg with transparency := semireducible, discharger := `[ring!]} else cfg in do t ← target, match get_contr_lemma_name t with | some nm := seq (applyc nm) $ do t ← intro1, linarith.interactive_aux cfg (some t) restr.is_some hyps | none := if cfg.exfalso then exfalso >> linarith.interactive_aux cfg none restr.is_some hyps else fail "linarith failed: target type is not an inequality." end end
61a8b63b1e1e60d9e993cd7413c45a595b79603e
d7189ea2ef694124821b033e533f18905b5e87ef
/galois/crypto/hmac.lean
1470c78d30c76a7a0dee0dd8f094323c588f7525
[ "Apache-2.0" ]
permissive
digama0/lean-protocol-support
eaa7e6f8b8e0d5bbfff1f7f52bfb79a3b11b0f59
cabfa3abedbdd6fdca6e2da6fbbf91a13ed48dda
refs/heads/master
1,625,421,450,627
1,506,035,462,000
1,506,035,462,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,410
lean
/- This defines an hmac primitive. -/ import galois.word import galois.tactic.nat import galois.bitvec.join import galois.crypto.sha2 namespace crypto definition hmac {olen : ℕ} -- ^ Output length (blen : ℕ) -- ^ Block length (hash : list byte → vector byte olen) (key : list byte) (msg : list byte) : vector byte olen := let klen := list.length key in let padded_key := if blen ≥ klen then key ++ list.repeat 0 (blen - klen) else key ++ list.repeat 0 (blen - olen) in let ki := list.map (bitvec.xor 54) padded_key in let ko := list.map (bitvec.xor 92) padded_key in hash (ko ++ (hash (ki ++ msg))^.to_list) end crypto namespace hmac /- hash_algorithm -/ inductive hash_algorithm | sha1 : hash_algorithm | sha2_256 : hash_algorithm | ripemd160 : hash_algorithm | sha2_224 : hash_algorithm | sha2_384 : hash_algorithm | sha2_512 : hash_algorithm | sha3_224 : hash_algorithm | sha3_256 : hash_algorithm | sha3_384 : hash_algorithm | sha3_512 : hash_algorithm | sm3 : hash_algorithm namespace hash_algorithm protected def to_string : hash_algorithm → string | sha1 := "sha1" | sha2_256 := "sha2_256" | ripemd160 := "ripemd160" | sha2_224 := "sha2_224" | sha2_384 := "sha2_384" | sha2_512 := "sha2_512" | sha3_224 := "sha3_224" | sha3_256 := "sha3_256" | sha3_384 := "sha3_384" | sha3_512 := "sha3_512" | sm3 := "sm3" instance : has_to_string hash_algorithm := ⟨ hash_algorithm.to_string ⟩ /- hash length in bytes -/ definition hash_length : hash_algorithm → ℕ | sha1 := 20 | sha2_256 := 32 | ripemd160 := 20 | sha2_224 := 28 | sha2_384 := 48 | sha2_512 := 64 | sha3_224 := 28 | sha3_256 := 32 | sha3_384 := 48 | sha3_512 := 64 | sm3 := 32 lemma max_hash_length (algo : hash_algorithm) : algo.hash_length ≤ 64 := begin cases algo, all_goals { dunfold hash_length }, all_goals { galois.tactic.nat.nat_lit_le }, end /- block length in bytes -/ definition block_length (algo : hash_algorithm) : ℕ := match algo with | sha1 := 64 | sha2_256 := 64 | ripemd160 := 64 | sha2_224 := 64 | sha2_384 := 128 | sha2_512 := 128 | sha3_224 := 144 | sha3_256 := 136 | sha3_384 := 104 | sha3_512 := 72 | sm3 := 64 end definition encode (algo : hash_algorithm) : byte := match algo with | sha1 := 0x0 | sha2_256 := 0x1 | ripemd160 := 0x2 | sha2_224 := 0x3 | sha2_384 := 0x4 | sha2_512 := 0x5 | sha3_224 := 0x7 | sha3_256 := 0x8 | sha3_384 := 0x9 | sha3_512 := 0xA | sm3 := 0xB end definition decode (w : byte) : option hash_algorithm := if w = 0x0 then some sha1 else if w = 0x1 then some sha2_256 else if w = 0x2 then some ripemd160 else if w = 0x3 then some sha2_224 else if w = 0x4 then some sha2_384 else if w = 0x5 then some sha2_512 else if w = 0x7 then some sha3_224 else if w = 0x8 then some sha3_256 else if w = 0x9 then some sha3_384 else if w = 0xA then some sha3_512 else if w = 0xB then some sm3 else none @[simp] lemma decode_encode (a : hash_algorithm) : decode (encode a) = some a := begin cases a, simp [encode, decode], all_goals { simp [encode, decode], smt_tactic.execute smt_tactic.solve_goals } end instance : decidable_eq hash_algorithm := by tactic.mk_dec_eq_instance ------------------------------------------------------------------------ -- hash -- | Helper function to speed up length proofs below def to_byte_list (m : ℕ) (v : bitvec (8 * m)) : list byte := cast rfl (@bitvec.split_vector 8 m v) protected lemma length_to_byte_list (m : ℕ) (v : bitvec (8 * m)) : (to_byte_list m v).length = m := vector.length_split_vector _ _ def nat_224_decompose : bitvec 224 → list byte := @to_byte_list 28 def nat_256_decompose : bitvec 256 → list byte := @to_byte_list 32 def nat_384_decompose : bitvec 384 → list byte := @to_byte_list 48 def nat_512_decompose : bitvec 512 → list byte := @to_byte_list 64 definition hash : hash_algorithm → list byte → list byte | sha2_256 data := nat_256_decompose (crypto.sha256 data) | sha2_224 data := nat_224_decompose (crypto.sha224 data) | sha2_384 data := nat_384_decompose (crypto.sha384 data) | sha2_512 data := nat_512_decompose (crypto.sha512 data) | algo data := list.repeat 0 (algo.hash_length) theorem length_hash_is_hash_length : ∀ (algo : hash_algorithm) (data : list byte), (algo.hash data).length = algo.hash_length | sha1 data := list.length_repeat _ _ | sha2_256 data := hash_algorithm.length_to_byte_list _ _ | ripemd160 data := list.length_repeat _ _ | sha2_224 data := hash_algorithm.length_to_byte_list _ _ | sha2_384 data := hash_algorithm.length_to_byte_list _ _ | sha2_512 data := hash_algorithm.length_to_byte_list _ _ | sha3_224 data := list.length_repeat _ _ | sha3_256 data := list.length_repeat _ _ | sha3_384 data := list.length_repeat _ _ | sha3_512 data := list.length_repeat _ _ | sm3 data := list.length_repeat _ _ -- Hash the data using the given algorithm. definition hashv (algo : hash_algorithm) (data : list byte) : vector byte algo.hash_length := ⟨ hash algo data, length_hash_is_hash_length algo data ⟩ end hash_algorithm end hmac
5e0ec39fa6aa6e44888db8796aeee729023cd95f
bdb33f8b7ea65f7705fc342a178508e2722eb851
/analysis/complex.lean
38c672ce64c7d96f1a4861118e7666c3ad1a6f15
[ "Apache-2.0" ]
permissive
rwbarton/mathlib
939ae09bf8d6eb1331fc2f7e067d39567e10e33d
c13c5ea701bb1eec057e0a242d9f480a079105e9
refs/heads/master
1,584,015,335,862
1,524,142,167,000
1,524,142,167,000
130,614,171
0
0
Apache-2.0
1,548,902,667,000
1,524,437,371,000
Lean
UTF-8
Lean
false
false
4,338
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Topology of the complex numbers. -/ import data.complex.basic analysis.metric_space noncomputable theory open filter namespace complex -- TODO(Mario): these proofs are all copied from analysis/real. Generalize -- to normed fields instance : metric_space ℂ := { dist := λx y, (x - y).abs, dist_self := by simp [abs_zero], eq_of_dist_eq_zero := by simp [add_neg_eq_zero], dist_comm := assume x y, by rw [complex.abs_sub], dist_triangle := assume x y z, complex.abs_sub_le _ _ _ } theorem dist_eq (x y : ℂ) : dist x y = (x - y).abs := rfl theorem uniform_continuous_add : uniform_continuous (λp : ℂ × ℂ, p.1 + p.2) := uniform_continuous_of_metric.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_add_continuous_lemma abs ε0 in ⟨δ, δ0, λ a b h, let ⟨h₁, h₂⟩ := max_lt_iff.1 h in Hδ h₁ h₂⟩ theorem uniform_continuous_neg : uniform_continuous (@has_neg.neg ℂ _) := uniform_continuous_of_metric.2 $ λ ε ε0, ⟨_, ε0, λ a b h, by rw dist_comm at h; simpa [dist_eq] using h⟩ instance : uniform_add_group ℂ := uniform_add_group.mk' uniform_continuous_add uniform_continuous_neg instance : topological_add_group ℂ := by apply_instance lemma uniform_continuous_inv (s : set ℂ) {r : ℝ} (r0 : 0 < r) (H : ∀ x ∈ s, r ≤ abs x) : uniform_continuous (λp:s, p.1⁻¹) := uniform_continuous_of_metric.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_inv_continuous_lemma abs ε0 r0 in ⟨δ, δ0, λ a b h, Hδ (H _ a.2) (H _ b.2) h⟩ lemma uniform_continuous_abs : uniform_continuous (abs : ℂ → ℝ) := uniform_continuous_of_metric.2 $ λ ε ε0, ⟨ε, ε0, λ a b, lt_of_le_of_lt (abs_abs_sub_le_abs_sub _ _)⟩ lemma continuous_abs : continuous (abs : ℂ → ℝ) := uniform_continuous_abs.continuous lemma tendsto_inv {r : ℂ} (r0 : r ≠ 0) : tendsto (λq, q⁻¹) (nhds r) (nhds r⁻¹) := by rw ← abs_pos at r0; exact tendsto_of_uniform_continuous_subtype (uniform_continuous_inv {x | abs r / 2 < abs x} (half_pos r0) (λ x h, le_of_lt h)) (mem_nhds_sets (continuous_abs _ $ is_open_lt' (abs r / 2)) (half_lt_self r0)) lemma continuous_inv' : continuous (λa:{r:ℂ // r ≠ 0}, a.val⁻¹) := continuous_iff_tendsto.mpr $ assume ⟨r, hr⟩, (continuous_iff_tendsto.mp continuous_subtype_val _).comp (tendsto_inv hr) lemma continuous_inv {α} [topological_space α] {f : α → ℂ} (h : ∀a, f a ≠ 0) (hf : continuous f) : continuous (λa, (f a)⁻¹) := show continuous ((has_inv.inv ∘ @subtype.val ℂ (λr, r ≠ 0)) ∘ λa, ⟨f a, h a⟩), from (continuous_subtype_mk _ hf).comp continuous_inv' lemma uniform_continuous_mul_const {x : ℂ} : uniform_continuous ((*) x) := uniform_continuous_of_metric.2 $ λ ε ε0, begin cases no_top (abs x) with y xy, have y0 := lt_of_le_of_lt (abs_nonneg _) xy, refine ⟨_, div_pos ε0 y0, λ a b h, _⟩, rw [dist_eq, ← mul_sub, abs_mul, ← mul_div_cancel' ε (ne_of_gt y0)], exact mul_lt_mul' (le_of_lt xy) h (abs_nonneg _) y0 end lemma uniform_continuous_mul (s : set (ℂ × ℂ)) {r₁ r₂ : ℝ} (r₁0 : 0 < r₁) (r₂0 : 0 < r₂) (H : ∀ x ∈ s, abs (x : ℂ × ℂ).1 < r₁ ∧ abs x.2 < r₂) : uniform_continuous (λp:s, p.1.1 * p.1.2) := uniform_continuous_of_metric.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_mul_continuous_lemma abs ε0 r₁0 r₂0 in ⟨δ, δ0, λ a b h, let ⟨h₁, h₂⟩ := max_lt_iff.1 h in Hδ (H _ a.2).1 (H _ b.2).2 h₁ h₂⟩ lemma continuous_mul : continuous (λp : ℂ × ℂ, p.1 * p.2) := continuous_iff_tendsto.2 $ λ ⟨a₁, a₂⟩, tendsto_of_uniform_continuous_subtype (uniform_continuous_mul ({x | abs x < abs a₁ + 1}.prod {x | abs x < abs a₂ + 1}) (lt_of_le_of_lt (abs_nonneg _) (lt_add_one _)) (lt_of_le_of_lt (abs_nonneg _) (lt_add_one _)) (λ x, id)) (mem_nhds_sets (is_open_prod (continuous_abs _ $ is_open_gt' _) (continuous_abs _ $ is_open_gt' _)) ⟨lt_add_one (abs a₁), lt_add_one (abs a₂)⟩) instance : topological_ring ℂ := { continuous_mul := continuous_mul, ..complex.topological_add_group } instance : topological_semiring ℂ := by apply_instance end complex
d0bc59ba5bfab348ce25809628b9b882d1a0232c
6f1049e897f569e5c47237de40321e62f0181948
/src/solutions/09_limits_final.lean
23599ad3df185e7308e6bea6d03156997f74869a
[ "Apache-2.0" ]
permissive
anrddh/tutorials
f654a0807b9523608544836d9a81939f8e1dceb8
3ba43804e7b632201c494cdaa8da5406f1a255f9
refs/heads/master
1,655,542,921,827
1,588,846,595,000
1,588,846,595,000
262,330,134
0
0
null
1,588,944,346,000
1,588,944,345,000
null
UTF-8
Lean
false
false
12,805
lean
import tuto_lib set_option pp.beta true set_option pp.coercions false /- This is the final file in this series. Here we use everything covered in previous files to prove a couple of famous theorems from elementary real analysis. Of course they all have more general versions in mathlib. As usual, keep in mind: abs_le (x y : ℝ) : |x| ≤ y ↔ -y ≤ x ∧ x ≤ y ge_max_iff (p q r) : r ≥ max p q ↔ r ≥ p ∧ r ≥ q le_max_left p q : p ≤ max p q le_max_right p q : q ≤ max p q as well as a lemma from the previous file: le_of_le_add_all : (∀ ε > 0, y ≤ x + ε) → y ≤ x Let's start with a variation on a known exercise. -/ -- 0071 lemma le_lim {x y : ℝ} {u : ℕ → ℝ} (hu : seq_limit u x) (ineg : ∃ N, ∀ n ≥ N, y ≤ u n) : y ≤ x := begin -- sorry apply le_of_le_add_all, intros ε ε_pos, cases hu ε ε_pos with N hN, cases ineg with N' hN', let N₀ := max N N', specialize hN N₀ (le_max_left N N'), specialize hN' N₀ (le_max_right N N'), rw abs_le at hN, linarith, -- sorry end /- Let's now return to the result proved in the 0th file of this series, and reprove the sequential characterization of upper bounds (with a slighly different proof). For this, and other exercises below, we'll need many things proved in previous files, and a couple of extras. From the 5th file: limit_const (x : ℝ) : seq_limit (λ n, x) x squeeze (lim_u : seq_limit u l) (lim_w : seq_limit w l) (hu : ∀ n, u n ≤ v n) (hw : ∀ n, v n ≤ w n) : seq_limit v l From the 8th: def upper_bound (A : set ℝ) (x : ℝ) := ∀ a ∈ A, a ≤ x def is_sup (A : set ℝ) (x : ℝ) := upper_bound A x ∧ ∀ y, upper_bound A y → x ≤ y lt_sup (hx : is_sup A x) : ∀ y, y < x → ∃ a ∈ A, y < a := You can also use inv_succ_pos : ∀ n : ℕ, 1/(n + 1 : ℝ) > 0 inv_succ_le_all : ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, 1/(n + 1 : ℝ) ≤ ε and their easy consequences: limit_of_sub_le_inv_succ (h : ∀ n, |u n - x| ≤ 1/(n+1)) : seq_limit u x limit_const_add_inv_succ (x : ℝ) : seq_limit (λ n, x + 1/(n+1)) x limit_const_sub_inv_succ (x : ℝ) : seq_limit (λ n, x - 1/(n+1)) x The structure of the proof is offered. It features a new tactic: `choose` which invokes the axiom of choice (observing the tactic state before and after using it should be enough to understand everything). -/ -- 0072 lemma is_sup_iff (A : set ℝ) (x : ℝ) : (is_sup A x) ↔ (upper_bound A x ∧ ∃ u : ℕ → ℝ, seq_limit u x ∧ ∀ n, u n ∈ A ) := begin split, { intro h, split, { -- sorry exact h.left, -- sorry }, { have : ∀ n : ℕ, ∃ a ∈ A, x - 1/(n+1) < a, { intros n, have : 1/(n+1 : ℝ) > 0, exact nat.one_div_pos_of_nat, -- sorry exact lt_sup h _ (by linarith), -- sorry }, choose u hu using this, -- sorry use u, split, { apply squeeze (limit_const_sub_inv_succ x) (limit_const x), { intros n, exact le_of_lt (hu n).2, }, { intro n, exact h.1 _ (hu n).left, } }, { intro n, exact (hu n).left }, -- sorry } }, { rintro ⟨maj, u, limu, u_in⟩, -- sorry split, { exact maj }, { intros y ymaj, apply lim_le limu, intro n, apply ymaj, apply u_in }, -- sorry }, end /-- Continuity of a function at a point -/ def continuous_at_pt (f : ℝ → ℝ) (x₀ : ℝ) : Prop := ∀ ε > 0, ∃ δ > 0, ∀ x, |x - x₀| ≤ δ → |f x - f x₀| ≤ ε variables {f : ℝ → ℝ} {x₀ : ℝ} {u : ℕ → ℝ} -- 0073 lemma seq_continuous_of_continuous (hf : continuous_at_pt f x₀) (hu : seq_limit u x₀) : seq_limit (f ∘ u) (f x₀) := begin -- sorry intros ε ε_pos, rcases hf ε ε_pos with ⟨δ, δ_pos, hδ⟩, cases hu δ δ_pos with N hN, use N, intros n hn, apply hδ, exact hN n hn, -- sorry end -- 0074 example : (∀ u : ℕ → ℝ, seq_limit u x₀ → seq_limit (f ∘ u) (f x₀)) → continuous_at_pt f x₀ := begin -- sorry contrapose!, intro hf, unfold continuous_at_pt at hf, push_neg at hf, cases hf with ε h, cases h with ε_pos hf, have H : ∀ n : ℕ, ∃ x, |x - x₀| ≤ 1/(n+1) ∧ ε < |f x - f x₀|, intro n, apply hf, exact nat.one_div_pos_of_nat, clear hf, choose u hu using H, use u, split, intros η η_pos, have fait : ∃ (N : ℕ), ∀ (n : ℕ), n ≥ N → 1 / (↑n + 1) ≤ η, exact inv_succ_le_all η η_pos, cases fait with N hN, use N, intros n hn, calc |u n - x₀| ≤ 1/(n+1) : (hu n).left ... ≤ η : hN n hn, unfold seq_limit, push_neg, use [ε, ε_pos], intro N, use N, split, linarith, exact (hu N).right, -- sorry end /- Recall from the 6th file: def extraction (φ : ℕ → ℕ) := ∀ n m, n < m → φ n < φ m def cluster_point (u : ℕ → ℝ) (a : ℝ) := ∃ φ, extraction φ ∧ seq_limit (u ∘ φ) a id_le_extraction : extraction φ → ∀ n, n ≤ φ n and from the 8th file: def tendsto_infinity (u : ℕ → ℝ) := ∀ A, ∃ N, ∀ n ≥ N, u n ≥ A not_seq_limit_of_tendstoinfinity : tendsto_infinity u → ∀ l, ¬ seq_limit u l -/ variables {φ : ℕ → ℕ} -- 0075 lemma subseq_tenstoinfinity (h : tendsto_infinity u) (hφ : extraction φ) : tendsto_infinity (u ∘ φ) := begin -- sorry intros A, cases h A with N hN, use N, intros n hn, apply hN, calc N ≤ n : hn ... ≤ φ n : id_le_extraction hφ n, -- sorry end -- 0076 lemma squeeze_infinity {u v : ℕ → ℝ} (hu : tendsto_infinity u) (huv : ∀ n, u n ≤ v n) : tendsto_infinity v := begin -- sorry intros A, cases hu A with N hN, use N, intros n hn, specialize hN n hn, specialize huv n, linarith, -- sorry end /- We will use segments Icc a b := { x | a ≤ x ∧ x ≤ b } The notation stands for Interval-closed-closed. Variations exist with o or i instead of c, where o stands for open and i for infinity. We will use the following version of Bolzano-Weirstrass bolzano_weierstrass (h : ∀ n, u n ∈ [a, b]) : ∃ c ∈ [a, b], cluster_point u c as well as the obvious seq_limit_id : tendsto_infinity (λ n, n) -/ open set -- 0077 lemma bdd_above_segment {f : ℝ → ℝ} {a b : ℝ} (hf : ∀ x ∈ Icc a b, continuous_at_pt f x) : ∃ M, ∀ x ∈ Icc a b, f x ≤ M := begin -- sorry by_contradiction H, push_neg at H, have clef : ∀ n : ℕ, ∃ x, x ∈ Icc a b ∧ f x > n, intro n, apply H, clear H, choose u hu using clef, have lim_infinie : tendsto_infinity (f ∘ u), apply squeeze_infinity (seq_limit_id), intros n, specialize hu n, linarith, have bornes : ∀ n, u n ∈ Icc a b, intro n, exact (hu n).left, rcases bolzano_weierstrass bornes with ⟨c, c_dans, φ, φ_extr, lim⟩, have lim_infinie_extr : tendsto_infinity (f ∘ (u ∘ φ)), exact subseq_tenstoinfinity lim_infinie φ_extr, have lim_extr : seq_limit (f ∘ (u ∘ φ)) (f c), exact seq_continuous_of_continuous (hf c c_dans) lim, exact not_seq_limit_of_tendstoinfinity lim_infinie_extr (f c) lim_extr, -- sorry end /- In the next exercice, we can use: abs_neg x : |-x| = |x| -/ -- 0078 lemma continuous_opposite {f : ℝ → ℝ} {x₀ : ℝ} (h : continuous_at_pt f x₀) : continuous_at_pt (λ x, -f x) x₀ := begin -- sorry intros ε ε_pos, cases h ε ε_pos with δ h, cases h with δ_pos h, use [δ, δ_pos], intros y hy, have : -f y - -f x₀ = -(f y - f x₀), ring, rw [this, abs_neg], exact h y hy, -- sorry end /- Now let's combine the two exercices above -/ -- 0079 lemma bdd_below_segment {f : ℝ → ℝ} {a b : ℝ} (hf : ∀ x ∈ Icc a b, continuous_at_pt f x) : ∃ m, ∀ x ∈ Icc a b, m ≤ f x := begin -- sorry have : ∃ M, ∀ x ∈ Icc a b, -f x ≤ M, { apply bdd_above_segment, intros x x_dans, exact continuous_opposite (hf x x_dans), }, cases this with M hM, use -M, intros x x_dans, specialize hM x x_dans, linarith, -- sorry end /- Remember from the 5th file: unique_limit : seq_limit u l → seq_limit u l' → l = l' and from the 6th one: subseq_tendsto_of_tendsto (h : seq_limit u l) (hφ : extraction φ) : seq_limit (u ∘ φ) l We now admit the following version of the least upper bound theorem (that cannot be proved without discussing the construction of real numbers or admitting another strong theorem). sup_segment {a b : ℝ} {A : set ℝ} (hnonvide : ∃ x, x ∈ A) (h : A ⊆ Icc a b) : ∃ x ∈ Icc a b, is_sup A x In the next exercise, it can be useful to prove inclusions of sets of real number. By definition, A ⊆ B means : ∀ x, x ∈ A → x ∈ B. Hence one can start a proof of A ⊆ B by `intros x x_in`, which brings `x : ℝ` and `x_in : x ∈ A` in the local context, and then prove `x ∈ B`. Note also the use of {x | P x} which denotes the set of x satisfying predicate P. Hence `x' ∈ { x | P x} ↔ P x'`, by definition. -/ -- 0080 example {a b : ℝ} (hab : a ≤ b) (hf : ∀ x ∈ Icc a b, continuous_at_pt f x) : ∃ x₀ ∈ Icc a b, ∀ x ∈ Icc a b, f x ≤ f x₀ := begin -- sorry cases bdd_below_segment hf with m hm, cases bdd_above_segment hf with M hM, let A := {y | ∃ x ∈ Icc a b, y = f x}, obtain ⟨y₀, y_dans, y_sup⟩ : ∃ y₀ ∈ Icc m M, is_sup A y₀, { apply sup_segment, { use [f a, a, by linarith, hab, by ring], }, { rintros y ⟨x, x_in, rfl⟩, exact ⟨hm x x_in, hM x x_in⟩ } }, rw is_sup_iff at y_sup, rcases y_sup with ⟨y_maj, u, lim_u, u_dans⟩, choose v hv using u_dans, cases forall_and_distrib.mp hv with v_dans hufv, replace hufv : u = f ∘ v := funext hufv, rcases bolzano_weierstrass v_dans with ⟨x₀, x₀_in, φ, φ_extr, lim_vφ⟩, use [x₀, x₀_in], intros x x_dans, have lim : seq_limit (f ∘ v ∘ φ) (f x₀), { apply seq_continuous_of_continuous, exact hf x₀ x₀_in, exact lim_vφ }, have unique : f x₀ = y₀, { apply unique_limit lim, rw hufv at lim_u, exact subseq_tendsto_of_tendsto lim_u φ_extr }, rw unique, apply y_maj, use [x, x_dans], -- sorry end lemma stupid {a b x : ℝ} (h : x ∈ Icc a b) (h' : x ≠ b) : x < b := lt_of_le_of_ne h.right h' /- And now the final boss... -/ def I := (Icc 0 1 : set ℝ) -- the type ascription makes sure 0 and 1 are real numbers here -- 0081 example (f : ℝ → ℝ) (hf : ∀ x, continuous_at_pt f x) (h₀ : f 0 < 0) (h₁ : f 1 > 0) : ∃ x₀ ∈ I, f x₀ = 0 := begin let A := { x | x ∈ I ∧ f x < 0}, have ex_x₀ : ∃ x₀ ∈ I, is_sup A x₀, { -- sorry apply sup_segment, use 0, split, split, linarith, linarith, exact h₀, intros x hx, exact hx.left -- sorry }, rcases ex_x₀ with ⟨x₀, x₀_in, x₀_sup⟩, use [x₀, x₀_in], have : f x₀ ≤ 0, { -- sorry rw is_sup_iff at x₀_sup, rcases x₀_sup with ⟨maj_x₀, u, lim_u, u_dans⟩, have : seq_limit (f ∘ u) (f x₀), exact seq_continuous_of_continuous (hf x₀) lim_u, apply lim_le this, intros n, have : f (u n) < 0, exact (u_dans n).right, linarith -- sorry }, have x₀_1: x₀ < 1, { -- sorry apply stupid x₀_in, intro h, rw ← h at h₁, linarith -- sorry }, have : f x₀ ≥ 0, { have dans : ∃ N : ℕ, ∀ n ≥ N, x₀ + 1/(n+1) ∈ I, { have : ∃ N : ℕ, ∀ n≥ N, 1/(n+1 : ℝ) ≤ 1-x₀, { -- sorry apply inv_succ_le_all, linarith, -- sorry }, -- sorry cases this with N hN, use N, intros n hn, specialize hN n hn, have : 1/(n+1 : ℝ) > 0, exact nat.one_div_pos_of_nat, change 0 ≤ x₀ ∧ x₀ ≤ 1 at x₀_in, split ; linarith, -- sorry }, have not_in : ∀ n : ℕ, x₀ + 1/(n+1) ∉ A, -- By definition, x ∉ A means ¬ (x ∈ A). { -- sorry intros n hn, cases x₀_sup with x₀_maj _, specialize x₀_maj _ hn, have : 1/(n+1 : ℝ) > 0, from nat.one_div_pos_of_nat, linarith, -- sorry }, dsimp [A] at not_in, -- This is useful to unfold a let -- sorry push_neg at not_in, have lim : seq_limit (λ n, f(x₀ + 1/(n+1))) (f x₀), { apply seq_continuous_of_continuous (hf x₀), apply limit_const_add_inv_succ }, apply le_lim lim, cases dans with N hN, use N, intros n hn, cases not_in n with H H, { exfalso, exact H (hN n hn) }, { exact H } -- sorry }, linarith, end
0a34c368eddfe7df67502d2b35d9b18065a91d47
46125763b4dbf50619e8846a1371029346f4c3db
/src/data/list/sort.lean
d0aa67e02bc6ae6d7244f02c9a18e24d89459b4a
[ "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
11,136
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad Insertion sort and merge sort. -/ import data.list.perm open list.perm namespace list section sorted universe variable uu variables {α : Type uu} {r : α → α → Prop} /-- `sorted r l` is the same as `pairwise r l`, preferred in the case that `r` is a `<` or `≤`-like relation (transitive and antisymmetric or asymmetric) -/ def sorted := @pairwise @[simp] theorem sorted_nil : sorted r [] := pairwise.nil theorem sorted_of_sorted_cons {a : α} {l : list α} : sorted r (a :: l) → sorted r l := pairwise_of_pairwise_cons theorem sorted.tail {r : α → α → Prop} : Π {l : list α}, sorted r l → sorted r l.tail | [] h := h | (hd :: tl) h := sorted_of_sorted_cons h theorem rel_of_sorted_cons {a : α} {l : list α} : sorted r (a :: l) → ∀ b ∈ l, r a b := rel_of_pairwise_cons @[simp] theorem sorted_cons {a : α} {l : list α} : sorted r (a :: l) ↔ (∀ b ∈ l, r a b) ∧ sorted r l := pairwise_cons theorem eq_of_sorted_of_perm [is_antisymm α r] {l₁ l₂ : list α} (p : l₁ ~ l₂) (s₁ : sorted r l₁) (s₂ : sorted r l₂) : l₁ = l₂ := begin induction s₁ with a l₁ h₁ s₁ IH generalizing l₂, { rw eq_nil_of_perm_nil p }, { have : a ∈ l₂ := perm_subset p (mem_cons_self _ _), rcases mem_split this with ⟨u₂, v₂, rfl⟩, have p' := (perm_cons a).1 (p.trans perm_middle), have := IH p' (pairwise_of_sublist (by simp) s₂), subst l₁, change a::u₂ ++ v₂ = u₂ ++ ([a] ++ v₂), rw ← append_assoc, congr, have : ∀ (x : α) (h : x ∈ u₂), x = a := λ x m, antisymm ((pairwise_append.1 s₂).2.2 _ m a (mem_cons_self _ _)) (h₁ _ (by simp [m])), rw [(@eq_repeat _ a (length u₂ + 1) (a::u₂)).2, (@eq_repeat _ a (length u₂ + 1) (u₂++[a])).2]; split; simp [iff_true_intro this, or_comm] } end @[simp] theorem sorted_singleton (a : α) : sorted r [a] := pairwise_singleton _ _ end sorted /- sorting procedures -/ section sort universe variable uu parameters {α : Type uu} (r : α → α → Prop) [decidable_rel r] local infix ` ≼ ` : 50 := r /- insertion sort -/ section insertion_sort /-- `ordered_insert a l` inserts `a` into `l` at such that `ordered_insert a l` is sorted if `l` is. -/ @[simp] def ordered_insert (a : α) : list α → list α | [] := [a] | (b :: l) := if a ≼ b then a :: b :: l else b :: ordered_insert l /-- `insertion_sort l` returns `l` sorted using the insertion sort algorithm. -/ @[simp] def insertion_sort : list α → list α | [] := [] | (b :: l) := ordered_insert b (insertion_sort l) @[simp] lemma ordered_insert_nil (a : α) : [].ordered_insert r a = [a] := rfl theorem ordered_insert_length : Π (L : list α) (a : α), (L.ordered_insert r a).length = L.length + 1 | [] a := rfl | (hd :: tl) a := by { dsimp [ordered_insert], split_ifs; simp [ordered_insert_length], } section correctness open perm theorem perm_ordered_insert (a) : ∀ l : list α, ordered_insert a l ~ a :: l | [] := perm.refl _ | (b :: l) := by by_cases a ≼ b; [simp [ordered_insert, h], simpa [ordered_insert, h] using (perm.skip _ (perm_ordered_insert l)).trans (perm.swap _ _ _)] theorem ordered_insert_count [decidable_eq α] (L : list α) (a b : α) : count a (L.ordered_insert r b) = count a L + if (a = b) then 1 else 0 := begin rw [perm_count (L.perm_ordered_insert r b), count_cons], split_ifs; simp only [nat.succ_eq_add_one, add_zero], end theorem perm_insertion_sort : ∀ l : list α, insertion_sort l ~ l | [] := perm.nil | (b :: l) := by simpa [insertion_sort] using (perm_ordered_insert _ _ _).trans (perm.skip b (perm_insertion_sort l)) section total_and_transitive variables [is_total α r] [is_trans α r] theorem sorted_ordered_insert (a : α) : ∀ l, sorted r l → sorted r (ordered_insert a l) | [] h := sorted_singleton a | (b :: l) h := begin by_cases h' : a ≼ b, { simpa [ordered_insert, h', h] using λ b' bm, trans h' (rel_of_sorted_cons h _ bm) }, { suffices : ∀ (b' : α), b' ∈ ordered_insert r a l → r b b', { simpa [ordered_insert, h', sorted_ordered_insert l (sorted_of_sorted_cons h)] }, intros b' bm, cases (show b' = a ∨ b' ∈ l, by simpa using perm_subset (perm_ordered_insert _ _ _) bm) with be bm, { subst b', exact (total_of r _ _).resolve_left h' }, { exact rel_of_sorted_cons h _ bm } } end theorem sorted_insertion_sort : ∀ l, sorted r (insertion_sort l) | [] := sorted_nil | (a :: l) := sorted_ordered_insert a _ (sorted_insertion_sort l) end total_and_transitive end correctness end insertion_sort /- merge sort -/ section merge_sort -- TODO(Jeremy): observation: if instead we write (a :: (split l).1, b :: (split l).2), the -- equation compiler can't prove the third equation /-- Split `l` into two lists of approximately equal length. split [1, 2, 3, 4, 5] = ([1, 3, 5], [2, 4]) -/ @[simp] def split : list α → list α × list α | [] := ([], []) | (a :: l) := let (l₁, l₂) := split l in (a :: l₂, l₁) theorem split_cons_of_eq (a : α) {l l₁ l₂ : list α} (h : split l = (l₁, l₂)) : split (a :: l) = (a :: l₂, l₁) := by rw [split, h]; refl theorem length_split_le : ∀ {l l₁ l₂ : list α}, split l = (l₁, l₂) → length l₁ ≤ length l ∧ length l₂ ≤ length l | [] ._ ._ rfl := ⟨nat.le_refl 0, nat.le_refl 0⟩ | (a::l) l₁' l₂' h := begin cases e : split l with l₁ l₂, injection (split_cons_of_eq _ e).symm.trans h, substs l₁' l₂', cases length_split_le e with h₁ h₂, exact ⟨nat.succ_le_succ h₂, nat.le_succ_of_le h₁⟩ end theorem length_split_lt {a b} {l l₁ l₂ : list α} (h : split (a::b::l) = (l₁, l₂)) : length l₁ < length (a::b::l) ∧ length l₂ < length (a::b::l) := begin cases e : split l with l₁' l₂', injection (split_cons_of_eq _ (split_cons_of_eq _ e)).symm.trans h, substs l₁ l₂, cases length_split_le e with h₁ h₂, exact ⟨nat.succ_le_succ (nat.succ_le_succ h₁), nat.succ_le_succ (nat.succ_le_succ h₂)⟩ end theorem perm_split : ∀ {l l₁ l₂ : list α}, split l = (l₁, l₂) → l ~ l₁ ++ l₂ | [] ._ ._ rfl := perm.refl _ | (a::l) l₁' l₂' h := begin cases e : split l with l₁ l₂, injection (split_cons_of_eq _ e).symm.trans h, substs l₁' l₂', exact perm.skip a ((perm_split e).trans perm_app_comm), end /-- Merge two sorted lists into one in linear time. merge [1, 2, 4, 5] [0, 1, 3, 4] = [0, 1, 1, 2, 3, 4, 4, 5] -/ def merge : list α → list α → list α | [] l' := l' | l [] := l | (a :: l) (b :: l') := if a ≼ b then a :: merge l (b :: l') else b :: merge (a :: l) l' using_well_founded wf_tacs include r /-- Implementation of a merge sort algorithm to sort a list. -/ def merge_sort : list α → list α | [] := [] | [a] := [a] | (a::b::l) := begin cases e : split (a::b::l) with l₁ l₂, cases length_split_lt e with h₁ h₂, exact merge r (merge_sort l₁) (merge_sort l₂) end using_well_founded { rel_tac := λ_ _, `[exact ⟨_, inv_image.wf length nat.lt_wf⟩], dec_tac := tactic.assumption } theorem merge_sort_cons_cons {a b} {l l₁ l₂ : list α} (h : split (a::b::l) = (l₁, l₂)) : merge_sort (a::b::l) = merge (merge_sort l₁) (merge_sort l₂) := begin suffices : ∀ (L : list α) h1, @@and.rec (λ a a (_ : length l₁ < length l + 1 + 1 ∧ length l₂ < length l + 1 + 1), L) h1 h1 = L, { simp [merge_sort, h], apply this }, intros, cases h1, refl end section correctness theorem perm_merge : ∀ (l l' : list α), merge l l' ~ l ++ l' | [] [] := perm.nil | [] (b :: l') := by simp [merge] | (a :: l) [] := by simp [merge] | (a :: l) (b :: l') := begin by_cases a ≼ b, { simpa [merge, h] using skip _ (perm_merge _ _) }, { suffices : b :: merge r (a :: l) l' ~ a :: (l ++ b :: l'), {simpa [merge, h]}, exact (skip _ (perm_merge _ _)).trans ((swap _ _ _).trans (skip _ perm_middle.symm)) } end using_well_founded wf_tacs theorem perm_merge_sort : ∀ l : list α, merge_sort l ~ l | [] := perm.refl _ | [a] := perm.refl _ | (a::b::l) := begin cases e : split (a::b::l) with l₁ l₂, cases length_split_lt e with h₁ h₂, rw [merge_sort_cons_cons r e], apply (perm_merge r _ _).trans, exact (perm_app (perm_merge_sort l₁) (perm_merge_sort l₂)).trans (perm_split e).symm end using_well_founded { rel_tac := λ_ _, `[exact ⟨_, inv_image.wf length nat.lt_wf⟩], dec_tac := tactic.assumption } @[simp] lemma length_merge_sort (l : list α) : (merge_sort l).length = l.length := perm_length (perm_merge_sort _) section total_and_transitive variables [is_total α r] [is_trans α r] theorem sorted_merge : ∀ {l l' : list α}, sorted r l → sorted r l' → sorted r (merge l l') | [] [] h₁ h₂ := sorted_nil | [] (b :: l') h₁ h₂ := by simpa [merge] using h₂ | (a :: l) [] h₁ h₂ := by simpa [merge] using h₁ | (a :: l) (b :: l') h₁ h₂ := begin by_cases a ≼ b, { suffices : ∀ (b' : α) (_ : b' ∈ merge r l (b :: l')), r a b', { simpa [merge, h, sorted_merge (sorted_of_sorted_cons h₁) h₂] }, intros b' bm, rcases (show b' = b ∨ b' ∈ l ∨ b' ∈ l', by simpa [or.left_comm] using perm_subset (perm_merge _ _ _) bm) with be | bl | bl', { subst b', assumption }, { exact rel_of_sorted_cons h₁ _ bl }, { exact trans h (rel_of_sorted_cons h₂ _ bl') } }, { suffices : ∀ (b' : α) (_ : b' ∈ merge r (a :: l) l'), r b b', { simpa [merge, h, sorted_merge h₁ (sorted_of_sorted_cons h₂)] }, intros b' bm, have ba : b ≼ a := (total_of r _ _).resolve_left h, rcases (show b' = a ∨ b' ∈ l ∨ b' ∈ l', by simpa using perm_subset (perm_merge _ _ _) bm) with be | bl | bl', { subst b', assumption }, { exact trans ba (rel_of_sorted_cons h₁ _ bl) }, { exact rel_of_sorted_cons h₂ _ bl' } } end using_well_founded wf_tacs theorem sorted_merge_sort : ∀ l : list α, sorted r (merge_sort l) | [] := sorted_nil | [a] := sorted_singleton _ | (a::b::l) := begin cases e : split (a::b::l) with l₁ l₂, cases length_split_lt e with h₁ h₂, rw [merge_sort_cons_cons r e], exact sorted_merge r (sorted_merge_sort l₁) (sorted_merge_sort l₂) end using_well_founded { rel_tac := λ_ _, `[exact ⟨_, inv_image.wf length nat.lt_wf⟩], dec_tac := tactic.assumption } theorem merge_sort_eq_self [is_antisymm α r] {l : list α} : sorted r l → merge_sort l = l := eq_of_sorted_of_perm (perm_merge_sort _) (sorted_merge_sort _) end total_and_transitive end correctness end merge_sort end sort /- try them out! -/ --#eval insertion_sort (λ m n : ℕ, m ≤ n) [5, 27, 221, 95, 17, 43, 7, 2, 98, 567, 23, 12] --#eval merge_sort (λ m n : ℕ, m ≤ n) [5, 27, 221, 95, 17, 43, 7, 2, 98, 567, 23, 12] end list
7c6bcaa35327585b7ccd42a4556d6775ea034608
626e312b5c1cb2d88fca108f5933076012633192
/src/analysis/calculus/fderiv_measurable.lean
85f8769a1b81ef8fc4e79d788a5008331928c950
[ "Apache-2.0" ]
permissive
Bioye97/mathlib
9db2f9ee54418d29dd06996279ba9dc874fd6beb
782a20a27ee83b523f801ff34efb1a9557085019
refs/heads/master
1,690,305,956,488
1,631,067,774,000
1,631,067,774,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
21,759
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel, Yury Kudryashov -/ import analysis.calculus.deriv import measure_theory.constructions.borel_space /-! # Derivative is measurable In this file we prove that the derivative of any function with complete codomain is a measurable function. Namely, we prove: * `measurable_set_of_differentiable_at`: the set `{x | differentiable_at 𝕜 f x}` is measurable; * `measurable_fderiv`: the function `fderiv 𝕜 f` is measurable; * `measurable_fderiv_apply_const`: for a fixed vector `y`, the function `λ x, fderiv 𝕜 f x y` is measurable; * `measurable_deriv`: the function `deriv f` is measurable (for `f : 𝕜 → F`). ## Implementation We give a proof that avoids second-countability issues, by expressing the differentiability set as a function of open sets in the following way. Define `A (L, r, ε)` to be the set of points where, on a ball of radius roughly `r` around `x`, the function is uniformly approximated by the linear map `L`, up to `ε r`. It is an open set. Let also `B (L, r, s, ε) = A (L, r, ε) ∩ A (L, s, ε)`: we require that at two possibly different scales `r` and `s`, the function is well approximated by the linear map `L`. It is also open. We claim that the differentiability set of `f` is exactly `D = ⋂ ε > 0, ⋃ δ > 0, ⋂ r, s < δ, ⋃ L, B (L, r, s, ε)`. In other words, for any `ε > 0`, we require that there is a size `δ` such that, for any two scales below this size, the function is well approximated by a linear map, common to the two scales. The set `⋃ L, B (L, r, s, ε)` is open, as a union of open sets. Converting the intersections and unions to countable ones (using real numbers of the form `2 ^ (-n)`), it follows that the differentiability set is measurable. To prove the claim, there are two inclusions. One is trivial: if the function is differentiable at `x`, then `x` belongs to `D` (just take `L` to be the derivative, and use that the differentiability exactly says that the map is well approximated by `L`). This is proved in `mem_A_of_differentiable` and `differentiable_set_subset_D`. For the other direction, the difficulty is that `L` in the union may depend on `ε, r, s`. The key point is that, in fact, it doesn't depend too much on them. First, if `x` belongs both to `A (L, r, ε)` and `A (L', r, ε)`, then `L` and `L'` have to be close on a shell, and thus `∥L - L'∥` is bounded by `ε` (see `norm_sub_le_of_mem_A`). Assume now `x ∈ D`. If one has two maps `L` and `L'` such that `x` belongs to `A (L, r, ε)` and to `A (L', r', ε')`, one deduces that `L` is close to `L'` by arguing as follows. Consider another scale `s` smaller than `r` and `r'`. Take a linear map `L₁` that approximates `f` around `x` both at scales `r` and `s` w.r.t. `ε` (it exists as `x` belongs to `D`). Take also `L₂` that approximates `f` around `x` both at scales `r'` and `s` w.r.t. `ε'`. Then `L₁` is close to `L` (as they are close on a shell of radius `r`), and `L₂` is close to `L₁` (as they are close on a shell of radius `s`), and `L'` is close to `L₂` (as they are close on a shell of radius `r'`). It follows that `L` is close to `L'`, as we claimed. It follows that the different approximating linear maps that show up form a Cauchy sequence when `ε` tends to `0`. When the target space is complete, this sequence converges, to a limit `f'`. With the same kind of arguments, one checks that `f` is differentiable with derivative `f'`. To show that the derivative itself is measurable, add in the definition of `B` and `D` a set `K` of continuous linear maps to which `L` should belong. Then, when `K` is complete, the set `D K` is exactly the set of points where `f` is differentiable with a derivative in `K`. ## Tags derivative, measurable function, Borel σ-algebra -/ noncomputable theory open set metric asymptotics filter continuous_linear_map open topological_space (second_countable_topology) open_locale topological_space namespace continuous_linear_map variables {𝕜 E F : Type*} [nondiscrete_normed_field 𝕜] [normed_group E] [normed_space 𝕜 E] [normed_group F] [normed_space 𝕜 F] lemma measurable_apply₂ [measurable_space E] [opens_measurable_space E] [second_countable_topology E] [second_countable_topology (E →L[𝕜] F)] [measurable_space F] [borel_space F] : measurable (λ p : (E →L[𝕜] F) × E, p.1 p.2) := is_bounded_bilinear_map_apply.continuous.measurable end continuous_linear_map variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] variables {F : Type*} [normed_group F] [normed_space 𝕜 F] variables {f : E → F} (K : set (E →L[𝕜] F)) namespace fderiv_measurable_aux /-- The set `A f L r ε` is the set of points `x` around which the function `f` is well approximated at scale `r` by the linear map `L`, up to an error `ε`. We tweak the definition to make sure that this is an open set.-/ def A (f : E → F) (L : E →L[𝕜] F) (r ε : ℝ) : set E := {x | ∃ r' ∈ Ioc (r/2) r, ∀ y z ∈ ball x r', ∥f z - f y - L (z-y)∥ ≤ ε * r} /-- The set `B f K r s ε` is the set of points `x` around which there exists a continuous linear map `L` belonging to `K` (a given set of continuous linear maps) that approximates well the function `f` (up to an error `ε`), simultaneously at scales `r` and `s`. -/ def B (f : E → F) (K : set (E →L[𝕜] F)) (r s ε : ℝ) : set E := ⋃ (L ∈ K), (A f L r ε) ∩ (A f L s ε) /-- The set `D f K` is a complicated set constructed using countable intersections and unions. Its main use is that, when `K` is complete, it is exactly the set of points where `f` is differentiable, with a derivative in `K`. -/ def D (f : E → F) (K : set (E →L[𝕜] F)) : set E := ⋂ (e : ℕ), ⋃ (n : ℕ), ⋂ (p ≥ n) (q ≥ n), B f K ((1/2) ^ p) ((1/2) ^ q) ((1/2) ^ e) lemma is_open_A (L : E →L[𝕜] F) (r ε : ℝ) : is_open (A f L r ε) := begin rw metric.is_open_iff, rintros x ⟨r', r'_mem, hr'⟩, obtain ⟨s, s_gt, s_lt⟩ : ∃ (s : ℝ), r / 2 < s ∧ s < r' := exists_between r'_mem.1, have : s ∈ Ioc (r/2) r := ⟨s_gt, le_of_lt (s_lt.trans_le r'_mem.2)⟩, refine ⟨r' - s, by linarith, λ x' hx', ⟨s, this, _⟩⟩, have B : ball x' s ⊆ ball x r' := ball_subset (le_of_lt hx'), assume y z hy hz, exact hr' y z (B hy) (B hz) end lemma is_open_B {K : set (E →L[𝕜] F)} {r s ε : ℝ} : is_open (B f K r s ε) := by simp [B, is_open_Union, is_open.inter, is_open_A] lemma A_mono (L : E →L[𝕜] F) (r : ℝ) {ε δ : ℝ} (h : ε ≤ δ) : A f L r ε ⊆ A f L r δ := begin rintros x ⟨r', r'r, hr'⟩, refine ⟨r', r'r, λ y z hy hz, _⟩, apply le_trans (hr' y z hy hz), apply mul_le_mul_of_nonneg_right h, linarith [mem_ball.1 hy, r'r.2, @dist_nonneg _ _ y x], end lemma le_of_mem_A {r ε : ℝ} {L : E →L[𝕜] F} {x : E} (hx : x ∈ A f L r ε) {y z : E} (hy : y ∈ closed_ball x (r/2)) (hz : z ∈ closed_ball x (r/2)) : ∥f z - f y - L (z-y)∥ ≤ ε * r := begin rcases hx with ⟨r', r'mem, hr'⟩, exact hr' _ _ (lt_of_le_of_lt (mem_closed_ball.1 hy) r'mem.1) (lt_of_le_of_lt (mem_closed_ball.1 hz) r'mem.1) end lemma mem_A_of_differentiable {ε : ℝ} (hε : 0 < ε) {x : E} (hx : differentiable_at 𝕜 f x) : ∃ R > 0, ∀ r ∈ Ioo (0 : ℝ) R, x ∈ A f (fderiv 𝕜 f x) r ε := begin have := hx.has_fderiv_at, simp only [has_fderiv_at, has_fderiv_at_filter, is_o_iff] at this, rcases eventually_nhds_iff_ball.1 (this (half_pos hε)) with ⟨R, R_pos, hR⟩, refine ⟨R, R_pos, λ r hr, _⟩, have : r ∈ Ioc (r/2) r := ⟨half_lt_self hr.1, le_refl _⟩, refine ⟨r, this, λ y z hy hz, _⟩, calc ∥f z - f y - (fderiv 𝕜 f x) (z - y)∥ = ∥(f z - f x - (fderiv 𝕜 f x) (z - x)) - (f y - f x - (fderiv 𝕜 f x) (y - x))∥ : by { congr' 1, simp only [continuous_linear_map.map_sub], abel } ... ≤ ∥(f z - f x - (fderiv 𝕜 f x) (z - x))∥ + ∥f y - f x - (fderiv 𝕜 f x) (y - x)∥ : norm_sub_le _ _ ... ≤ ε / 2 * ∥z - x∥ + ε / 2 * ∥y - x∥ : add_le_add (hR _ (lt_trans (mem_ball.1 hz) hr.2)) (hR _ (lt_trans (mem_ball.1 hy) hr.2)) ... ≤ ε / 2 * r + ε / 2 * r : add_le_add (mul_le_mul_of_nonneg_left (le_of_lt (mem_ball_iff_norm.1 hz)) (le_of_lt (half_pos hε))) (mul_le_mul_of_nonneg_left (le_of_lt (mem_ball_iff_norm.1 hy)) (le_of_lt (half_pos hε))) ... = ε * r : by ring end lemma norm_sub_le_of_mem_A {c : 𝕜} (hc : 1 < ∥c∥) {r ε : ℝ} (hε : 0 < ε) (hr : 0 < r) {x : E} {L₁ L₂ : E →L[𝕜] F} (h₁ : x ∈ A f L₁ r ε) (h₂ : x ∈ A f L₂ r ε) : ∥L₁ - L₂∥ ≤ 4 * ∥c∥ * ε := begin have : 0 ≤ 4 * ∥c∥ * ε := mul_nonneg (mul_nonneg (by norm_num : (0 : ℝ) ≤ 4) (norm_nonneg _)) hε.le, apply op_norm_le_of_shell (half_pos hr) this hc, assume y ley ylt, rw [div_div_eq_div_mul, div_le_iff' (mul_pos (by norm_num : (0 : ℝ) < 2) (zero_lt_one.trans hc))] at ley, calc ∥(L₁ - L₂) y∥ = ∥(f (x + y) - f x - L₂ ((x + y) - x)) - (f (x + y) - f x - L₁ ((x + y) - x))∥ : by simp ... ≤ ∥(f (x + y) - f x - L₂ ((x + y) - x))∥ + ∥(f (x + y) - f x - L₁ ((x + y) - x))∥ : norm_sub_le _ _ ... ≤ ε * r + ε * r : begin apply add_le_add, { apply le_of_mem_A h₂, { simp only [le_of_lt (half_pos hr), mem_closed_ball, dist_self] }, { simp only [dist_eq_norm, add_sub_cancel', mem_closed_ball, ylt.le], } }, { apply le_of_mem_A h₁, { simp only [le_of_lt (half_pos hr), mem_closed_ball, dist_self] }, { simp only [dist_eq_norm, add_sub_cancel', mem_closed_ball, ylt.le] } }, end ... = 2 * ε * r : by ring ... ≤ 2 * ε * (2 * ∥c∥ * ∥y∥) : mul_le_mul_of_nonneg_left ley (mul_nonneg (by norm_num) hε.le) ... = 4 * ∥c∥ * ε * ∥y∥ : by ring end /-- Easy inclusion: a differentiability point with derivative in `K` belongs to `D f K`. -/ lemma differentiable_set_subset_D : {x | differentiable_at 𝕜 f x ∧ fderiv 𝕜 f x ∈ K} ⊆ D f K := begin assume x hx, rw [D, mem_Inter], assume e, have : (0 : ℝ) < (1/2) ^ e := pow_pos (by norm_num) _, rcases mem_A_of_differentiable this hx.1 with ⟨R, R_pos, hR⟩, obtain ⟨n, hn⟩ : ∃ (n : ℕ), (1/2) ^ n < R := exists_pow_lt_of_lt_one R_pos (by norm_num : (1 : ℝ)/2 < 1), simp only [mem_Union, mem_Inter, B, mem_inter_eq], refine ⟨n, λ p hp q hq, ⟨fderiv 𝕜 f x, hx.2, ⟨_, _⟩⟩⟩; { refine hR _ ⟨pow_pos (by norm_num) _, lt_of_le_of_lt _ hn⟩, exact pow_le_pow_of_le_one (by norm_num) (by norm_num) (by assumption) } end /-- Harder inclusion: at a point in `D f K`, the function `f` has a derivative, in `K`. -/ lemma D_subset_differentiable_set {K : set (E →L[𝕜] F)} (hK : is_complete K) : D f K ⊆ {x | differentiable_at 𝕜 f x ∧ fderiv 𝕜 f x ∈ K} := begin have P : ∀ {n : ℕ}, (0 : ℝ) < (1/2) ^ n := pow_pos (by norm_num), rcases normed_field.exists_one_lt_norm 𝕜 with ⟨c, hc⟩, have cpos : 0 < ∥c∥ := lt_trans zero_lt_one hc, assume x hx, have : ∀ (e : ℕ), ∃ (n : ℕ), ∀ p q, n ≤ p → n ≤ q → ∃ L ∈ K, x ∈ A f L ((1/2) ^ p) ((1/2) ^ e) ∩ A f L ((1/2) ^ q) ((1/2) ^ e), { assume e, have := mem_Inter.1 hx e, rcases mem_Union.1 this with ⟨n, hn⟩, refine ⟨n, λ p q hp hq, _⟩, simp only [mem_Inter, ge_iff_le] at hn, rcases mem_Union.1 (hn p hp q hq) with ⟨L, hL⟩, exact ⟨L, mem_Union.1 hL⟩, }, /- Recast the assumptions: for each `e`, there exist `n e` and linear maps `L e p q` in `K` such that, for `p, q ≥ n e`, then `f` is well approximated by `L e p q` at scale `2 ^ (-p)` and `2 ^ (-q)`, with an error `2 ^ (-e)`. -/ choose! n L hn using this, /- All the operators `L e p q` that show up are close to each other. To prove this, we argue that `L e p q` is close to `L e p r` (where `r` is large enough), as both approximate `f` at scale `2 ^(- p)`. And `L e p r` is close to `L e' p' r` as both approximate `f` at scale `2 ^ (- r)`. And `L e' p' r` is close to `L e' p' q'` as both approximate `f` at scale `2 ^ (- p')`. -/ have M : ∀ e p q e' p' q', n e ≤ p → n e ≤ q → n e' ≤ p' → n e' ≤ q' → e ≤ e' → ∥L e p q - L e' p' q'∥ ≤ 12 * ∥c∥ * (1/2) ^ e, { assume e p q e' p' q' hp hq hp' hq' he', let r := max (n e) (n e'), have I : ((1:ℝ)/2)^e' ≤ (1/2)^e := pow_le_pow_of_le_one (by norm_num) (by norm_num) he', have J1 : ∥L e p q - L e p r∥ ≤ 4 * ∥c∥ * (1/2)^e, { have I1 : x ∈ A f (L e p q) ((1 / 2) ^ p) ((1/2)^e) := (hn e p q hp hq).2.1, have I2 : x ∈ A f (L e p r) ((1 / 2) ^ p) ((1/2)^e) := (hn e p r hp (le_max_left _ _)).2.1, exact norm_sub_le_of_mem_A hc P P I1 I2 }, have J2 : ∥L e p r - L e' p' r∥ ≤ 4 * ∥c∥ * (1/2)^e, { have I1 : x ∈ A f (L e p r) ((1 / 2) ^ r) ((1/2)^e) := (hn e p r hp (le_max_left _ _)).2.2, have I2 : x ∈ A f (L e' p' r) ((1 / 2) ^ r) ((1/2)^e') := (hn e' p' r hp' (le_max_right _ _)).2.2, exact norm_sub_le_of_mem_A hc P P I1 (A_mono _ _ I I2) }, have J3 : ∥L e' p' r - L e' p' q'∥ ≤ 4 * ∥c∥ * (1/2)^e, { have I1 : x ∈ A f (L e' p' r) ((1 / 2) ^ p') ((1/2)^e') := (hn e' p' r hp' (le_max_right _ _)).2.1, have I2 : x ∈ A f (L e' p' q') ((1 / 2) ^ p') ((1/2)^e') := (hn e' p' q' hp' hq').2.1, exact norm_sub_le_of_mem_A hc P P (A_mono _ _ I I1) (A_mono _ _ I I2) }, calc ∥L e p q - L e' p' q'∥ = ∥(L e p q - L e p r) + (L e p r - L e' p' r) + (L e' p' r - L e' p' q')∥ : by { congr' 1, abel } ... ≤ ∥L e p q - L e p r∥ + ∥L e p r - L e' p' r∥ + ∥L e' p' r - L e' p' q'∥ : le_trans (norm_add_le _ _) (add_le_add_right (norm_add_le _ _) _) ... ≤ 4 * ∥c∥ * (1/2)^e + 4 * ∥c∥ * (1/2)^e + 4 * ∥c∥ * (1/2)^e : by apply_rules [add_le_add] ... = 12 * ∥c∥ * (1/2)^e : by ring }, /- For definiteness, use `L0 e = L e (n e) (n e)`, to have a single sequence. We claim that this is a Cauchy sequence. -/ let L0 : ℕ → (E →L[𝕜] F) := λ e, L e (n e) (n e), have : cauchy_seq L0, { rw metric.cauchy_seq_iff', assume ε εpos, obtain ⟨e, he⟩ : ∃ (e : ℕ), (1/2) ^ e < ε / (12 * ∥c∥) := exists_pow_lt_of_lt_one (div_pos εpos (mul_pos (by norm_num) cpos)) (by norm_num), refine ⟨e, λ e' he', _⟩, rw [dist_comm, dist_eq_norm], calc ∥L0 e - L0 e'∥ ≤ 12 * ∥c∥ * (1/2)^e : M _ _ _ _ _ _ (le_refl _) (le_refl _) (le_refl _) (le_refl _) he' ... < 12 * ∥c∥ * (ε / (12 * ∥c∥)) : mul_lt_mul' (le_refl _) he (le_of_lt P) (mul_pos (by norm_num) cpos) ... = ε : by { field_simp [(by norm_num : (12 : ℝ) ≠ 0), ne_of_gt cpos], ring } }, /- As it is Cauchy, the sequence `L0` converges, to a limit `f'` in `K`.-/ obtain ⟨f', f'K, hf'⟩ : ∃ f' ∈ K, tendsto L0 at_top (𝓝 f') := cauchy_seq_tendsto_of_is_complete hK (λ e, (hn e (n e) (n e) (le_refl _) (le_refl _)).1) this, have Lf' : ∀ e p, n e ≤ p → ∥L e (n e) p - f'∥ ≤ 12 * ∥c∥ * (1/2)^e, { assume e p hp, apply le_of_tendsto (tendsto_const_nhds.sub hf').norm, rw eventually_at_top, exact ⟨e, λ e' he', M _ _ _ _ _ _ (le_refl _) hp (le_refl _) (le_refl _) he'⟩ }, /- Let us show that `f` has derivative `f'` at `x`. -/ have : has_fderiv_at f f' x, { simp only [has_fderiv_at_iff_is_o_nhds_zero, is_o_iff], /- to get an approximation with a precision `ε`, we will replace `f` with `L e (n e) m` for some large enough `e` (yielding a small error by uniform approximation). As one can vary `m`, this makes it possible to cover all scales, and thus to obtain a good linear approximation in the whole ball of radius `(1/2)^(n e)`. -/ assume ε εpos, have pos : 0 < 4 + 12 * ∥c∥ := add_pos_of_pos_of_nonneg (by norm_num) (mul_nonneg (by norm_num) (norm_nonneg _)), obtain ⟨e, he⟩ : ∃ (e : ℕ), (1 / 2) ^ e < ε / (4 + 12 * ∥c∥) := exists_pow_lt_of_lt_one (div_pos εpos pos) (by norm_num), rw eventually_nhds_iff_ball, refine ⟨(1/2) ^ (n e + 1), P, λ y hy, _⟩, -- We need to show that `f (x + y) - f x - f' y` is small. For this, we will work at scale -- `k` where `k` is chosen with `∥y∥ ∼ 2 ^ (-k)`. by_cases y_pos : y = 0, {simp [y_pos] }, have yzero : 0 < ∥y∥ := norm_pos_iff.mpr y_pos, have y_lt : ∥y∥ < (1/2) ^ (n e + 1), by simpa using mem_ball_iff_norm.1 hy, have yone : ∥y∥ ≤ 1 := le_trans (y_lt.le) (pow_le_one _ (by norm_num) (by norm_num)), -- define the scale `k`. obtain ⟨k, hk, h'k⟩ : ∃ (k : ℕ), (1/2) ^ (k + 1) < ∥y∥ ∧ ∥y∥ ≤ (1/2) ^ k := exists_nat_pow_near_of_lt_one yzero yone (by norm_num : (0 : ℝ) < 1/2) (by norm_num : (1 : ℝ)/2 < 1), -- the scale is large enough (as `y` is small enough) have k_gt : n e < k, { have : ((1:ℝ)/2) ^ (k + 1) < (1/2) ^ (n e + 1) := lt_trans hk y_lt, rw pow_lt_pow_iff_of_lt_one (by norm_num : (0 : ℝ) < 1/2) (by norm_num) at this, linarith }, set m := k - 1 with hl, have m_ge : n e ≤ m := nat.le_pred_of_lt k_gt, have km : k = m + 1 := (nat.succ_pred_eq_of_pos (lt_of_le_of_lt (zero_le _) k_gt)).symm, rw km at hk h'k, -- `f` is well approximated by `L e (n e) k` at the relevant scale -- (in fact, we use `m = k - 1` instead of `k` because of the precise definition of `A`). have J1 : ∥f (x + y) - f x - L e (n e) m ((x + y) - x)∥ ≤ (1/2) ^ e * (1/2) ^ m, { apply le_of_mem_A (hn e (n e) m (le_refl _) m_ge).2.2, { simp only [mem_closed_ball, dist_self], exact div_nonneg (le_of_lt P) (zero_le_two) }, { simp [dist_eq_norm], convert h'k, field_simp, ring_exp } }, have J2 : ∥f (x + y) - f x - L e (n e) m y∥ ≤ 4 * (1/2) ^ e * ∥y∥ := calc ∥f (x + y) - f x - L e (n e) m y∥ ≤ (1/2) ^ e * (1/2) ^ m : by simpa only [add_sub_cancel'] using J1 ... = 4 * (1/2) ^ e * (1/2) ^ (m + 2) : by { field_simp, ring_exp } ... ≤ 4 * (1/2) ^ e * ∥y∥ : mul_le_mul_of_nonneg_left (le_of_lt hk) (mul_nonneg (by norm_num) (le_of_lt P)), -- use the previous estimates to see that `f (x + y) - f x - f' y` is small. calc ∥f (x + y) - f x - f' y∥ = ∥(f (x + y) - f x - L e (n e) m y) + (L e (n e) m - f') y∥ : by { congr' 1, simp, abel } ... ≤ ∥f (x + y) - f x - L e (n e) m y∥ + ∥(L e (n e) m - f') y∥ : norm_add_le _ _ ... ≤ 4 * (1/2) ^ e * ∥y∥ + 12 * ∥c∥ * (1/2) ^ e * ∥y∥ : add_le_add J2 (le_trans (le_op_norm _ _) (mul_le_mul_of_nonneg_right (Lf' _ _ m_ge) (norm_nonneg _))) ... = (4 + 12 * ∥c∥) * ∥y∥ * (1/2) ^ e : by ring ... ≤ (4 + 12 * ∥c∥) * ∥y∥ * (ε / (4 + 12 * ∥c∥)) : mul_le_mul_of_nonneg_left he.le (mul_nonneg (add_nonneg (by norm_num) (mul_nonneg (by norm_num) (norm_nonneg _))) (norm_nonneg _)) ... = ε * ∥y∥ : by { field_simp [ne_of_gt pos], ring } }, rw ← this.fderiv at f'K, exact ⟨this.differentiable_at, f'K⟩ end theorem differentiable_set_eq_D (hK : is_complete K) : {x | differentiable_at 𝕜 f x ∧ fderiv 𝕜 f x ∈ K} = D f K := subset.antisymm (differentiable_set_subset_D _) (D_subset_differentiable_set hK) end fderiv_measurable_aux open fderiv_measurable_aux variables [measurable_space E] [opens_measurable_space E] variables (𝕜 f) /-- The set of differentiability points of a function, with derivative in a given complete set, is Borel-measurable. -/ theorem measurable_set_of_differentiable_at_of_is_complete {K : set (E →L[𝕜] F)} (hK : is_complete K) : measurable_set {x | differentiable_at 𝕜 f x ∧ fderiv 𝕜 f x ∈ K} := by simp [differentiable_set_eq_D K hK, D, is_open_B.measurable_set, measurable_set.Inter_Prop, measurable_set.Inter, measurable_set.Union] variable [complete_space F] /-- The set of differentiability points of a function taking values in a complete space is Borel-measurable. -/ theorem measurable_set_of_differentiable_at : measurable_set {x | differentiable_at 𝕜 f x} := begin have : is_complete (univ : set (E →L[𝕜] F)) := complete_univ, convert measurable_set_of_differentiable_at_of_is_complete 𝕜 f this, simp end lemma measurable_fderiv : measurable (fderiv 𝕜 f) := begin refine measurable_of_is_closed (λ s hs, _), have : fderiv 𝕜 f ⁻¹' s = {x | differentiable_at 𝕜 f x ∧ fderiv 𝕜 f x ∈ s} ∪ {x | (0 : E →L[𝕜] F) ∈ s} ∩ {x | ¬differentiable_at 𝕜 f x} := set.ext (λ x, mem_preimage.trans fderiv_mem_iff), rw this, exact (measurable_set_of_differentiable_at_of_is_complete _ _ hs.is_complete).union ((measurable_set.const _).inter (measurable_set_of_differentiable_at _ _).compl) end lemma measurable_fderiv_apply_const [measurable_space F] [borel_space F] (y : E) : measurable (λ x, fderiv 𝕜 f x y) := (continuous_linear_map.measurable_apply y).comp (measurable_fderiv 𝕜 f) variable {𝕜} lemma measurable_deriv [measurable_space 𝕜] [opens_measurable_space 𝕜] [measurable_space F] [borel_space F] (f : 𝕜 → F) : measurable (deriv f) := by simpa only [fderiv_deriv] using measurable_fderiv_apply_const 𝕜 f 1
7d300c0aaa371620224742e58b3858f86983f759
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/src/Lean/Parser/Extension.lean
87a299462e922fc80e3a794c9e84646f5a16ba9f
[ "Apache-2.0" ]
permissive
dupuisf/lean4
d082d13b01243e1de29ae680eefb476961221eef
6a39c65bd28eb0e28c3870188f348c8914502718
refs/heads/master
1,676,948,755,391
1,610,665,114,000
1,610,665,114,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
26,245
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 d => return trailingNode k prec (← 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 ++ "'") @[builtinInit] def setCategoryParserFnRef : IO Unit := 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, mkNatLit prio] let decl := Declaration.defnDecl { name := name, lparams := [], 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) @[builtinInit] private def registerParserAttributeImplBuilder : IO Unit := 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 | some (Syntax.atom _ sym) => if ctx.insideQuot && sym == "$" then s else match cat.tables.leadingTable.find? (Name.mkSimple sym) with | some _ => s.mkUnexpectedError (toString catName) | _ => s | _ => s @[inline] def notFollowedByCategoryToken (catName : Name) : Parser := { fn := notFollowedByCategoryTokenFn catName } abbrev notFollowedByCommandToken : Parser := notFollowedByCategoryToken `command abbrev notFollowedByTermToken : Parser := notFollowedByCategoryToken `term end Parser end Lean
494eb0636fe0eb4ce3a1796ad4af6329ff548a56
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/coe3.lean
f4c9c52f285972a9b7412caa4d4bc5d18ab6b938
[ "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
759
lean
import logic namespace setoid inductive setoid : Type := mk_setoid: Π (A : Type), (A → A → Prop) → setoid 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 set_option pp.universes true 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.mk end setoid
75767cce13204976eb134fc4ac4b96a0f33a8f77
a726f88081e44db9edfd14d32cfe9c4393ee56a4
/src/game/world9/level4.lean
26b33db835507ec1376fe301c77820d6a80c643c
[]
no_license
b-mehta/natural_number_game
80451bf10277adc89a55dbe8581692c36d822462
9faf799d0ab48ecbc89b3d70babb65ba64beee3b
refs/heads/master
1,598,525,389,186
1,573,516,674,000
1,573,516,674,000
217,339,684
0
0
null
1,571,933,100,000
1,571,933,099,000
null
UTF-8
Lean
false
false
1,153
lean
import game.world9.level3 -- hide namespace mynat -- hide /- # Multiplication World ## Level 4: `mul_left_cancel` This is the last of the bonus multiplication levels. `mul_left_cancel` will be useful in inequality world. -/ /- Theorem If $a \neq 0$, $b$ and $c$ are natural numbers such that $ ab = ac, $ then $b = c$. -/ theorem mul_left_cancel (a b c : mynat) (ha : a ≠ 0) : a * b = a * c → b = c := begin [less_leaky] revert b, induction c with d hd, { intro b, rw mul_zero, intro h, cases (eq_zero_or_eq_zero_of_mul_eq_zero _ _ h) with h1 h2, exfalso, apply ha, assumption, assumption }, { intros b hb, cases b with c, { rw mul_zero at hb, exfalso, apply ha, symmetry at hb, cases (eq_zero_or_eq_zero_of_mul_eq_zero _ _ hb) with h h, exact h, exfalso, exact succ_ne_zero _ h, }, { have h : c = d, apply hd, rw mul_succ at hb, rw mul_succ at hb, apply add_right_cancel hb, rw h, refl, } } end end mynat -- hide /- To come -- inequality world. 30 levels of `≤` and the `use` tactic. -/
3119980417c6f9ec7f8eed6e00e00a9577391462
9dc8cecdf3c4634764a18254e94d43da07142918
/test/induction.lean
ddd471dc6d49ec006195bb28435096e4c26da9a7
[ "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
37,996
lean
import tactic.induction import tactic.linarith universes u v w -------------------------------------------------------------------------------- -- Setup: Some Inductive Types -------------------------------------------------------------------------------- inductive le : ℕ → ℕ → Type | zero {n} : le 0 n | succ {n m} : le n m → le (n + 1) (m + 1) inductive lt : ℕ → ℕ → Type | zero {n} : lt 0 (n + 1) | succ {n m} : lt n m → lt (n + 1) (m + 1) inductive Fin : ℕ → Type | zero {n} : Fin (n + 1) | succ {n} : Fin n → Fin (n + 1) inductive List (α : Sort*) : Sort* | nil {} : List | cons {} (x : α) (xs : List) : List namespace List def append {α} : List α → List α → List α | nil ys := ys | (cons x xs) ys := cons x (append xs ys) end List inductive Vec (α : Sort u) : ℕ → Sort (max 1 u) | nil : Vec 0 | cons {n} : α → 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} {xs : Vec α n} {ys : Vec α m} {x y : α} : x = y → eq n m xs ys → eq (n + 1) (m + 1) (cons x xs) (cons y ys) end Vec inductive Two : Type | zero | one inductive ℕ' : Type | intro : ℕ → ℕ' -------------------------------------------------------------------------------- -- Unit Tests -------------------------------------------------------------------------------- example (k) : 0 + k = k := begin induction' k, { refl }, { simp } end example {k} (fk : Fin k) : Fin (k + 1) := begin induction' fk, { exact Fin.zero }, { exact Fin.succ ih } end example {α} (l : List α) : l.append List.nil = l := begin induction' l, { refl }, { dsimp only [List.append], exact (congr_arg _ ih) } end example {k l} (h : lt k l) : le k l := begin induction' h, { exact le.zero }, { exact le.succ ih } end example {k l} : lt k l → le k l := begin induction' k; induction' l; intro hlt, { cases' hlt }, { exact le.zero }, { cases' hlt }, { cases' hlt, exact le.succ (@ih m hlt), } end example {α n m} {xs : Vec α n} {ys : Vec α m} (h : Vec.eq n m xs ys) : n = m := begin induction' h, case nil { refl }, case cons { exact congr_arg nat.succ ih, } end -- A simple induction with complex index arguments. example {k} (h : lt (k + 1) k) : false := begin induction' h, { exact ih } end -- A more complex induction with complex index arguments. Note the dependencies -- between index arguments. example {α : Sort u} {x y n m} {xs : Vec α n} {ys : Vec α m} : Vec.eq (n + 1) (m + 1) (Vec.cons x xs) (Vec.cons y ys) → Vec.eq n m xs ys := begin intro h, induction' h, exact h_1 end -- It also works with cases'. example {α : Sort u} {x y n m} {xs : Vec α n} {ys : Vec α m} : Vec.eq (n + 1) (m + 1) (Vec.cons x xs) (Vec.cons y ys) → Vec.eq n m xs ys := begin intro h, cases' h, exact h_1 end -- This example requires elimination of cyclic generalised index equations. example (n : ℕ) (h : n = n + 3) : false := begin success_if_fail { cases h }, induction' h end -- It also works with cases'. example (n : ℕ) (h : n = n + 3) : false := begin success_if_fail { cases h }, cases' h end -- This example used to fail because it involves a nested inductive as a complex -- index. inductive rose₁ : Type | tip : rose₁ | node : list rose₁ → rose₁ example (rs) (h : rose₁.tip = rose₁.node rs) : false := begin cases' h end -- This example checks whether we can deal with infinitely branching inductive -- types. inductive inf_tree (α : Type) : Type | tip : inf_tree | node (a : α) (f : ∀ (n : ℕ), inf_tree) : inf_tree namespace inf_tree inductive all {α} (P : α → Prop) : inf_tree α → Prop | tip : all tip | node {a} {f : ℕ → inf_tree α} : P a → (∀ n, all (f n)) → all (node a f) example {α} (t : inf_tree α) : all (λ _, true) t := begin induction' t, { exact all.tip }, { exact all.node trivial ih } end end inf_tree -- This example tests type-based naming. example (k : ℕ') (i : ℕ') : ℕ := begin induction' k, induction' i, exact (n + m) end -- For constructor arguments that are propositions, the default name is "h". -- For non-propositions, it is "x". inductive nat_or_positive | nat : ℕ' → nat_or_positive | positive (n : ℕ) : n > 0 → nat_or_positive example (n : nat_or_positive) : unit := begin cases' n, case nat { guard_hyp x : ℕ', exact () }, case positive { guard_hyp n : ℕ, guard_hyp h : n > 0, exact () } end -- By default, induction' generates the most general possible induction -- hypothesis. example {n m : ℕ} : n + m = m + n := begin induction' m, case zero { simp }, case succ : k IH { guard_hyp k : ℕ, guard_hyp n : ℕ, guard_hyp IH : ∀ {n}, n + k = k + n, ac_refl } end -- Here's an example where this is more useful. example {n m : ℕ} (h : n + n = m + m) : n = m := begin induction' n with n ih, case zero { cases' m, { refl }, { cases' h } }, case succ { cases' m, { cases' h }, { rw @ih m, simp only [nat.succ_eq_add_one] at h, replace h : n + n + 2 = m + m + 2 := by linarith, injections } } end -- If we don't want a hypothesis to be generalised, we can say so with a -- "fixing" clause. example {n m : ℕ} : n + m = m + n := begin induction' m fixing n, case zero { simp }, case succ : k IH { guard_hyp k : ℕ, guard_hyp n : ℕ, guard_hyp IH : n + k = k + n, ac_refl } end -- We can also fix all hypotheses. This gives us the behaviour of stock -- `induction`. Hypotheses which depend on the major premise (or its index -- arguments) still get generalised. example {n m k : ℕ} (h : n + m = k) : n + m = k := begin induction' n fixing *, case zero { simp [*] }, case succ : n IH { guard_hyp n : ℕ, guard_hyp m : ℕ, guard_hyp k : ℕ, guard_hyp h : n.succ + m = k, guard_hyp IH : n + m = k → n + m = k, -- Neither m nor k were generalised. exact h } end -- We can also generalise only certain hypotheses using a `generalizing` -- clause. This gives us the behaviour of stock `induction ... generalizing`. -- Hypotheses which depend on the major premise get generalised even if they are -- not mentioned in the `generalizing` clause. example {n m k : ℕ} (h : n + m = k) : n + m = k := begin induction' n generalizing k, case zero { simp [*] }, case succ : n IH { guard_hyp n : ℕ, guard_hyp m : ℕ, guard_hyp k : ℕ, guard_hyp h : n.succ + m = k, guard_hyp IH : ∀ {k}, n + m = k → n + m = k, -- k was generalised, but m was not. exact h } end -- Sometimes generalising a hypothesis H does not give us a more general -- induction hypothesis. In such cases, induction' should not generalise H. The -- following example is not realistic, but situations like this can occur in -- practice; see accufact_1_eq_fact below. example (n m k : ℕ) : m + k = k + m := begin induction' m, case zero { simp }, case succ { guard_hyp ih : ∀ k, m + k = k + m, -- k was generalised because this makes the IH more general. -- n was not generalised -- if it had been, the IH would be -- -- ∀ n k, m + k = k + m -- -- with one useless additional argument. ac_refl } end -- This example checks that constructor arguments don't 'steal' the names of -- generalised hypotheses. example (n : list ℕ) (n : ℕ) : list ℕ := begin -- this performs induction on (n : ℕ) induction' n, { exact n }, { guard_hyp n : list ℕ, guard_hyp n_1 : ℕ, -- n is the list, which was automatically generalized and keeps its name. -- n_1 is the recursive argument of `nat.succ`. It would be called `n` if -- there wasn't already an `n` in the context. exact (n_1 :: n) } end -- This example tests whether `induction'` gets confused when there are -- additional cases around. example (k : ℕ) (t : Two) : 0 + k = k := begin cases t, induction' k, { refl }, { simp }, induction' k, { refl }, { simp } end -- The type of the induction premise can be a complex expression so long as it -- normalises to an inductive (possibly applied to params/indexes). example (n) : 0 + n = n := begin let T := ℕ, change T at n, induction' n; simp end -- Fail if the type of the induction premise is not an inductive type example {α} (x : α) (f : α → α) : unit := begin success_if_fail { induction' x }, success_if_fail { induction' f }, exact () end -- The following example used to trigger a bug where eliminate would generate -- hypotheses with duplicate names. structure fraction : Type := (num : ℤ) (denom : ℤ) (denom_ne_zero : denom ≠ 0) lemma fraction.ext (a b : fraction) (hnum : fraction.num a = fraction.num b) (hdenom : fraction.denom a = fraction.denom b) : a = b := begin cases' a, cases' b, guard_hyp num : ℤ, guard_hyp denom : ℤ, guard_hyp num_1 : ℤ, guard_hyp denom_1 : ℤ, rw fraction.mk.inj_eq, exact and.intro hnum hdenom end -- A "with" clause can be used to give the names of constructor arguments (as -- for `cases`, `induction` etc). example (x : ℕ × ℕ) (y : Vec ℕ 2) (z : List ℕ) : unit := begin cases' x with i j k l, guard_hyp i : ℕ, guard_hyp j : ℕ, clear i j, cases' y with i j k l, -- Note that i is 'skipped' because it is used to name the (n : ℕ) -- argument of `cons`, but that argument is cleared by index unification. I -- find this a little strange, but `cases` also behaves like this. guard_hyp j : ℕ, guard_hyp k : Vec ℕ 1, clear j k, cases' z with i j k l, case nil { exact () }, case cons { guard_hyp i : ℕ, guard_hyp j : List ℕ, exact () } end -- "with" also works with induction'. example (x : List ℕ) : unit := begin induction' x with i j k l, case nil { exact () }, case cons { guard_hyp i : ℕ, guard_hyp j : List ℕ, guard_hyp k : unit, exact () } end -- An underscore in a "with" clause means "use the auto-generated name for this -- argument". example (x : List ℕ) : unit := begin induction' x with _ j _ l, case nil { exact () }, case cons { guard_hyp x : ℕ, guard_hyp j : List ℕ, guard_hyp ih : unit, exact () } end namespace with_tests inductive test | intro (n) (f : fin n) (m) (g : fin m) -- A hyphen in a "with" clause means "clear this hypothesis and its reverse -- dependencies". example (h : test) : unit := begin cases' h with - F M G, guard_hyp M : ℕ, guard_hyp G : fin M, success_if_fail { guard_hyp n }, success_if_fail { guard_hyp F }, exact () end -- Names given in a "with" clause are used verbatim, even if this results in -- shadowing. example (x : ℕ) (h : test) : unit := begin cases' h with x y y -, /- Expected goal: x x : ℕ, y : fin x, y : ℕ ⊢ unit It's hard to give a good test case here because we would need a variant of `guard_hyp` that is sensitive to shadowing. But we can at least check that the hyps don't have the names they would get if we avoided shadowing. -/ success_if_fail { guard_hyp x_1 }, success_if_fail { guard_hyp y_1 }, exact () end end with_tests -- induction' and cases' can be used to perform induction/case analysis on -- arbitrary expressions (not just hypotheses). A very synthetic example: example {α} : α ∨ ¬ α := begin cases' classical.em α with a nota, { exact (or.inl a) }, { exact (or.inr nota) } end -- Cases'/induction' can add an equation witnessing the case split it -- performed. Again, a highly synthetic example: example {α} (xs : list α) : xs.reverse.length = 0 ∨ ∃ m, xs.reverse.length = m + 1 := begin cases' eq : xs.length, case zero { left, rw list.length_reverse, exact eq }, case succ : l { right, rw list.length_reverse, use l, exact eq } end -- Index equation simplification can deal with equations that aren't in normal -- form. example {α} (x : α) (xs) : list.take 1 (x :: xs) ≠ [] := begin intro contra, cases' contra end -- Index generalisation should leave early occurrences of complex index terms -- alone. This means that given the major premise `e : E (f y) y` where `y` is a -- complex term, index generalisation should give us -- -- e : E (f y) i, -- -- *not* -- -- e : E (f i) i. -- -- Otherwise we get problems with examples like this: inductive ℕ₂ : Type | zero | succ (n : ℕ₂) : ℕ₂ namespace ℕ₂ def plus : ℕ₂ → ℕ₂ → ℕ₂ | zero y := y | (succ x) y := succ (plus x y) example (x : ℕ₂) (h : plus zero x = zero) : x = zero := begin cases' h, guard_target zero = plus zero zero, refl -- If index generalisation blindly replaced all occurrences of zero, we would -- get -- -- index = zero → plus index x = index → x = index -- -- and after applying the recursor -- -- plus index x = zero → x = plus index x -- -- This leaves the goal provable, but very confusing. end -- TODO Here's a test case (due to Floris van Doorn) where index generalisation -- is over-eager: it replaces the complex index `zero` everywhere in the goal, -- which makes the goal type-incorrect. `cases` does not exhibit this problem. example (x : ℕ₂) (h : plus zero x = zero) : (⟨x, h⟩ : ∃ x, plus zero x = zero) = ⟨zero, rfl⟩ := begin success_if_fail { cases' h }, cases h, refl end end ℕ₂ -- For whatever reason, the eliminator for `false` has an explicit argument -- where all other eliminators have an implicit one. `eliminate_hyp` has to -- work around this to ensure that we can eliminate a `false` hyp. example {α} (h : false) : α := begin cases' h end -- Index equation simplification also works with nested datatypes. inductive rose (α : Type) : Type | leaf : rose | node (val : α) (children : list rose) : rose namespace rose inductive nonempty {α} : rose α → Prop | node (v c cs) : nonempty (node v (c :: cs)) lemma nonempty_node_elim {α} {v : α} {cs} (h : nonempty (node v cs)) : ¬ cs.empty := begin induction' h, finish end end rose -- The following test cases, provided by Patrick Massot, test interactions with -- several 'advanced' Lean features. namespace topological_space_tests class topological_space (X : Type) := (is_open : set X → Prop) (univ_mem : is_open set.univ) (union : ∀ (B : set (set X)) (h : ∀ b ∈ B, is_open b), is_open (⋃₀ B)) (inter : ∀ (A B : set X) (hA : is_open A) (hB : is_open B), is_open (A ∩ B)) open topological_space (is_open) inductive generated_open (X : Type) (g : set (set X)) : set X → Prop | generator : ∀ A ∈ g, generated_open A | inter : ∀ A B, generated_open A → generated_open B → generated_open (A ∩ B) | union : ∀ (B : set (set X)), (∀ b ∈ B, generated_open b) → generated_open (⋃₀ B) | univ : generated_open set.univ def generate_from (X : Type) (g : set (set X)) : topological_space X := { is_open := generated_open X g, univ_mem := generated_open.univ, inter := generated_open.inter, union := generated_open.union } inductive generated_filter {X : Type*} (g : set (set X)) : set X → Prop | generator {A} : A ∈ g → generated_filter A | inter {A B} : generated_filter A → generated_filter B → generated_filter (A ∩ B) | subset {A B} : generated_filter A → A ⊆ B → generated_filter B | univ : generated_filter set.univ def neighbourhood {X : Type} [topological_space X] (x : X) (V : set X) : Prop := ∃ (U : set X), is_open U ∧ x ∈ U ∧ U ⊆ V axiom nhd_inter {X : Type*} [topological_space X] {x : X} {U V : set X} (hU : neighbourhood x U) (hV : neighbourhood x V) : neighbourhood x (U ∩ V) axiom nhd_superset {X : Type*} [topological_space X] {x : X} {U V : set X} (hU : neighbourhood x U) (hUV : U ⊆ V) : neighbourhood x V axiom nhd_univ {X : Type*} [topological_space X] {x : X} : neighbourhood x set.univ -- This example fails if auto-generalisation refuses to revert before -- frozen local instances. example {X : Type} [T : topological_space X] {s : set (set X)} (h : T = generate_from X s) {U x} : generated_filter {V | V ∈ s ∧ x ∈ V} U → neighbourhood x U := begin rw h, intro U_in, induction' U_in fixing T h with U hU U V U_gen V_gen hU hV U V U_gen hUV hU, { exact ⟨U, generated_open.generator U hU.1, hU.2, set.subset.refl U⟩ }, { exact @nhd_inter _ (generate_from X s) _ _ _ hU hV }, { exact @nhd_superset _ (generate_from X s) _ _ _ hU hUV }, { apply nhd_univ } end -- This example fails if auto-generalisation tries to generalise `let` -- hypotheses. example {X : Type} [T : topological_space X] {s : set (set X)} (h : T = generate_from X s) {U x} : generated_filter {V | V ∈ s ∧ x ∈ V} U → neighbourhood x U := begin rw h, letI := generate_from X s, intro U_in, induction' U_in fixing T h with U hU U V U_gen V_gen hU hV U V U_gen hUV hU, { exact ⟨U, generated_open.generator U hU.1, hU.2, set.subset.refl U⟩ }, { exact nhd_inter hU hV }, { exact nhd_superset hU hUV }, { apply nhd_univ } end -- This example fails if infinitely branching inductive types like -- `generated_open` are not handled properly. In particular, it tests the -- interaction of infinitely branching types with complex indices. example {X : Type*} [T : topological_space X] {s : set (set X)} (h : T = generate_from X s) {U : set X} {x : X} : neighbourhood x U → generated_filter {V | V ∈ s ∧ x ∈ V} U := begin rw h, letI := generate_from X s, clear h, rintros ⟨V, V_op, x_in, hUV⟩, apply generated_filter.subset _ hUV, clear hUV, induction' V_op fixing _inst T s U, { apply generated_filter.generator, split ; assumption }, { cases x_in, apply generated_filter.inter ; tauto }, { rw set.mem_sUnion at x_in, rcases x_in with ⟨W, hW, hxW⟩, exact generated_filter.subset (ih W hW hxW) (set.subset_sUnion_of_mem hW)}, { apply generated_filter.univ } end end topological_space_tests -------------------------------------------------------------------------------- -- Logical Verification Use Cases -------------------------------------------------------------------------------- -- The following examples were provided by Jasmin Blanchette. They are taken -- from his course 'Logical Verification'. /- Head induction for transitive closure -/ inductive star {α : Sort*} (r : α → α → Prop) (a : α) : α → Prop | refl {} : star a | tail {b c} : star b → r b c → star c namespace star variables {α : Sort*} {r : α → α → Prop} {a b c d : α} lemma head (hab : r a b) (hbc : star r b c) : star r a c := begin induction' hbc fixing hab, case refl { exact refl.tail hab }, case tail : c d hbc hcd hac { exact hac.tail hcd } end -- In this example, induction' must apply the dependent recursor for star; the -- nondependent one doesn't apply. lemma head_induction_on {b} {P : ∀a : α, star r a b → Prop} {a} (h : star r a b) (refl : P b refl) (head : ∀{a c} (h' : r a c) (h : star r c b), P c h → P a (h.head h')) : P a h := begin induction' h, case refl { exact refl }, case tail : b c hab hbc ih { apply ih, { exact head hbc _ refl, }, { intros _ _ hab _, exact head hab _} } end end star /- Factorial -/ def accufact : ℕ → ℕ → ℕ | a 0 := a | a (n + 1) := accufact ((n + 1) * a) n lemma accufact_1_eq_fact (n : ℕ) : accufact 1 n = nat.factorial n := have accufact_eq_fact_mul : ∀m a, accufact a m = nat.factorial m * a := begin intros m a, induction' m, case zero { simp [nat.factorial, accufact] }, case succ { simp [nat.factorial, accufact, ih, nat.succ_eq_add_one], cc } end, by simp [accufact_eq_fact_mul n 1] /- Substitution -/ namespace expressions inductive exp : Type | Var : string → exp | Num : ℤ → exp | Plus : exp → exp → exp export exp def subst (ρ : string → exp) : exp → exp | (Var y) := ρ y | (Num i) := Num i | (Plus e₁ e₂) := Plus (subst e₁) (subst e₂) lemma subst_Var (e : exp) : subst (λx, Var x) e = e := begin induction' e, case Var { guard_hyp s : string, rw [subst] }, case Num { guard_hyp n : ℤ, rw [subst] }, case Plus { guard_hyp e : exp, guard_hyp e_1 : exp, guard_hyp ih_e, guard_hyp ih_e_1, rw [subst], rw ih_e, rw ih_e_1 } end end expressions /- Less-than -/ namespace less_than inductive lt : nat → nat → Type | zero_succ (n : nat) : lt 0 (1 + n) | succ_succ {n m : nat} : lt n m → lt (1 + n) (1 + m) inductive lte : nat → nat → Type | zero (n : nat) : lte 0 n | succ {n m : nat} : lte n m → lte (1 + n) (1 + m) def lt_lte {n m} : lt n m → lte n m := begin intro lt_n_m, induction' lt_n_m, case zero_succ : i { constructor }, case succ_succ : i j lt_i_j ih { constructor, apply ih } end end less_than /- Sortedness -/ inductive sorted : list ℕ → Prop | nil : sorted [] | single {x : ℕ} : sorted [x] | two_or_more {x y : ℕ} {zs : list ℕ} (hle : x ≤ y) (hsorted : sorted (y :: zs)) : sorted (x :: y :: zs) /- In this example it's important that cases' *doesn't* normalise the values of indexes when simplifying index equations. -/ lemma not_sorted_17_13 : ¬ sorted [17, 13] := begin intro h, cases' h, guard_hyp hle : 17 ≤ 13, linarith end /- Palindromes -/ namespace palindrome inductive palindrome {α : Type} : list α → Prop | nil : palindrome [] | single (x : α) : palindrome [x] | sandwich (x : α) (xs : list α) (hpal : palindrome xs) : palindrome ([x] ++ xs ++ [x]) axiom reverse_append_sandwich {α : Type} (x : α) (ys : list α) : list.reverse ([x] ++ ys ++ [x]) = [x] ++ list.reverse ys ++ [x] lemma rev_palindrome {α : Type} (xs : list α) (hpal : palindrome xs) : palindrome (list.reverse xs) := begin induction' hpal, case nil { exact palindrome.nil }, case single { exact palindrome.single _ }, case sandwich { rw reverse_append_sandwich, apply palindrome.sandwich, apply ih } end end palindrome /- Transitive Closure -/ namespace transitive_closure inductive tc {α : Type} (r : α → α → Prop) : α → α → Prop | base (x y : α) (hr : r x y) : tc x y | step (x y z : α) (hr : r x y) (ht : tc y z) : tc x z /- The transitive closure is a nice example with lots of variables to keep track of. We start with a lemma where the variable names do not collide with those appearing in the definition of the inductive predicate. -/ lemma tc_pets₁ {α : Type} (r : α → α → Prop) (c : α) : ∀a b, tc r a b → r b c → tc r a c := begin intros a b htab hrbc, induction' htab fixing c, case base : _ _ hrab { exact tc.step _ _ _ hrab (tc.base _ _ hrbc) }, case step : _ x _ hrax { exact tc.step _ _ _ hrax (ih hrbc) } end /- The same proof, but this time the variable names clash. Also, this time we let `induction'` generalize `z`. -/ lemma tc_pets₂ {α : Type} (r : α → α → Prop) (z : α) : ∀x y, tc r x y → r y z → tc r x z := begin intros x y htxy hryz, induction' htxy, case base : _ _ hrxy { exact tc.step _ _ _ hrxy (tc.base _ _ hryz) }, case step : _ x' y hrxx' htx'y ih { exact tc.step _ _ _ hrxx' (ih _ hryz) } end /- Another proof along the same lines. -/ lemma tc_trans {α : Type} (r : α → α → Prop) (c : α) : ∀a b : α, tc r a b → tc r b c → tc r a c := begin intros a b htab htbc, induction' htab, case base { exact tc.step _ _ _ hr htbc }, case step { exact tc.step _ _ _ hr (ih _ htbc) } end /- ... and with clashing variable names: -/ lemma tc_trans' {α : Type} (r : α → α → Prop) {x y z} : tc r x y → tc r y z → tc r x z := begin intros h₁ h₂, induction' h₁, case base { exact tc.step _ _ _ hr h₂ }, case step { exact tc.step _ _ _ hr (ih h₂) } end end transitive_closure /- Evenness -/ inductive Even : ℕ → Prop | zero : Even 0 | add_two : ∀k : ℕ, Even k → Even (k + 2) lemma not_even_2_mul_add_1 (n : ℕ) : ¬ Even (2 * n + 1) := begin intro h, induction' h, -- No case tag since there's only one goal. I don't really like this, but -- this is the behaviour of induction/cases. { apply ih (n - 1), cases' n, case zero { linarith }, case succ { simp [nat.succ_eq_add_one] at *, linarith } } end /- Big-Step Semantics -/ namespace semantics def state := string → ℕ def state.update (name : string) (val : ℕ) (s : state) : state := λname', if name' = name then val else s name' notation s `{` name ` ↦ ` val `}` := state.update name val s inductive stmt : Type | skip : stmt | assign : string → (state → ℕ) → stmt | seq : stmt → stmt → stmt | ite : (state → Prop) → stmt → stmt → stmt | while : (state → Prop) → stmt → stmt export stmt infixr ` ;; ` : 90 := stmt.seq /- Our first version is partly uncurried, like in the Logical Verification course, and also like in Concrete Semantics. This makes the binary infix notation possible. -/ inductive big_step : stmt × state → state → Prop | skip {s} : big_step (skip, s) s | assign {x a s} : big_step (assign x a, s) (s{x ↦ a s}) | seq {S T s t u} (hS : big_step (S, s) t) (hT : big_step (T, t) u) : big_step (seq S T, s) u | ite_true {b : state → Prop} {S T s t} (hcond : b s) (hbody : big_step (S, s) t) : big_step (ite b S T, s) t | ite_false {b : state → Prop} {S T s t} (hcond : ¬ b s) (hbody : big_step (T, s) t) : big_step (ite b S T, s) t | while_true {b : state → Prop} {S s t u} (hcond : b s) (hbody : big_step (S, s) t) (hrest : big_step (while b S, t) u) : big_step (while b S, s) u | while_false {b : state → Prop} {S s} (hcond : ¬ b s) : big_step (while b S, s) s infix ` ⟹ `:110 := big_step open big_step lemma not_big_step_while_true {S s t} : ¬ (while (λ_, true) S, s) ⟹ t := begin intro hw, induction' hw, case while_true { exact ih_hw_1 }, case while_false { exact hcond trivial } end /- The same with a curried version of the predicate. It should make no difference whether a predicate is curried or uncurried. -/ inductive curried_big_step : stmt → state → state → Prop | skip {s} : curried_big_step skip s s | assign {x a s} : curried_big_step (assign x a) s (s{x ↦ a s}) | seq {S T s t u} (hS : curried_big_step S s t) (hT : curried_big_step T t u) : curried_big_step (seq S T) s u | ite_true {b : state → Prop} {S T s t} (hcond : b s) (hbody : curried_big_step S s t) : curried_big_step (ite b S T) s t | ite_false {b : state → Prop} {S T s t} (hcond : ¬ b s) (hbody : curried_big_step T s t) : curried_big_step (ite b S T) s t | while_true {b : state → Prop} {S s t u} (hcond : b s) (hbody : curried_big_step S s t) (hrest : curried_big_step (while b S) t u) : curried_big_step (while b S) s u | while_false {b : state → Prop} {S s} (hcond : ¬ b s) : curried_big_step (while b S) s s lemma not_curried_big_step_while_true {S s t} : ¬ curried_big_step (while (λ_, true) S) s t := begin intro hw, induction' hw, case while_true { exact ih_hw_1, }, case while_false { exact hcond trivial } end end semantics /- Small-Step Semantics -/ namespace semantics inductive small_step : stmt × state → stmt × state → Prop | assign {x a s} : small_step (assign x a, s) (skip, s{x ↦ a s}) | seq_step {S S' T s s'} (hS : small_step (S, s) (S', s')) : small_step (seq S T, s) (seq S' T, s') | seq_skip {T s} : small_step (seq skip T, s) (T, s) | ite_true {b : state → Prop} {S T s} (hcond : b s) : small_step (ite b S T, s) (S, s) | ite_false {b : state → Prop} {S T s} (hcond : ¬ b s) : small_step (ite b S T, s) (T, s) | while {b : state → Prop} {S s} : small_step (while b S, s) (ite b (seq S (while b S)) skip, s) lemma small_step_if_equal_states {S T s t s' t'} (hstep : small_step (S, s) (T, t)) (hs : s' = s) (ht : t' = t) : small_step (S, s') (T, t') := begin induction' hstep, { rw [hs, ht], exact small_step.assign, }, { apply small_step.seq_step, exact ih hs ht, }, { rw [hs, ht], exact small_step.seq_skip, }, { rw [hs, ht], exact small_step.ite_true hcond, }, { rw [hs, ht], exact small_step.ite_false hcond, }, { rw [hs, ht], exact small_step.while, } end infixr (name := small_step) ` ⇒ ` := small_step infixr (name := small_step.star) ` ⇒* ` : 100 := star small_step /- More lemmas about big-step and small-step semantics. These are taken from the Logical Verification course materials. They provide lots of good test cases for cases'/induction'. -/ namespace star variables {α : Sort*} {r : α → α → Prop} {a b c d : α} attribute [refl] star.refl @[trans] lemma trans (hab : star r a b) (hbc : star r b c) : star r a c := begin induction' hbc, case refl { assumption }, case tail : c d hbc hcd hac { exact (star.tail (hac hab)) hcd } end lemma single (hab : r a b) : star r a b := star.refl.tail hab lemma trans_induction_on {α : Sort*} {r : α → α → Prop} {p : ∀{a b : α}, star r a b → Prop} {a b : α} (h : star r a b) (ih₁ : ∀a, @p a a star.refl) (ih₂ : ∀{a b} (h : r a b), p (single h)) (ih₃ : ∀{a b c} (h₁ : star r a b) (h₂ : star r b c), p h₁ → p h₂ → p (trans h₁ h₂)) : p h := begin induction' h, case refl { exact ih₁ a }, case tail : b c hab hbc ih { exact ih₃ hab (single hbc) (ih ih₁ @ih₂ @ih₃) (ih₂ hbc) } end lemma lift {β : Sort*} {s : β → β → Prop} (f : α → β) (h : ∀a b, r a b → s (f a) (f b)) (hab : star r a b) : star s (f a) (f b) := begin apply trans_induction_on hab, exact (λ a, star.refl), exact (λ a b, star.single ∘ h _ _), exact (λ a b c _ _, star.trans) end end star lemma big_step_deterministic {S s l r} (hl : (S, s) ⟹ l) (hr : (S, s) ⟹ r) : l = r := begin induction' hl, case skip : t { cases' hr, refl }, case assign : x a s { cases' hr, refl }, case seq : S T s t l hS hT ihS ihT { cases' hr with _ _ _ _ _ _ _ t' _ hS' hT', cases' ihS hS', cases' ihT hT', refl }, case ite_true : b S T s t hb hS ih { cases' hr, { apply ih, assumption }, { apply ih, cc } }, case ite_false : b S T s t hb hT ih { cases' hr, { apply ih, cc }, { apply ih, assumption } }, case while_true : b S s t u hb hS hw ihS ihw { cases' hr, { cases' ihS hr, cases' ihw hr_1, refl }, { cc } }, { cases' hr, { cc }, { refl } } end @[simp] lemma big_step_skip_iff {s t} : (stmt.skip, s) ⟹ t ↔ t = s := begin apply iff.intro, { intro h, cases' h, refl }, { intro h, rw h, exact big_step.skip } end @[simp] lemma big_step_assign_iff {x a s t} : (stmt.assign x a, s) ⟹ t ↔ t = s{x ↦ a s} := begin apply iff.intro, { intro h, cases' h, refl }, { intro h, rw h, exact big_step.assign } end @[simp] lemma big_step_seq_iff {S T s t} : (S ;; T, s) ⟹ t ↔ (∃u, (S, s) ⟹ u ∧ (T, u) ⟹ t) := begin apply iff.intro, { intro h, cases' h, apply exists.intro, apply and.intro; assumption }, { intro h, cases' h, cases' h, apply big_step.seq; assumption } end @[simp] lemma big_step_ite_iff {b S T s t} : (stmt.ite b S T, s) ⟹ t ↔ (b s ∧ (S, s) ⟹ t) ∨ (¬ b s ∧ (T, s) ⟹ t) := begin apply iff.intro, { intro h, cases' h, { apply or.intro_left, cc }, { apply or.intro_right, cc } }, { intro h, cases' h; cases' h, { apply big_step.ite_true; assumption }, { apply big_step.ite_false; assumption } } end lemma big_step_while_iff {b S s u} : (stmt.while b S, s) ⟹ u ↔ (∃t, b s ∧ (S, s) ⟹ t ∧ (stmt.while b S, t) ⟹ u) ∨ (¬ b s ∧ u = s) := begin apply iff.intro, { intro h, cases' h, { apply or.intro_left, apply exists.intro t, cc }, { apply or.intro_right, cc } }, { intro h, cases' h, case or.inl { cases' h with t h, cases' h with hb h, cases' h with hS hwhile, exact big_step.while_true hb hS hwhile }, case or.inr { cases' h with hb hus, rw hus, exact big_step.while_false hb } } end lemma big_step_while_true_iff {b : state → Prop} {S s u} (hcond : b s) : (stmt.while b S, s) ⟹ u ↔ (∃t, (S, s) ⟹ t ∧ (stmt.while b S, t) ⟹ u) := by rw big_step_while_iff; simp [hcond] @[simp] lemma big_step_while_false_iff {b : state → Prop} {S s t} (hcond : ¬ b s) : (stmt.while b S, s) ⟹ t ↔ t = s := by rw big_step_while_iff; simp [hcond] lemma small_step_final (S s) : (¬ ∃T t, (S, s) ⇒ (T, t)) ↔ S = stmt.skip := begin induction' S, case skip { simp, intros T t hstep, cases' hstep }, case assign : x a { simp, apply exists.intro stmt.skip, apply exists.intro (s{x ↦ a s}), exact small_step.assign }, case seq : S T ihS ihT { simp, cases' classical.em (S = stmt.skip), case inl { rw h, apply exists.intro T, apply exists.intro s, exact small_step.seq_skip }, case inr { simp [h, not_forall, not_not] at ihS, cases' ihS s with S' hS', cases' hS' with s' hs', apply exists.intro (S' ;; T), apply exists.intro s', exact small_step.seq_step hs' } }, case ite : b S T ihS ihT { simp, cases' classical.em (b s), case inl { apply exists.intro S, apply exists.intro s, exact small_step.ite_true h }, case inr { apply exists.intro T, apply exists.intro s, exact small_step.ite_false h } }, case while : b S ih { simp, apply exists.intro (stmt.ite b (S ;; stmt.while b S) stmt.skip), apply exists.intro s, exact small_step.while } end lemma small_step_deterministic {S s Ll Rr} (hl : (S, s) ⇒ Ll) (hr : (S, s) ⇒ Rr) : Ll = Rr := begin induction' hl, case assign : x a s { cases' hr, refl }, case seq_step : S S₁ T s s₁ hS₁ ih { cases' hr, case seq_step : S S₂ _ _ s₂ hS₂ { have hSs₁₂ := ih hS₂, cc }, case seq_skip { cases' hS₁ } }, case seq_skip : T s { cases' hr, { cases' hr }, { refl } }, case ite_true : b S T s hcond { cases' hr, case ite_true { refl }, case ite_false { cc } }, case ite_false : b S T s hcond { cases' hr, case ite_true { cc }, case ite_false { refl } }, case while : b S s { cases' hr, refl } end lemma small_step_skip {S s t} : ¬ ((stmt.skip, s) ⇒ (S, t)) := by intro h; cases' h @[simp] lemma small_step_seq_iff {S T s Ut} : (S ;; T, s) ⇒ Ut ↔ (∃S' t, (S, s) ⇒ (S', t) ∧ Ut = (S' ;; T, t)) ∨ (S = stmt.skip ∧ Ut = (T, s)) := begin apply iff.intro, { intro h, cases' h, { apply or.intro_left, apply exists.intro S', apply exists.intro s', cc }, { apply or.intro_right, cc } }, { intro h, cases' h, { cases' h, cases' h, cases' h, rw right, apply small_step.seq_step, assumption }, { cases' h, rw left, rw right, apply small_step.seq_skip } } end @[simp] lemma small_step_ite_iff {b S T s Us} : (stmt.ite b S T, s) ⇒ Us ↔ (b s ∧ Us = (S, s)) ∨ (¬ b s ∧ Us = (T, s)) := begin apply iff.intro, { intro h, cases' h, { apply or.intro_left, cc }, { apply or.intro_right, cc } }, { intro h, cases' h, { cases' h, rw right, apply small_step.ite_true, assumption }, { cases' h, rw right, apply small_step.ite_false, assumption } } end lemma star_small_step_seq {S T s u} (h : (S, s) ⇒* (stmt.skip, u)) : (S ;; T, s) ⇒* (stmt.skip ;; T, u) := begin apply star.lift (λSs, (prod.fst Ss ;; T, prod.snd Ss)) _ h, intros Ss Ss' h, cases' Ss, cases' Ss', apply small_step.seq_step, assumption end lemma star_small_step_of_big_step {S s t} (h : (S, s) ⟹ t) : (S, s) ⇒* (stmt.skip, t) := begin induction' h, case skip { refl }, case assign { exact star.single small_step.assign }, case seq : S T s t u hS hT ihS ihT { transitivity, exact star_small_step_seq ihS, apply star.head small_step.seq_skip ihT }, case ite_true : b S T s t hs hst ih { exact star.head (small_step.ite_true hs) ih }, case ite_false : b S T s t hs hst ih { exact star.head (small_step.ite_false hs) ih }, case while_true : b S s t u hb hS hw ihS ihw { exact (star.head small_step.while (star.head (small_step.ite_true hb) (star.trans (star_small_step_seq ihS) (star.head small_step.seq_skip ihw)))) }, case while_false : b S s hb { exact star.tail (star.single small_step.while) (small_step.ite_false hb) } end lemma big_step_of_small_step_of_big_step {S₀ S₁ s₀ s₁ s₂} (h₁ : (S₀, s₀) ⇒ (S₁, s₁)) : (S₁, s₁) ⟹ s₂ → (S₀, s₀) ⟹ s₂ := begin induction' h₁; simp [*, big_step_while_true_iff, or_imp_distrib] {contextual := tt}, case seq_step { intros u hS' hT, apply exists.intro u, exact and.intro (ih hS') hT }, end lemma big_step_of_star_small_step {S s t} : (S, s) ⇒* (stmt.skip, t) → (S, s) ⟹ t := begin generalize hSs : (S, s) = Ss, intro h, induction h using star.head_induction_on with _ S's' h h' ih generalizing S s; cases' hSs, { exact big_step.skip }, { cases' S's' with S' s', apply big_step_of_small_step_of_big_step h, apply ih, refl } end end semantics
d8143342a49216aca8cbeb19aadbb36fee7cced2
34c1747a946aa0941114ffca77a3b7c1e4cfb686
/src/sheaves/presheaf_on_basis.lean
88bc4e7d5455601a9591aca08b9cc9aea08fe569
[]
no_license
martrik/lean-scheme
2b9edd63550c4579a451f793ab289af9fc79a16d
033dc47192ba4c61e4e771701f5e29f8007e6332
refs/heads/master
1,588,866,287,405
1,554,922,682,000
1,554,922,682,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,529
lean
/- Presheaf (of types) on basis. https://stacks.math.columbia.edu/tag/009I -/ import topology.basic import topology.opens import sheaves.presheaf universes u v open topological_space -- Presheaf of types where we only define sections on basis elements. structure presheaf_on_basis (α : Type u) [T : topological_space α] {B : set (opens α)} (HB : opens.is_basis B) := (F : Π {U}, U ∈ B → Type v) (res : ∀ {U V} (BU : U ∈ B) (BV : V ∈ B) (HVU : V ⊆ U), F BU → F BV) (Hid : ∀ {U} (BU : U ∈ B), (res BU BU (set.subset.refl U)) = id) (Hcomp : ∀ {U V W} (BU : U ∈ B) (BV : V ∈ B) (BW : W ∈ B) (HWV : W ⊆ V) (HVU : V ⊆ U), res BU BW (set.subset.trans HWV HVU) = (res BV BW HWV) ∘ (res BU BV HVU)) namespace presheaf_on_basis variables {α : Type u} [T : topological_space α] variables {B : set (opens α)} {HB : opens.is_basis B} instance : has_coe_to_fun (presheaf_on_basis α HB) := { F := λ _, Π {U}, U ∈ B → Type v, coe := presheaf_on_basis.F } -- Simplification lemmas. @[simp] lemma Hid' (F : presheaf_on_basis α HB) : ∀ {U} (BU : U ∈ B) (s : F BU), (F.res BU BU (set.subset.refl U)) s = s := λ U OU s, by rw F.Hid OU; simp @[simp] lemma Hcomp' (F : presheaf_on_basis α HB) : ∀ {U V W} (BU : U ∈ B) (BV : V ∈ B) (BW : W ∈ B) (HWV : W ⊆ V) (HVU : V ⊆ U) (s : F BU), (F.res BU BW (set.subset.trans HWV HVU)) s = (F.res BV BW HWV) ((F.res BU BV HVU) s) := λ U V W OU OV OW HWV HVU s, by rw F.Hcomp OU OV OW HWV HVU -- Morphism of presheaves on a basis (same as presheaves). structure morphism (F G : presheaf_on_basis α HB) := (map : ∀ {U} (HU : U ∈ B), F HU → G HU) (commutes : ∀ {U V} (HU : U ∈ B) (HV : V ∈ B) (Hsub : V ⊆ U), (G.res HU HV Hsub) ∘ (map HU) = (map HV) ∘ (F.res HU HV Hsub)) infix `⟶`:80 := morphism section morphism def comp {F G H : presheaf_on_basis α HB} (fg : F ⟶ G) (gh : G ⟶ H) : F ⟶ H := { map := λ U HU, gh.map HU ∘ fg.map HU, commutes := λ U V BU BV HVU, begin rw [←function.comp.assoc, gh.commutes BU BV HVU], symmetry, rw [function.comp.assoc, ←fg.commutes BU BV HVU] end } infix `⊚`:80 := comp def id (F : presheaf_on_basis α HB) : F ⟶ F := { map := λ U BU, id, commutes := λ U V BU BV HVU, by simp, } structure iso (F G : presheaf_on_basis α HB) := (mor : F ⟶ G) (inv : G ⟶ F) (mor_inv_id : mor ⊚ inv = id F) (inv_mor_id : inv ⊚ mor = id G) infix `≅`:80 := iso end morphism end presheaf_on_basis
3531441d1394aeb63e6f773e363abb97e9280fef
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/11_Tactic-Style_Proofs.org.51.lean
b86135ecd7827f9397ced078c07a9bf585318345
[]
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
279
lean
import standard import data.list open list variable {A : Type} theorem append_assoc : ∀ (s t u : list A), s ++ t ++ u = s ++ (t ++ u) | append_assoc nil t u := by apply rfl | append_assoc (a :: l) t u := begin rewrite ▸ a :: (l ++ t ++ u) = _, rewrite append_assoc end
28d4dd837126fb9d14d4b7e635b5364bfc4467bf
95dcf8dea2baf2b4b0a60d438f27c35ae3dd3990
/src/category_theory/limits/cones.lean
aa1275e12543dbc75b82c4dc070023c6fce30871
[ "Apache-2.0" ]
permissive
uniformity1/mathlib
829341bad9dfa6d6be9adaacb8086a8a492e85a4
dd0e9bd8f2e5ec267f68e72336f6973311909105
refs/heads/master
1,588,592,015,670
1,554,219,842,000
1,554,219,842,000
179,110,702
0
0
Apache-2.0
1,554,220,076,000
1,554,220,076,000
null
UTF-8
Lean
false
false
11,111
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Stephen Morgan, Scott Morrison import category_theory.natural_isomorphism import category_theory.whiskering import category_theory.const import category_theory.opposites import category_theory.yoneda universes v u u' -- declare the `v`'s first; see `category_theory.category` for an explanation open category_theory -- There is an awkward difficulty with universes here. -- If we allowed `J` to be a small category in `Prop`, we'd run into trouble -- because `yoneda.obj (F : (J ⥤ C)ᵒᵖ)` will be a functor into `Sort (max v 1)`, -- not into `Sort v`. -- So we don't allow this case; it's not particularly useful anyway. variables {J : Type v} [small_category J] variables {C : Sort u} [𝒞 : category.{v+1} C] include 𝒞 open category_theory open category_theory.category open category_theory.functor namespace category_theory namespace functor variables {J C} (F : J ⥤ C) /-- `F.cones` is the functor assigning to an object `X` the type of natural transformations from the constant functor with value `X` to `F`. An object representing this functor is a limit of `F`. -/ def cones : Cᵒᵖ ⥤ Type v := (const J).op ⋙ (yoneda.obj F) lemma cones_obj (X : Cᵒᵖ) : F.cones.obj X = ((const J).obj (unop X) ⟶ F) := rfl @[simp] lemma cones_map_app {X₁ X₂ : Cᵒᵖ} (f : X₁ ⟶ X₂) (t : F.cones.obj X₁) (j : J) : (F.cones.map f t).app j = f.unop ≫ t.app j := rfl /-- `F.cocones` is the functor assigning to an object `X` the type of natural transformations from `F` to the constant functor with value `X`. An object corepresenting this functor is a colimit of `F`. -/ def cocones : C ⥤ Type v := const J ⋙ coyoneda.obj (op F) lemma cocones_obj (X : C) : F.cocones.obj X = (F ⟹ (const J).obj X) := rfl @[simp] lemma cocones_map_app {X₁ X₂ : C} (f : X₁ ⟶ X₂) (t : F.cocones.obj X₁) (j : J) : (F.cocones.map f t).app j = t.app j ≫ f := rfl end functor section variables (J C) def cones : (J ⥤ C) ⥤ (Cᵒᵖ ⥤ Type v) := { obj := functor.cones, map := λ F G f, whisker_left (const J).op (yoneda.map f) } def cocones : (J ⥤ C)ᵒᵖ ⥤ (C ⥤ Type v) := { obj := λ F, functor.cocones (unop F), map := λ F G f, whisker_left (const J) (coyoneda.map f) } variables {J C} @[simp] lemma cones_obj (F : J ⥤ C) : (cones J C).obj F = F.cones := rfl @[simp] lemma cones_map {F G : J ⥤ C} {f : F ⟶ G} : (cones J C).map f = (whisker_left (const J).op (yoneda.map f)) := rfl @[simp] lemma cocones_obj (F : (J ⥤ C)ᵒᵖ) : (cocones J C).obj F = (unop F).cocones := rfl @[simp] lemma cocones_map {F G : (J ⥤ C)ᵒᵖ} {f : F ⟶ G} : (cocones J C).map f = (whisker_left (const J) (coyoneda.map f)) := rfl end namespace limits /-- A `c : cone F` is: * an object `c.X` and * a natural transformation `c.π : c.X ⟹ F` from the constant `c.X` functor to `F`. `cone F` is equivalent, in the obvious way, to `Σ X, F.cones.obj X`. -/ structure cone (F : J ⥤ C) := (X : C) (π : (const J).obj X ⟹ F) @[simp] lemma cone.w {F : J ⥤ C} (c : cone F) {j j' : J} (f : j ⟶ j') : c.π.app j ≫ F.map f = c.π.app j' := by convert ←(c.π.naturality f).symm; apply id_comp /-- A `c : cocone F` is * an object `c.X` and * a natural transformation `c.ι : F ⟹ c.X` from `F` to the constant `c.X` functor. `cocone F` is equivalent, in the obvious way, to `Σ X, F.cocones.obj X`. -/ structure cocone (F : J ⥤ C) := (X : C) (ι : F ⟹ (const J).obj X) @[simp] lemma cocone.w {F : J ⥤ C} (c : cocone F) {j j' : J} (f : j ⟶ j') : F.map f ≫ c.ι.app j' = c.ι.app j := by convert ←(c.ι.naturality f); apply comp_id variables {F : J ⥤ C} namespace cone @[simp] def extensions (c : cone F) : yoneda.obj c.X ⟶ F.cones := { app := λ X f, ((const J).map f) ≫ c.π } /-- A map to the vertex of a cone induces a cone by composition. -/ @[simp] def extend (c : cone F) {X : C} (f : X ⟶ c.X) : cone F := { X := X, π := c.extensions.app (op X) f } @[simp] lemma extend_π (c : cone F) {X : Cᵒᵖ} (f : unop X ⟶ c.X) : (extend c f).π = c.extensions.app X f := rfl def whisker {K : Type v} [small_category K] (E : K ⥤ J) (c : cone F) : cone (E ⋙ F) := { X := c.X, π := whisker_left E c.π } @[simp] lemma whisker_π_app (c : cone F) {K : Type v} [small_category K] (E : K ⥤ J) (k : K) : (c.whisker E).π.app k = (c.π).app (E.obj k) := rfl end cone namespace cocone @[simp] def extensions (c : cocone F) : coyoneda.obj (op c.X) ⟶ F.cocones := { app := λ X f, c.ι ≫ ((const J).map f) } /-- A map from the vertex of a cocone induces a cocone by composition. -/ @[simp] def extend (c : cocone F) {X : C} (f : c.X ⟶ X) : cocone F := { X := X, ι := c.extensions.app X f } @[simp] lemma extend_ι (c : cocone F) {X : C} (f : c.X ⟶ X) : (extend c f).ι = c.extensions.app X f := rfl def whisker {K : Type v} [small_category K] (E : K ⥤ J) (c : cocone F) : cocone (E ⋙ F) := { X := c.X, ι := whisker_left E c.ι } @[simp] lemma whisker_ι_app (c : cocone F) {K : Type v} [small_category K] (E : K ⥤ J) (k : K) : (c.whisker E).ι.app k = (c.ι).app (E.obj k) := rfl end cocone structure cone_morphism (A B : cone F) := (hom : A.X ⟶ B.X) (w' : ∀ j : J, hom ≫ B.π.app j = A.π.app j . obviously) restate_axiom cone_morphism.w' attribute [simp] cone_morphism.w @[extensionality] lemma cone_morphism.ext {A B : cone F} {f g : cone_morphism A B} (w : f.hom = g.hom) : f = g := by cases f; cases g; simpa using w instance cone.category : category.{v+1} (cone F) := { hom := λ A B, cone_morphism A B, comp := λ X Y Z f g, { hom := f.hom ≫ g.hom, w' := by intro j; rw [assoc, g.w, f.w] }, id := λ B, { hom := 𝟙 B.X } } namespace cones @[simp] lemma id.hom (c : cone F) : (𝟙 c : cone_morphism c c).hom = 𝟙 (c.X) := rfl @[simp] lemma comp.hom {c d e : cone F} (f : c ⟶ d) (g : d ⟶ e) : (f ≫ g).hom = f.hom ≫ g.hom := rfl /-- To give an isomorphism between cones, it suffices to give an isomorphism between their vertices which commutes with the cone maps. -/ @[extensionality] def ext {c c' : cone F} (φ : c.X ≅ c'.X) (w : ∀ j, c.π.app j = φ.hom ≫ c'.π.app j) : c ≅ c' := { hom := { hom := φ.hom }, inv := { hom := φ.inv, w' := λ j, φ.inv_comp_eq.mpr (w j) } } def postcompose {G : J ⥤ C} (α : F ⟶ G) : cone F ⥤ cone G := { obj := λ c, { X := c.X, π := c.π ⊟ α }, map := λ c₁ c₂ f, { hom := f.hom, w' := by intro; erw ← category.assoc; simp [-category.assoc] } } @[simp] lemma postcompose_obj_X {G : J ⥤ C} (α : F ⟶ G) (c : cone F) : ((postcompose α).obj c).X = c.X := rfl @[simp] lemma postcompose_obj_π {G : J ⥤ C} (α : F ⟶ G) (c : cone F) : ((postcompose α).obj c).π = c.π ⊟ α := rfl @[simp] lemma postcompose_map_hom {G : J ⥤ C} (α : F ⟶ G) {c₁ c₂ : cone F} (f : c₁ ⟶ c₂): ((postcompose α).map f).hom = f.hom := rfl def forget : cone F ⥤ C := { obj := λ t, t.X, map := λ s t f, f.hom } @[simp] lemma forget_obj {t : cone F} : forget.obj t = t.X := rfl @[simp] lemma forget_map {s t : cone F} {f : s ⟶ t} : forget.map f = f.hom := rfl section variables {D : Sort u'} [𝒟 : category.{v+1} D] include 𝒟 @[simp] def functoriality (G : C ⥤ D) : cone F ⥤ cone (F ⋙ G) := { obj := λ A, { X := G.obj A.X, π := { app := λ j, G.map (A.π.app j), naturality' := by intros; erw ←G.map_comp; tidy } }, map := λ X Y f, { hom := G.map f.hom, w' := by intros; rw [←functor.map_comp, f.w] } } end end cones structure cocone_morphism (A B : cocone F) := (hom : A.X ⟶ B.X) (w' : ∀ j : J, A.ι.app j ≫ hom = B.ι.app j . obviously) restate_axiom cocone_morphism.w' attribute [simp] cocone_morphism.w @[extensionality] lemma cocone_morphism.ext {A B : cocone F} {f g : cocone_morphism A B} (w : f.hom = g.hom) : f = g := by cases f; cases g; simpa using w instance cocone.category : category.{v+1} (cocone F) := { hom := λ A B, cocone_morphism A B, comp := λ _ _ _ f g, { hom := f.hom ≫ g.hom, w' := by intro j; rw [←assoc, f.w, g.w] }, id := λ B, { hom := 𝟙 B.X } } namespace cocones @[simp] lemma id.hom (c : cocone F) : (𝟙 c : cocone_morphism c c).hom = 𝟙 (c.X) := rfl @[simp] lemma comp.hom {c d e : cocone F} (f : c ⟶ d) (g : d ⟶ e) : (f ≫ g).hom = f.hom ≫ g.hom := rfl /-- To give an isomorphism between cocones, it suffices to give an isomorphism between their vertices which commutes with the cocone maps. -/ @[extensionality] def ext {c c' : cocone F} (φ : c.X ≅ c'.X) (w : ∀ j, c.ι.app j ≫ φ.hom = c'.ι.app j) : c ≅ c' := { hom := { hom := φ.hom }, inv := { hom := φ.inv, w' := λ j, φ.comp_inv_eq.mpr (w j).symm } } def precompose {G : J ⥤ C} (α : G ⟶ F) : cocone F ⥤ cocone G := { obj := λ c, { X := c.X, ι := α ⊟ c.ι }, map := λ c₁ c₂ f, { hom := f.hom } } @[simp] lemma precompose_obj_X {G : J ⥤ C} (α : G ⟶ F) (c : cocone F) : ((precompose α).obj c).X = c.X := rfl @[simp] lemma precompose_obj_ι {G : J ⥤ C} (α : G ⟶ F) (c : cocone F) : ((precompose α).obj c).ι = α ⊟ c.ι := rfl @[simp] lemma precompose_map_hom {G : J ⥤ C} (α : G ⟶ F) {c₁ c₂ : cocone F} (f : c₁ ⟶ c₂) : ((precompose α).map f).hom = f.hom := rfl def forget : cocone F ⥤ C := { obj := λ t, t.X, map := λ s t f, f.hom } @[simp] lemma forget_obj {t : cocone F} : forget.obj t = t.X := rfl @[simp] lemma forget_map {s t : cocone F} {f : s ⟶ t} : forget.map f = f.hom := rfl section variables {D : Sort u'} [𝒟 : category.{v+1} D] include 𝒟 @[simp] def functoriality (G : C ⥤ D) : cocone F ⥤ cocone (F ⋙ G) := { obj := λ A, { X := G.obj A.X, ι := { app := λ j, G.map (A.ι.app j), naturality' := by intros; erw ←G.map_comp; tidy } }, map := λ _ _ f, { hom := G.map f.hom, w' := by intros; rw [←functor.map_comp, cocone_morphism.w] } } end end cocones end limits namespace functor variables {D : Sort u'} [category.{v+1} D] variables {F : J ⥤ C} {G : J ⥤ C} (H : C ⥤ D) open category_theory.limits /-- The image of a cone in C under a functor G : C ⥤ D is a cone in D. -/ def map_cone (c : cone F) : cone (F ⋙ H) := (cones.functoriality H).obj c /-- The image of a cocone in C under a functor G : C ⥤ D is a cocone in D. -/ def map_cocone (c : cocone F) : cocone (F ⋙ H) := (cocones.functoriality H).obj c def map_cone_morphism {c c' : cone F} (f : cone_morphism c c') : cone_morphism (H.map_cone c) (H.map_cone c') := (cones.functoriality H).map f def map_cocone_morphism {c c' : cocone F} (f : cocone_morphism c c') : cocone_morphism (H.map_cocone c) (H.map_cocone c') := (cocones.functoriality H).map f @[simp] lemma map_cone_π (c : cone F) (j : J) : (map_cone H c).π.app j = H.map (c.π.app j) := rfl @[simp] lemma map_cocone_ι (c : cocone F) (j : J) : (map_cocone H c).ι.app j = H.map (c.ι.app j) := rfl end functor end category_theory
1339e657a13a47be4c3b5c65a35d1fd84072009a
c31182a012eec69da0a1f6c05f42b0f0717d212d
/src/thm95/col_exact_prep.lean
0e3af9cae80b0eb449d0a4c280481b61b1016734
[]
no_license
Ja1941/lean-liquid
fbec3ffc7fc67df1b5ca95b7ee225685ab9ffbdc
8e80ed0cbdf5145d6814e833a674eaf05a1495c1
refs/heads/master
1,689,437,983,362
1,628,362,719,000
1,628,362,719,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,140
lean
import pseudo_normed_group.FP import system_of_complexes.basic import prop819 import pseudo_normed_group.sum_hom noncomputable theory open_locale nnreal big_operators open category_theory opposite simplex_category local attribute [instance] type_pow universe variables u u₀ uₘ -- set_option pp.universes true namespace system_of_complexes variables (C : system_of_complexes) def norm_exact_complex (D : cochain_complex SemiNormedGroup ℕ) : Prop := ∀ (m : ℕ) (ε : ℝ≥0) (hε : 0 < ε) (x : D.X m) (hx : D.d _ (m+1) x = 0), ∃ y : D.X (m-1), D.d _ _ y = x ∧ ∥y∥₊ ≤ (1 + ε) * ∥x∥₊ lemma weak_exact_of_factor_exact (k : ℝ≥0) [fact (1 ≤ k)] (m : ℕ) (c₀ : ℝ≥0) (D : ℝ≥0 → cochain_complex SemiNormedGroup ℕ) (hD : ∀ c, c₀ ≤ c → norm_exact_complex (D c)) (f : Π c, C.obj (op $ k * c) ⟶ D c) (g : Π c, D c ⟶ C.obj (op c)) (hf : ∀ c i, ((f c).f i).norm_noninc) (hg : ∀ c i, ((g c).f i).norm_noninc) (hfg : ∀ c, c₀ ≤ c → f c ≫ g c = C.map (hom_of_le (fact.out _ : c ≤ k * c)).op) : C.is_weak_bounded_exact k 1 m c₀ := begin intros c hc i hi x ε' hε', let dx := C.d _ (i+1) x, let fx := (f _).f _ x, let fdx := (f c).f _ dx, let dfx := (D _).d _ (i+1) fx, have fdx_dfx : fdx = dfx, { simp only [fdx, dfx, fx, ← comp_apply], congr' 1, exact ((f _).comm _ _).symm }, have hfdx : (D _).d _ (i+2) fdx = 0, { calc (D _).d _ (i+2) fdx = (D _).d _ (i+2) ((D _).d _ (i+1) (fx)) : congr_arg _ fdx_dfx ... = ((D _).d _ (i+1) ≫ (D _).d _ (i+2)) (fx) : rfl ... = 0 : by { rw (D c).d_comp_d _ _ _, refl } }, let ε : ℝ≥0 := ⟨ε', hε'.le⟩, have hε : 0 < ε := hε', let δ : ℝ≥0 := ε / (∥dx∥₊ + 1), have hδ : 0 < δ, { rw [← nnreal.coe_lt_coe], exact div_pos hε (lt_of_le_of_lt (nnreal.coe_nonneg _) (lt_add_one _)), }, obtain ⟨(x' : (D c).X i), (hdx' : (D c).d i (i+1) x' = fdx), hnorm_x'⟩ := (hD _ hc.1) _ δ hδ _ hfdx, let gx' := (g _).f _ x', have hdfxx' : (D _).d _ (i+1) (fx - x') = 0, { rw [normed_group_hom.map_sub, hdx', fdx_dfx], exact sub_self _ }, obtain ⟨y, hdy, -⟩ := (hD _ hc.1) _ δ hδ _ hdfxx', let gy := (g _).f _ y, let dgy := C.d _ i gy, let gdy := (g _).f _ ((D _).d _ i y), have gdy_dgy : gdy = dgy, { simp only [gdy, dgy, gy, ← comp_apply], congr' 1, exact ((g _).comm _ _).symm }, refine ⟨i-1, i+1, rfl, rfl, gy, _⟩, simp only [nnreal.coe_one, one_mul], have hxdgy : res x - C.d _ _ gy = gx', { calc res x - dgy = (g _).f _ ((f _).f _ x) - gdy : _ ... = gx' : by rw [← normed_group_hom.map_sub, hdy, sub_sub_cancel], rw [gdy_dgy, ← comp_apply, ← homological_complex.comp_f, hfg _ hc.1], refl }, rw hxdgy, change (∥gx'∥₊ : ℝ) ≤ ∥dx∥₊ + ε, simp only [← nnreal.coe_add, nnreal.coe_le_coe], calc ∥gx'∥₊ ≤ ∥x'∥₊ : hg _ _ _ ... ≤ (1 + δ) * ∥fdx∥₊ : hnorm_x' ... ≤ (1 + δ) * ∥dx∥₊ : mul_le_mul' le_rfl (hf _ _ _) ... ≤ ∥dx∥₊ + δ * ∥dx∥₊ : by rw [add_mul, one_mul] ... ≤ ∥dx∥₊ + ε * 1 : add_le_add le_rfl _ ... ≤ ∥dx∥₊ + ε : by rw [mul_one], dsimp only [δ], rw [div_eq_mul_inv, mul_assoc], refine mul_le_mul' le_rfl _, rw [nnreal.mul_le_iff_le_inv, inv_inv', mul_one], { exact (lt_add_one _).le }, { refine inv_ne_zero (lt_of_le_of_lt _ (lt_add_one _)).ne', exact zero_le' } end end system_of_complexes namespace thm95 variables (r' : ℝ) (V : SemiNormedGroup.{u}) (M : Type u) {M₁ M₂ : Type u} (N : ℕ) (d : ℝ≥0) variables [profinitely_filtered_pseudo_normed_group M] [pseudo_normed_group.splittable M N d] variables [profinitely_filtered_pseudo_normed_group M₁] variables [profinitely_filtered_pseudo_normed_group M₂] variables (f : profinitely_filtered_pseudo_normed_group_hom M₁ M₂) (hf : f.strict) section open Profinite pseudo_normed_group profinitely_filtered_pseudo_normed_group @[simps left right] def FLC_complex_arrow (c : ℝ≥0) : arrow Profinite := @arrow.mk _ _ (filtration_obj M₁ c) (filtration_obj M₂ c) $ { to_fun := pseudo_normed_group.level f hf c, continuous_to_fun := f.continuous _ (λ _, rfl) } end section open profinitely_filtered_pseudo_normed_group @[simps obj map] def FLC_complex : system_of_complexes := { obj := λ c, (FLC_functor V).obj (op $ FLC_complex_arrow f hf c.unop), map := λ c₁ c₂ h, (FLC_functor V).map $ quiver.hom.op $ @arrow.hom_mk _ _ (FLC_complex_arrow f hf c₂.unop) (FLC_complex_arrow f hf c₁.unop) (⟨_, (@embedding_cast_le _ _ _ _ ⟨le_of_hom h.unop⟩).continuous⟩) (⟨_, (@embedding_cast_le _ _ _ _ ⟨le_of_hom h.unop⟩).continuous⟩) (by { ext, refl }), map_id' := λ c, begin convert (FLC_functor V).map_id _, simp only [unop_id, ←op_id, quiver.hom.op_inj.eq_iff, nat_trans.id_app], ext; refl, end, map_comp' := λ c₁ c₂ c₃ h1 h2, begin convert (FLC_functor V).map_comp _ _, simp only [← op_comp, quiver.hom.op_inj.eq_iff, nat_trans.comp_app], ext; refl, end, } . end namespace FLC_complex open pseudo_normed_group variables (c₁ c₂ : ℝ≥0) [fact (c₁ ≤ c₂)] def aux_space (c₁ c₂ : ℝ≥0) [fact (c₁ ≤ c₂)] := { p : filtration M₂ c₁ × filtration M₁ c₂ // cast_le p.1 = level f hf c₂ p.2 } namespace aux_space open profinitely_filtered_pseudo_normed_group instance : topological_space (aux_space f hf c₁ c₂) := by { delta aux_space, apply_instance } instance : t2_space (aux_space f hf c₁ c₂) := by { delta aux_space, apply_instance } instance : totally_disconnected_space (aux_space f hf c₁ c₂) := subtype.totally_disconnected_space instance : compact_space (aux_space f hf c₁ c₂) := { compact_univ := begin rw embedding_subtype_coe.is_compact_iff_is_compact_image, simp only [set.image_univ, subtype.range_coe_subtype], refine is_closed.is_compact _, refine is_closed_eq ((embedding_cast_le _ _).continuous.comp continuous_fst) ((f.continuous _ _).comp continuous_snd), intro, refl end } end aux_space def AuxSpace : Profinite := Profinite.of (aux_space f hf c₁ c₂) namespace AuxSpace open profinitely_filtered_pseudo_normed_group @[simps] def ι : filtration_obj M₁ c₁ ⟶ AuxSpace f hf c₁ c₂ := { to_fun := λ x, ⟨⟨level f hf c₁ x, Filtration.cast_le M₁ c₁ c₂ x⟩, rfl⟩, continuous_to_fun := begin apply continuous_induced_rng, refine continuous.prod_mk (f.continuous _ (λ _, rfl)) (Filtration.cast_le M₁ c₁ c₂).continuous, end } @[simps] def fst : AuxSpace f hf c₁ c₂ ⟶ filtration_obj M₂ c₁ := { to_fun := _, continuous_to_fun := continuous_fst.comp continuous_subtype_coe } @[simps] def snd : AuxSpace f hf c₁ c₂ ⟶ filtration_obj M₁ c₂ := { to_fun := _, continuous_to_fun := continuous_snd.comp continuous_subtype_coe } @[simps left right] def fstₐ : arrow Profinite := arrow.mk (fst f hf c₁ c₂) include d lemma fst_surjective [fact (0 < N)] (h : c₁ / N + d ≤ c₂ * N⁻¹) : function.surjective (fst _ (sum_hom_strict M N) c₁ c₂) := begin intros y, dsimp at y, obtain ⟨x, hx1, hx2⟩ := exists_sum N d _ _ y.2, simp only [fst_to_fun, function.comp_app], refine ⟨⟨⟨y, ⟨x, _⟩⟩, _⟩, rfl⟩, { erw rescale.mem_filtration, refine filtration_mono h hx2 }, { simp only [pseudo_normed_group.level, sum_hom_apply, subtype.coe_mk, ← hx1], refl }, end end AuxSpace open AuxSpace profinitely_filtered_pseudo_normed_group @[simps] def sum_hom₀ [fact (0 < N)] (c : ℝ≥0) : filtration_obj (rescale N (M^N)) c ⟶ filtration_obj M c := ⟨pseudo_normed_group.level (sum_hom M N) (sum_hom_strict M N) c, (sum_hom M N).continuous _ (λ _, rfl)⟩ @[simps left right hom] def sum_homₐ [fact (0 < N)] (c : ℝ≥0) : arrow Profinite := arrow.mk (sum_hom₀ M N c) def sum_homₐ_fstₐ [fact (0 < N)] : sum_homₐ M N c₁ ⟶ fstₐ _ (sum_hom_strict M N) c₁ c₂ := { left := AuxSpace.ι _ _ _ _, right := 𝟙 _, } def fstₐ_sum_homₐ [fact (0 < N)] : fstₐ _ (sum_hom_strict M N) c₁ c₂ ⟶ sum_homₐ M N c₂ := { left := snd _ _ _ _, right := Filtration.cast_le _ _ _, w' := by { ext1 ⟨x, h⟩, exact h.symm } } include d lemma weak_bounded_exact (k : ℝ≥0) [hk : fact (1 ≤ k)] (m : ℕ) (c₀ : ℝ≥0) [fact (0 < N)] (hdkc₀N : d ≤ (k - 1) * c₀ / N) : (FLC_complex V _ (sum_hom_strict M N)).is_weak_bounded_exact k 1 m c₀ := begin let D := λ c, (FLC_functor V).obj (op $ fstₐ _ (sum_hom_strict M N) c (k * c)), let f := λ c, (FLC_functor V).map (fstₐ_sum_homₐ M N c (k * c)).op, let g := λ c, (FLC_functor V).map (sum_homₐ_fstₐ M N c (k * c)).op, refine system_of_complexes.weak_exact_of_factor_exact _ k m c₀ D _ f g _ _ _, { intros c hc, suffices : function.surjective ((unop (op (fstₐ (sum_hom M N) _ c (k * c)))).hom), { intros i ε hε x hx, cases i, { simp only [nat.one_ne_zero, homological_complex.shape, complex_shape.up_rel, exists_and_distrib_left, not_false_iff, normed_group_hom.zero_apply], refine ⟨(prop819_degree_zero _ this _ x hx).symm, 0, _⟩, simp only [nnnorm_zero, zero_le'] }, exact prop819 _ this _ ε hε x hx }, refine fst_surjective M N d c (k * c) _, calc c / N + d ≤ c / N + (k - 1) * c₀ / N : add_le_add le_rfl hdkc₀N ... ≤ c / N + (k - 1) * c / N : add_le_add le_rfl _ ... ≤ 1 * c / N + (k - 1) * c / N : by rw one_mul ... = k * c / N : _, { simp only [div_eq_mul_inv], refine mul_le_mul' (mul_le_mul' le_rfl hc) le_rfl, }, { simp only [div_eq_mul_inv, mul_assoc], rw ← add_mul, congr, rw [← nnreal.eq_iff, nnreal.coe_add, nnreal.coe_sub hk.1, add_sub_cancel'_right], } }, { intros c i, exact FLC_functor_map_norm_noninc _ _ _ }, { intros c i, exact FLC_functor_map_norm_noninc _ _ _ }, { intros c hc, dsimp only [f, g, FLC_complex_map], rw [← category_theory.functor.map_comp, ← op_comp], refl } end end FLC_complex end thm95
7766ec74b7ca77efbb6e850f232d844123872525
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/tactic/rewrite_all/congr.lean
996dceb715ed78dfb7d77ab5920a7bf8c71e7db5
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
4,816
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Keeley Hoek -/ import tactic.rewrite_all.basic import tactic.core namespace tactic -- Sometimes `mk_congr_arg` fails, when the function is 'superficially dependent'. -- This hack `dsimp`s the function before building the `congr_arg` expression. -- Unfortunately it creates some dummy hypotheses that I can't work out how to dispose of cleanly. meta def mk_congr_arg_using_dsimp' (G W : expr) (u : list name) : tactic expr := do s ← simp_lemmas.mk_default, t ← infer_type G, t' ← s.dsimplify u t {fail_if_unchanged := ff}, definev `_mk_congr_arg_aux t' G, to_expr ```(congr_arg _mk_congr_arg_aux %%W) namespace rewrite_all.congr open rewrite_all meta inductive expr_lens | app_fun : expr_lens → expr → expr_lens | app_arg : expr_lens → expr → expr_lens | entire : expr_lens open expr_lens meta def expr_lens.to_sides : expr_lens → list side | entire := [] | (app_fun l _) := l.to_sides.concat side.R | (app_arg l _) := l.to_sides.concat side.L meta def expr_lens.replace : expr_lens → expr → expr | entire e := e | (app_fun l f) x := expr_lens.replace l (expr.app f x) | (app_arg l x) f := expr_lens.replace l (expr.app f x) private meta def trace_congr_error (f : expr) (x_eq : expr) : tactic unit := do pp_f ← pp f, pp_f_t ← (infer_type f >>= λ t, pp t), pp_x_eq ← pp x_eq, pp_x_eq_t ← (infer_type x_eq >>= λ t, pp t), trace format!"expr_lens.congr failed on \n{pp_f} : {pp_f_t}\n{pp_x_eq} : {pp_x_eq_t}" meta def expr_lens.congr : expr_lens → expr → tactic expr | entire e_eq := pure e_eq | (app_fun l f) x_eq := do fx_eq ← try_core $ mk_congr_arg f x_eq <|> mk_congr_arg_using_dsimp' f x_eq [`has_coe_to_fun.F], match fx_eq with | (some fx_eq) := expr_lens.congr l fx_eq | none := trace_congr_error f x_eq >> failed end | (app_arg l x) f_eq := mk_congr_fun f_eq x >>= expr_lens.congr l meta def expr_lens.to_tactic_string : expr_lens → tactic string | entire := return "(entire)" | (app_fun l f) := do pp ← pp f, rest ← l.to_tactic_string, return sformat!"(fun \"{pp}\" {rest})" | (app_arg l x) := do pp ← pp x, rest ← l.to_tactic_string, return sformat!"(arg \"{pp}\" {rest})" private meta def app_map_aux {α} (F : expr_lens → expr → tactic (list α)) : expr_lens → expr → tactic (list α) | l (expr.app f x) := list.join <$> monad.sequence [ F l (expr.app f x), app_map_aux (expr_lens.app_arg l x) f, app_map_aux (expr_lens.app_fun l f) x ] <|> pure [] | l e := F l e <|> pure [] meta def app_map {α} (F : expr_lens → expr → tactic (list α)) : expr → tactic (list α) | e := app_map_aux F expr_lens.entire e meta def rewrite_without_new_mvars (r : expr) (e : expr) (cfg : rewrite_all.cfg := {}) : tactic (expr × expr) := lock_tactic_state $ -- This makes sure that we forget everything in between rewrites; -- otherwise we don't correctly find everything! do (new_t, prf, metas) ← rewrite_core r e { cfg.to_rewrite_cfg with md := semireducible }, try_apply_opt_auto_param cfg.to_apply_cfg metas, set_goals metas, all_goals (try cfg.discharger), done, prf ← instantiate_mvars prf, -- This is necessary because of the locked tactic state. return (new_t, prf) -- This is a bit of a hack: we manually inspect the proof that `rewrite_core` -- produced, and deduce from that whether or not the entire expression was rewritten. meta def rewrite_is_of_entire : expr → bool | `(@eq.rec _ %%term %%C %%p _ _) := match C with | `(λ p, _ = p) := tt | _ := ff end | _ := ff meta def rewrite_at_lens (cfg : rewrite_all.cfg) (r : expr × bool) (l : expr_lens) (e : expr) : tactic (list tracked_rewrite) := do (v, pr) ← rewrite_without_new_mvars r.1 e {cfg with symm := r.2}, -- Now we determine whether the rewrite transforms the entire expression or not: if ¬(rewrite_is_of_entire pr) then return [] else do let w := l.replace v, qr ← l.congr pr, s ← try_core (cfg.simplifier w), (w, qr) ← match s with | none := pure (w, qr) | some (w', qr') := do qr ← mk_eq_trans qr qr', return (w', qr) end, return [⟨w, pure qr, l.to_sides⟩] meta def rewrite_all (e : expr) (r : expr × bool) (cfg : rewrite_all.cfg := {}) : tactic (list tracked_rewrite) := app_map (rewrite_at_lens cfg r) e meta def rewrite_all_lazy (e : expr) (r : expr × bool) (cfg : rewrite_all.cfg := {}) : mllist tactic tracked_rewrite := mllist.squash $ mllist.of_list <$> rewrite_all e r cfg end rewrite_all.congr end tactic
b8423fc48384b1f57f7b4e1eb8f6f2e2086b5091
b00eb947a9c4141624aa8919e94ce6dcd249ed70
/tests/lean/interactive/hover.lean
c02210f4599fa54f90ad75002eb8255b530017cf
[ "Apache-2.0" ]
permissive
gebner/lean4-old
a4129a041af2d4d12afb3a8d4deedabde727719b
ee51cdfaf63ee313c914d83264f91f414a0e3b6e
refs/heads/master
1,683,628,606,745
1,622,651,300,000
1,622,654,405,000
142,608,821
1
0
null
null
null
null
UTF-8
Lean
false
false
245
lean
example : True := by apply True.intro --^ textDocument/hover example : True := by simp [True.intro] --^ textDocument/hover example (n : Nat) : True := by match n with | Nat.zero => _ --^ textDocument/hover | n + 1 => _
18fe27d4892e38998691c41d8cc2c86b7c4fbe98
137c667471a40116a7afd7261f030b30180468c2
/src/linear_algebra/direct_sum_module.lean
dc0e040156d1a5125c5bb9a18383c31dcc08d9e8
[ "Apache-2.0" ]
permissive
bragadeesh153/mathlib
46bf814cfb1eecb34b5d1549b9117dc60f657792
b577bb2cd1f96eb47031878256856020b76f73cd
refs/heads/master
1,687,435,188,334
1,626,384,207,000
1,626,384,207,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,172
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau Direct sum of modules over commutative rings, indexed by a discrete type. -/ import algebra.direct_sum import linear_algebra.dfinsupp /-! # Direct sum of modules over commutative rings, indexed by a discrete type. This file provides constructors for finite direct sums of modules. It provides a construction of the direct sum using the universal property and proves its uniqueness. ## Implementation notes All of this file assumes that * `R` is a commutative ring, * `ι` is a discrete type, * `S` is a finite set in `ι`, * `M` is a family of `R` modules indexed over `ι`. -/ universes u v w u₁ variables (R : Type u) [semiring R] variables (ι : Type v) [dec_ι : decidable_eq ι] (M : ι → Type w) variables [Π i, add_comm_monoid (M i)] [Π i, module R (M i)] include R namespace direct_sum open_locale direct_sum variables {R ι M} instance : module R (⨁ i, M i) := dfinsupp.module instance {S : Type*} [semiring S] [Π i, module S (M i)] [Π i, smul_comm_class R S (M i)] : smul_comm_class R S (⨁ i, M i) := dfinsupp.smul_comm_class instance {S : Type*} [semiring S] [has_scalar R S] [Π i, module S (M i)] [Π i, is_scalar_tower R S (M i)] : is_scalar_tower R S (⨁ i, M i) := dfinsupp.is_scalar_tower lemma smul_apply (b : R) (v : ⨁ i, M i) (i : ι) : (b • v) i = b • (v i) := dfinsupp.smul_apply _ _ _ include dec_ι variables R ι M /-- Create the direct sum given a family `M` of `R` modules indexed over `ι`. -/ def lmk : Π s : finset ι, (Π i : (↑s : set ι), M i.val) →ₗ[R] (⨁ i, M i) := dfinsupp.lmk /-- Inclusion of each component into the direct sum. -/ def lof : Π i : ι, M i →ₗ[R] (⨁ i, M i) := dfinsupp.lsingle variables {ι M} lemma single_eq_lof (i : ι) (b : M i) : dfinsupp.single i b = lof R ι M i b := rfl /-- Scalar multiplication commutes with direct sums. -/ theorem mk_smul (s : finset ι) (c : R) (x) : mk M s (c • x) = c • mk M s x := (lmk R ι M s).map_smul c x /-- Scalar multiplication commutes with the inclusion of each component into the direct sum. -/ theorem of_smul (i : ι) (c : R) (x) : of M i (c • x) = c • of M i x := (lof R ι M i).map_smul c x variables {R} lemma support_smul [Π (i : ι) (x : M i), decidable (x ≠ 0)] (c : R) (v : ⨁ i, M i) : (c • v).support ⊆ v.support := dfinsupp.support_smul _ _ variables {N : Type u₁} [add_comm_monoid N] [module R N] variables (φ : Π i, M i →ₗ[R] N) variables (R ι N φ) /-- The linear map constructed using the universal property of the coproduct. -/ def to_module : (⨁ i, M i) →ₗ[R] N := dfinsupp.lsum ℕ φ variables {ι N φ} /-- The map constructed using the universal property gives back the original maps when restricted to each component. -/ @[simp] lemma to_module_lof (i) (x : M i) : to_module R ι N φ (lof R ι M i x) = φ i x := to_add_monoid_of (λ i, (φ i).to_add_monoid_hom) i x variables (ψ : (⨁ i, M i) →ₗ[R] N) /-- Every linear map from a direct sum agrees with the one obtained by applying the universal property to each of its components. -/ theorem to_module.unique (f : ⨁ i, M i) : ψ f = to_module R ι N (λ i, ψ.comp $ lof R ι M i) f := to_add_monoid.unique ψ.to_add_monoid_hom f variables {ψ} {ψ' : (⨁ i, M i) →ₗ[R] N} theorem to_module.ext (H : ∀ i, ψ.comp (lof R ι M i) = ψ'.comp (lof R ι M i)) (f : ⨁ i, M i) : ψ f = ψ' f := by rw dfinsupp.lhom_ext' H /-- The inclusion of a subset of the direct summands into a larger subset of the direct summands, as a linear map. -/ def lset_to_set (S T : set ι) (H : S ⊆ T) : (⨁ (i : S), M i) →ₗ (⨁ (i : T), M i) := to_module R _ _ $ λ i, lof R T (λ (i : subtype T), M i) ⟨i, H i.prop⟩ omit dec_ι /-- The natural linear equivalence between `⨁ _ : ι, M` and `M` when `unique ι`. -/ protected def lid (M : Type v) (ι : Type* := punit) [add_comm_monoid M] [module R M] [unique ι] : (⨁ (_ : ι), M) ≃ₗ M := { .. direct_sum.id M ι, .. to_module R ι M (λ i, linear_map.id) } variables (ι M) /-- The projection map onto one component, as a linear map. -/ def component (i : ι) : (⨁ i, M i) →ₗ[R] M i := dfinsupp.lapply i variables {ι M} lemma apply_eq_component (f : ⨁ i, M i) (i : ι) : f i = component R ι M i f := rfl @[ext] lemma ext {f g : ⨁ i, M i} (h : ∀ i, component R ι M i f = component R ι M i g) : f = g := dfinsupp.ext h lemma ext_iff {f g : ⨁ i, M i} : f = g ↔ ∀ i, component R ι M i f = component R ι M i g := ⟨λ h _, by rw h, ext R⟩ include dec_ι @[simp] lemma lof_apply (i : ι) (b : M i) : ((lof R ι M i) b) i = b := dfinsupp.single_eq_same @[simp] lemma component.lof_self (i : ι) (b : M i) : component R ι M i ((lof R ι M i) b) = b := lof_apply R i b lemma component.of (i j : ι) (b : M j) : component R ι M i ((lof R ι M j) b) = if h : j = i then eq.rec_on h b else 0 := dfinsupp.single_apply /-- The `direct_sum` formed by a collection of `submodule`s of `M` is said to be internal if the canonical map `(⨁ i, A i) →ₗ[R] M` is bijective. -/ def submodule_is_internal {R M : Type*} [semiring R] [add_comm_monoid M] [module R M] (A : ι → submodule R M) : Prop := function.bijective (to_module R ι M (λ i, (A i).subtype)) lemma submodule_is_internal.to_add_submonoid {R M : Type*} [semiring R] [add_comm_monoid M] [module R M] (A : ι → submodule R M) : submodule_is_internal A ↔ add_submonoid_is_internal (λ i, (A i).to_add_submonoid) := iff.rfl lemma submodule_is_internal.to_add_subgroup {R M : Type*} [ring R] [add_comm_group M] [module R M] (A : ι → submodule R M) : submodule_is_internal A ↔ add_subgroup_is_internal (λ i, (A i).to_add_subgroup) := iff.rfl lemma submodule_is_internal.supr_eq_top {R M : Type*} [semiring R] [add_comm_monoid M] [module R M] (A : ι → submodule R M) (h : submodule_is_internal A) : supr A = ⊤ := begin rw [submodule.supr_eq_range_dfinsupp_lsum, linear_map.range_eq_top], exact function.bijective.surjective h, end end direct_sum
e57fece2dac0f50d261b4f87c6a51af1783a9fb2
618003631150032a5676f229d13a079ac875ff77
/src/category_theory/limits/limits.lean
9bcf401fcb92739f5a590cf22e3c03a2a539f577
[ "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
42,800
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Mario Carneiro, Scott Morrison, Floris van Doorn -/ import category_theory.limits.cones import category_theory.adjunction.basic open category_theory category_theory.category category_theory.functor opposite namespace category_theory.limits universes v u u' u'' w -- declare the `v`'s first; see `category_theory.category` for an explanation -- See the notes at the top of cones.lean, explaining why we can't allow `J : Prop` here. variables {J K : Type v} [small_category J] [small_category K] variables {C : Type u} [category.{v} C] variables {F : J ⥤ C} /-- A cone `t` on `F` is a limit cone if each cone on `F` admits a unique cone morphism to `t`. -/ @[nolint has_inhabited_instance] structure is_limit (t : cone F) := (lift : Π (s : cone F), s.X ⟶ t.X) (fac' : ∀ (s : cone F) (j : J), lift s ≫ t.π.app j = s.π.app j . obviously) (uniq' : ∀ (s : cone F) (m : s.X ⟶ t.X) (w : ∀ j : J, m ≫ t.π.app j = s.π.app j), m = lift s . obviously) restate_axiom is_limit.fac' attribute [simp, reassoc] is_limit.fac restate_axiom is_limit.uniq' namespace is_limit instance subsingleton {t : cone F} : subsingleton (is_limit t) := ⟨by intros P Q; cases P; cases Q; congr; ext; solve_by_elim⟩ /- Repackaging the definition in terms of cone morphisms. -/ /-- The universal morphism from any other cone to a limit cone. -/ def lift_cone_morphism {t : cone F} (h : is_limit t) (s : cone F) : s ⟶ t := { hom := h.lift s } lemma uniq_cone_morphism {s t : cone F} (h : is_limit t) {f f' : s ⟶ t} : f = f' := have ∀ {g : s ⟶ t}, g = h.lift_cone_morphism s, by intro g; ext; exact h.uniq _ _ g.w, this.trans this.symm /-- Alternative constructor for `is_limit`, providing a morphism of cones rather than a morphism between the cone points and separately the factorisation condition. -/ def mk_cone_morphism {t : cone F} (lift : Π (s : cone F), s ⟶ t) (uniq' : ∀ (s : cone F) (m : s ⟶ t), m = lift s) : is_limit t := { lift := λ s, (lift s).hom, uniq' := λ s m w, have cone_morphism.mk m w = lift s, by apply uniq', congr_arg cone_morphism.hom this } /-- Limit cones on `F` are unique up to isomorphism. -/ def unique_up_to_iso {s t : cone F} (P : is_limit s) (Q : is_limit t) : s ≅ t := { hom := Q.lift_cone_morphism s, inv := P.lift_cone_morphism t, hom_inv_id' := P.uniq_cone_morphism, inv_hom_id' := Q.uniq_cone_morphism } /-- Limits of `F` are unique up to isomorphism. -/ -- We may later want to prove the coherence of these isomorphisms. def cone_point_unique_up_to_iso {s t : cone F} (P : is_limit s) (Q : is_limit t) : s.X ≅ t.X := (cones.forget F).map_iso (unique_up_to_iso P Q) /-- Transport evidence that a cone is a limit cone across an isomorphism of cones. -/ def of_iso_limit {r t : cone F} (P : is_limit r) (i : r ≅ t) : is_limit t := is_limit.mk_cone_morphism (λ s, P.lift_cone_morphism s ≫ i.hom) (λ s m, by rw ←i.comp_inv_eq; apply P.uniq_cone_morphism) variables {t : cone F} lemma hom_lift (h : is_limit t) {W : C} (m : W ⟶ t.X) : m = h.lift { X := W, π := { app := λ b, m ≫ t.π.app b } } := h.uniq { X := W, π := { app := λ b, m ≫ t.π.app b } } m (λ b, rfl) /-- Two morphisms into a limit are equal if their compositions with each cone morphism are equal. -/ lemma hom_ext (h : is_limit t) {W : C} {f f' : W ⟶ t.X} (w : ∀ j, f ≫ t.π.app j = f' ≫ t.π.app j) : f = f' := by rw [h.hom_lift f, h.hom_lift f']; congr; exact funext w /-- The universal property of a limit cone: a map `W ⟶ X` is the same as a cone on `F` with vertex `W`. -/ def hom_iso (h : is_limit t) (W : C) : (W ⟶ t.X) ≅ ((const J).obj W ⟶ F) := { hom := λ f, (t.extend f).π, inv := λ π, h.lift { X := W, π := π }, hom_inv_id' := by ext f; apply h.hom_ext; intro j; simp; dsimp; refl } @[simp] lemma hom_iso_hom (h : is_limit t) {W : C} (f : W ⟶ t.X) : (is_limit.hom_iso h W).hom f = (t.extend f).π := rfl /-- The limit of `F` represents the functor taking `W` to the set of cones on `F` with vertex `W`. -/ def nat_iso (h : is_limit t) : yoneda.obj t.X ≅ F.cones := nat_iso.of_components (λ W, is_limit.hom_iso h (unop W)) (by tidy). /-- Another, more explicit, formulation of the universal property of a limit cone. See also `hom_iso`. -/ def hom_iso' (h : is_limit t) (W : C) : ((W ⟶ t.X) : Type v) ≅ { p : Π j, W ⟶ F.obj j // ∀ {j j'} (f : j ⟶ j'), p j ≫ F.map f = p j' } := h.hom_iso W ≪≫ { hom := λ π, ⟨λ j, π.app j, λ j j' f, by convert ←(π.naturality f).symm; apply id_comp⟩, inv := λ p, { app := λ j, p.1 j, naturality' := λ j j' f, begin dsimp, rw [id_comp], exact (p.2 f).symm end } } /-- If G : C → D is a faithful functor which sends t to a limit cone, then it suffices to check that the induced maps for the image of t can be lifted to maps of C. -/ def of_faithful {t : cone F} {D : Type u'} [category.{v} D] (G : C ⥤ D) [faithful G] (ht : is_limit (G.map_cone t)) (lift : Π (s : cone F), s.X ⟶ t.X) (h : ∀ s, G.map (lift s) = ht.lift (G.map_cone s)) : is_limit t := { lift := lift, fac' := λ s j, by apply G.injectivity; rw [G.map_comp, h]; apply ht.fac, uniq' := λ s m w, begin apply G.injectivity, rw h, refine ht.uniq (G.map_cone s) _ (λ j, _), convert ←congr_arg (λ f, G.map f) (w j), apply G.map_comp end } /-- If `F` and `G` are naturally isomorphic, then `F.map_cone c` being a limit implies `G.map_cone c` is also a limit. -/ def map_cone_equiv {D : Type u'} [category.{v} D] {K : J ⥤ C} {F G : C ⥤ D} (h : F ≅ G) {c : cone K} (t : is_limit (F.map_cone c)) : is_limit (G.map_cone c) := { lift := λ s, t.lift ((cones.postcompose (iso_whisker_left K h).inv).obj s) ≫ h.hom.app c.X, fac' := λ s j, begin slice_lhs 2 3 {erw ← h.hom.naturality (c.π.app j)}, slice_lhs 1 2 {erw t.fac ((cones.postcompose (iso_whisker_left K h).inv).obj s) j}, dsimp, slice_lhs 2 3 {rw nat_iso.inv_hom_id_app}, rw category.comp_id, end, uniq' := λ s m J, begin rw ← cancel_mono (h.inv.app c.X), apply t.hom_ext, intro j, dsimp, slice_lhs 2 3 {erw ← h.inv.naturality (c.π.app j)}, slice_lhs 1 2 {erw J j}, conv_rhs {congr, rw [category.assoc, nat_iso.hom_inv_id_app, comp_id]}, apply (t.fac ((cones.postcompose (iso_whisker_left K h).inv).obj s) j).symm end } /-- A cone is a limit cone exactly if there is a unique cone morphism from any other cone. -/ def iso_unique_cone_morphism {t : cone F} : is_limit t ≅ Π s, unique (s ⟶ t) := { hom := λ h s, { default := h.lift_cone_morphism s, uniq := λ _, h.uniq_cone_morphism }, inv := λ h, { lift := λ s, (h s).default.hom, uniq' := λ s f w, congr_arg cone_morphism.hom ((h s).uniq ⟨f, w⟩) } } -- TODO: this should actually hold for an adjunction between cone F and cone G, not just for -- equivalences /-- Given two functors which have equivalent categories of cones, we can transport a limiting cone across the equivalence. -/ def of_cone_equiv {D : Type u'} [category.{v} D] {G : K ⥤ D} (h : cone F ≌ cone G) {c : cone G} (t : is_limit c) : is_limit (h.inverse.obj c) := mk_cone_morphism (λ s, h.to_adjunction.hom_equiv s c (t.lift_cone_morphism _)) (λ s m, (adjunction.eq_hom_equiv_apply _ _ _).2 t.uniq_cone_morphism ) namespace of_nat_iso variables {X : C} (h : yoneda.obj X ≅ F.cones) /-- If `F.cones` is represented by `X`, each morphism `f : Y ⟶ X` gives a cone with cone point `Y`. -/ def cone_of_hom {Y : C} (f : Y ⟶ X) : cone F := { X := Y, π := h.hom.app (op Y) f } /-- If `F.cones` is represented by `X`, each cone `s` gives a morphism `s.X ⟶ X`. -/ def hom_of_cone (s : cone F) : s.X ⟶ X := h.inv.app (op s.X) s.π @[simp] lemma cone_of_hom_of_cone (s : cone F) : cone_of_hom h (hom_of_cone h s) = s := begin dsimp [cone_of_hom, hom_of_cone], cases s, congr, dsimp, exact congr_fun (congr_fun (congr_arg nat_trans.app h.inv_hom_id) (op s_X)) s_π, end @[simp] lemma hom_of_cone_of_hom {Y : C} (f : Y ⟶ X) : hom_of_cone h (cone_of_hom h f) = f := congr_fun (congr_fun (congr_arg nat_trans.app h.hom_inv_id) (op Y)) f /-- If `F.cones` is represented by `X`, the cone corresponding to the identity morphism on `X` will be a limit cone. -/ def limit_cone : cone F := cone_of_hom h (𝟙 X) /-- If `F.cones` is represented by `X`, the cone corresponding to a morphism `f : Y ⟶ X` is the limit cone extended by `f`. -/ lemma cone_of_hom_fac {Y : C} (f : Y ⟶ X) : cone_of_hom h f = (limit_cone h).extend f := begin dsimp [cone_of_hom, limit_cone, cone.extend], congr, ext j, have t := congr_fun (h.hom.naturality f.op) (𝟙 X), dsimp at t, simp only [comp_id] at t, rw congr_fun (congr_arg nat_trans.app t) j, refl, end /-- If `F.cones` is represented by `X`, any cone is the extension of the limit cone by the corresponding morphism. -/ lemma cone_fac (s : cone F) : (limit_cone h).extend (hom_of_cone h s) = s := begin rw ←cone_of_hom_of_cone h s, conv_lhs { simp only [hom_of_cone_of_hom] }, apply (cone_of_hom_fac _ _).symm, end end of_nat_iso section open of_nat_iso /-- If `F.cones` is representable, then the cone corresponding to the identity morphism on the representing object is a limit cone. -/ def of_nat_iso {X : C} (h : yoneda.obj X ≅ F.cones) : is_limit (limit_cone h) := { lift := λ s, hom_of_cone h s, fac' := λ s j, begin have h := cone_fac h s, cases s, injection h with h₁ h₂, simp only [heq_iff_eq] at h₂, conv_rhs { rw ← h₂ }, refl, end, uniq' := λ s m w, begin rw ←hom_of_cone_of_hom h m, congr, rw cone_of_hom_fac, dsimp, cases s, congr, ext j, exact w j, end } end end is_limit /-- A cocone `t` on `F` is a colimit cocone if each cocone on `F` admits a unique cocone morphism from `t`. -/ @[nolint has_inhabited_instance] structure is_colimit (t : cocone F) := (desc : Π (s : cocone F), t.X ⟶ s.X) (fac' : ∀ (s : cocone F) (j : J), t.ι.app j ≫ desc s = s.ι.app j . obviously) (uniq' : ∀ (s : cocone F) (m : t.X ⟶ s.X) (w : ∀ j : J, t.ι.app j ≫ m = s.ι.app j), m = desc s . obviously) restate_axiom is_colimit.fac' attribute [simp] is_colimit.fac restate_axiom is_colimit.uniq' namespace is_colimit instance subsingleton {t : cocone F} : subsingleton (is_colimit t) := ⟨by intros P Q; cases P; cases Q; congr; ext; solve_by_elim⟩ /- Repackaging the definition in terms of cone morphisms. -/ /-- The universal morphism from a colimit cocone to any other cone. -/ def desc_cocone_morphism {t : cocone F} (h : is_colimit t) (s : cocone F) : t ⟶ s := { hom := h.desc s } lemma uniq_cocone_morphism {s t : cocone F} (h : is_colimit t) {f f' : t ⟶ s} : f = f' := have ∀ {g : t ⟶ s}, g = h.desc_cocone_morphism s, by intro g; ext; exact h.uniq _ _ g.w, this.trans this.symm /-- Alternative constructor for `is_colimit`, providing a morphism of cocones rather than a morphism between the cocone points and separately the factorisation condition. -/ def mk_cocone_morphism {t : cocone F} (desc : Π (s : cocone F), t ⟶ s) (uniq' : ∀ (s : cocone F) (m : t ⟶ s), m = desc s) : is_colimit t := { desc := λ s, (desc s).hom, uniq' := λ s m w, have cocone_morphism.mk m w = desc s, by apply uniq', congr_arg cocone_morphism.hom this } /-- Limit cones on `F` are unique up to isomorphism. -/ def unique_up_to_iso {s t : cocone F} (P : is_colimit s) (Q : is_colimit t) : s ≅ t := { hom := P.desc_cocone_morphism t, inv := Q.desc_cocone_morphism s, hom_inv_id' := P.uniq_cocone_morphism, inv_hom_id' := Q.uniq_cocone_morphism } /-- Colimits of `F` are unique up to isomorphism. -/ -- We may later want to prove the coherence of these isomorphisms. def cocone_point_unique_up_to_iso {s t : cocone F} (P : is_colimit s) (Q : is_colimit t) : s.X ≅ t.X := (cocones.forget F).map_iso (unique_up_to_iso P Q) /-- Transport evidence that a cocone is a colimit cocone across an isomorphism of cocones. -/ def of_iso_colimit {r t : cocone F} (P : is_colimit r) (i : r ≅ t) : is_colimit t := is_colimit.mk_cocone_morphism (λ s, i.inv ≫ P.desc_cocone_morphism s) (λ s m, by rw i.eq_inv_comp; apply P.uniq_cocone_morphism) variables {t : cocone F} lemma hom_desc (h : is_colimit t) {W : C} (m : t.X ⟶ W) : m = h.desc { X := W, ι := { app := λ b, t.ι.app b ≫ m, naturality' := by intros; erw [←assoc, t.ι.naturality, comp_id, comp_id] } } := h.uniq { X := W, ι := { app := λ b, t.ι.app b ≫ m, naturality' := _ } } m (λ b, rfl) /-- Two morphisms out of a colimit are equal if their compositions with each cocone morphism are equal. -/ lemma hom_ext (h : is_colimit t) {W : C} {f f' : t.X ⟶ W} (w : ∀ j, t.ι.app j ≫ f = t.ι.app j ≫ f') : f = f' := by rw [h.hom_desc f, h.hom_desc f']; congr; exact funext w /-- The universal property of a colimit cocone: a map `X ⟶ W` is the same as a cocone on `F` with vertex `W`. -/ def hom_iso (h : is_colimit t) (W : C) : (t.X ⟶ W) ≅ (F ⟶ (const J).obj W) := { hom := λ f, (t.extend f).ι, inv := λ ι, h.desc { X := W, ι := ι }, hom_inv_id' := by ext f; apply h.hom_ext; intro j; simp; dsimp; refl } @[simp] lemma hom_iso_hom (h : is_colimit t) {W : C} (f : t.X ⟶ W) : (is_colimit.hom_iso h W).hom f = (t.extend f).ι := rfl /-- The colimit of `F` represents the functor taking `W` to the set of cocones on `F` with vertex `W`. -/ def nat_iso (h : is_colimit t) : coyoneda.obj (op t.X) ≅ F.cocones := nat_iso.of_components (is_colimit.hom_iso h) (by intros; ext; dsimp; rw ←assoc; refl) /-- Another, more explicit, formulation of the universal property of a colimit cocone. See also `hom_iso`. -/ def hom_iso' (h : is_colimit t) (W : C) : ((t.X ⟶ W) : Type v) ≅ { p : Π j, F.obj j ⟶ W // ∀ {j j' : J} (f : j ⟶ j'), F.map f ≫ p j' = p j } := h.hom_iso W ≪≫ { hom := λ ι, ⟨λ j, ι.app j, λ j j' f, by convert ←(ι.naturality f); apply comp_id⟩, inv := λ p, { app := λ j, p.1 j, naturality' := λ j j' f, begin dsimp, rw [comp_id], exact (p.2 f) end } } /-- If G : C → D is a faithful functor which sends t to a colimit cocone, then it suffices to check that the induced maps for the image of t can be lifted to maps of C. -/ def of_faithful {t : cocone F} {D : Type u'} [category.{v} D] (G : C ⥤ D) [faithful G] (ht : is_colimit (G.map_cocone t)) (desc : Π (s : cocone F), t.X ⟶ s.X) (h : ∀ s, G.map (desc s) = ht.desc (G.map_cocone s)) : is_colimit t := { desc := desc, fac' := λ s j, by apply G.injectivity; rw [G.map_comp, h]; apply ht.fac, uniq' := λ s m w, begin apply G.injectivity, rw h, refine ht.uniq (G.map_cocone s) _ (λ j, _), convert ←congr_arg (λ f, G.map f) (w j), apply G.map_comp end } /-- A cocone is a colimit cocone exactly if there is a unique cocone morphism from any other cocone. -/ def iso_unique_cocone_morphism {t : cocone F} : is_colimit t ≅ Π s, unique (t ⟶ s) := { hom := λ h s, { default := h.desc_cocone_morphism s, uniq := λ _, h.uniq_cocone_morphism }, inv := λ h, { desc := λ s, (h s).default.hom, uniq' := λ s f w, congr_arg cocone_morphism.hom ((h s).uniq ⟨f, w⟩) } } namespace of_nat_iso variables {X : C} (h : coyoneda.obj (op X) ≅ F.cocones) /-- If `F.cocones` is corepresented by `X`, each morphism `f : X ⟶ Y` gives a cocone with cone point `Y`. -/ def cocone_of_hom {Y : C} (f : X ⟶ Y) : cocone F := { X := Y, ι := h.hom.app Y f } /-- If `F.cocones` is corepresented by `X`, each cocone `s` gives a morphism `X ⟶ s.X`. -/ def hom_of_cocone (s : cocone F) : X ⟶ s.X := h.inv.app s.X s.ι @[simp] lemma cocone_of_hom_of_cocone (s : cocone F) : cocone_of_hom h (hom_of_cocone h s) = s := begin dsimp [cocone_of_hom, hom_of_cocone], cases s, congr, dsimp, exact congr_fun (congr_fun (congr_arg nat_trans.app h.inv_hom_id) s_X) s_ι, end @[simp] lemma hom_of_cocone_of_hom {Y : C} (f : X ⟶ Y) : hom_of_cocone h (cocone_of_hom h f) = f := congr_fun (congr_fun (congr_arg nat_trans.app h.hom_inv_id) Y) f /-- If `F.cocones` is corepresented by `X`, the cocone corresponding to the identity morphism on `X` will be a colimit cocone. -/ def colimit_cocone : cocone F := cocone_of_hom h (𝟙 X) /-- If `F.cocones` is corepresented by `X`, the cocone corresponding to a morphism `f : Y ⟶ X` is the colimit cocone extended by `f`. -/ lemma cocone_of_hom_fac {Y : C} (f : X ⟶ Y) : cocone_of_hom h f = (colimit_cocone h).extend f := begin dsimp [cocone_of_hom, colimit_cocone, cocone.extend], congr, ext j, have t := congr_fun (h.hom.naturality f) (𝟙 X), dsimp at t, simp only [id_comp] at t, rw congr_fun (congr_arg nat_trans.app t) j, refl, end /-- If `F.cocones` is corepresented by `X`, any cocone is the extension of the colimit cocone by the corresponding morphism. -/ lemma cocone_fac (s : cocone F) : (colimit_cocone h).extend (hom_of_cocone h s) = s := begin rw ←cocone_of_hom_of_cocone h s, conv_lhs { simp only [hom_of_cocone_of_hom] }, apply (cocone_of_hom_fac _ _).symm, end end of_nat_iso section open of_nat_iso /-- If `F.cocones` is corepresentable, then the cocone corresponding to the identity morphism on the representing object is a colimit cocone. -/ def of_nat_iso {X : C} (h : coyoneda.obj (op X) ≅ F.cocones) : is_colimit (colimit_cocone h) := { desc := λ s, hom_of_cocone h s, fac' := λ s j, begin have h := cocone_fac h s, cases s, injection h with h₁ h₂, simp only [heq_iff_eq] at h₂, conv_rhs { rw ← h₂ }, refl, end, uniq' := λ s m w, begin rw ←hom_of_cocone_of_hom h m, congr, rw cocone_of_hom_fac, dsimp, cases s, congr, ext j, exact w j, end } end end is_colimit section limit /-- `has_limit F` represents a particular chosen limit of the diagram `F`. -/ class has_limit (F : J ⥤ C) := (cone : cone F) (is_limit : is_limit cone) variables (J C) /-- `C` has limits of shape `J` if we have chosen a particular limit of every functor `F : J ⥤ C`. -/ class has_limits_of_shape := (has_limit : Π F : J ⥤ C, has_limit F) /-- `C` has all (small) limits if it has limits of every shape. -/ class has_limits := (has_limits_of_shape : Π (J : Type v) [𝒥 : small_category J], has_limits_of_shape J C) variables {J C} @[priority 100] -- see Note [lower instance priority] instance has_limit_of_has_limits_of_shape {J : Type v} [small_category J] [H : has_limits_of_shape J C] (F : J ⥤ C) : has_limit F := has_limits_of_shape.has_limit F @[priority 100] -- see Note [lower instance priority] instance has_limits_of_shape_of_has_limits {J : Type v} [small_category J] [H : has_limits.{v} C] : has_limits_of_shape J C := has_limits.has_limits_of_shape J /- Interface to the `has_limit` class. -/ /-- The chosen limit cone of a functor. -/ def limit.cone (F : J ⥤ C) [has_limit F] : cone F := has_limit.cone /-- The chosen limit object of a functor. -/ def limit (F : J ⥤ C) [has_limit F] := (limit.cone F).X /-- The projection from the chosen limit object to a value of the functor. -/ def limit.π (F : J ⥤ C) [has_limit F] (j : J) : limit F ⟶ F.obj j := (limit.cone F).π.app j @[simp] lemma limit.cone_π {F : J ⥤ C} [has_limit F] (j : J) : (limit.cone F).π.app j = limit.π _ j := rfl @[simp] lemma limit.w (F : J ⥤ C) [has_limit F] {j j' : J} (f : j ⟶ j') : limit.π F j ≫ F.map f = limit.π F j' := (limit.cone F).w f /-- Evidence that the chosen cone is a limit cone. -/ def limit.is_limit (F : J ⥤ C) [has_limit F] : is_limit (limit.cone F) := has_limit.is_limit.{v} /-- The morphism from the cone point of any other cone to the chosen limit object. -/ def limit.lift (F : J ⥤ C) [has_limit F] (c : cone F) : c.X ⟶ limit F := (limit.is_limit F).lift c @[simp] lemma limit.is_limit_lift {F : J ⥤ C} [has_limit F] (c : cone F) : (limit.is_limit F).lift c = limit.lift F c := rfl @[simp, reassoc] lemma limit.lift_π {F : J ⥤ C} [has_limit F] (c : cone F) (j : J) : limit.lift F c ≫ limit.π F j = c.π.app j := is_limit.fac _ c j /-- The cone morphism from any cone to the chosen limit cone. -/ def limit.cone_morphism {F : J ⥤ C} [has_limit F] (c : cone F) : c ⟶ (limit.cone F) := (limit.is_limit F).lift_cone_morphism c @[simp] lemma limit.cone_morphism_hom {F : J ⥤ C} [has_limit F] (c : cone F) : (limit.cone_morphism c).hom = limit.lift F c := rfl lemma limit.cone_morphism_π {F : J ⥤ C} [has_limit F] (c : cone F) (j : J) : (limit.cone_morphism c).hom ≫ limit.π F j = c.π.app j := by simp @[ext] lemma limit.hom_ext {F : J ⥤ C} [has_limit F] {X : C} {f f' : X ⟶ limit F} (w : ∀ j, f ≫ limit.π F j = f' ≫ limit.π F j) : f = f' := (limit.is_limit F).hom_ext w /-- The isomorphism (in `Type`) between morphisms from a specified object `W` to the limit object, and cones with cone point `W`. -/ def limit.hom_iso (F : J ⥤ C) [has_limit F] (W : C) : (W ⟶ limit F) ≅ (F.cones.obj (op W)) := (limit.is_limit F).hom_iso W @[simp] lemma limit.hom_iso_hom (F : J ⥤ C) [has_limit F] {W : C} (f : W ⟶ limit F) : (limit.hom_iso F W).hom f = (const J).map f ≫ (limit.cone F).π := (limit.is_limit F).hom_iso_hom f /-- The isomorphism (in `Type`) between morphisms from a specified object `W` to the limit object, and an explicit componentwise description of cones with cone point `W`. -/ def limit.hom_iso' (F : J ⥤ C) [has_limit F] (W : C) : ((W ⟶ limit F) : Type v) ≅ { p : Π j, W ⟶ F.obj j // ∀ {j j' : J} (f : j ⟶ j'), p j ≫ F.map f = p j' } := (limit.is_limit F).hom_iso' W lemma limit.lift_extend {F : J ⥤ C} [has_limit F] (c : cone F) {X : C} (f : X ⟶ c.X) : limit.lift F (c.extend f) = f ≫ limit.lift F c := by obviously /-- If we've chosen a limit for a functor `F`, we can transport that choice across a natural isomorphism. -/ def has_limit_of_iso {F G : J ⥤ C} [has_limit F] (α : F ≅ G) : has_limit G := { cone := (cones.postcompose α.hom).obj (limit.cone F), is_limit := { lift := λ s, limit.lift F ((cones.postcompose α.inv).obj s), fac' := λ s j, begin rw [cones.postcompose_obj_π, nat_trans.comp_app, limit.cone_π, ←category.assoc, limit.lift_π], simp end, uniq' := λ s m w, begin apply limit.hom_ext, intro j, rw [limit.lift_π, cones.postcompose_obj_π, nat_trans.comp_app, ←nat_iso.app_inv, iso.eq_comp_inv], simpa using w j end } } /-- If a functor `G` has the same collection of cones as a functor `F` which has a limit, then `G` also has a limit. -/ -- See the construction of limits from products and equalizers -- for an example usage. def has_limit.of_cones_iso {J K : Type v} [small_category J] [small_category K] (F : J ⥤ C) (G : K ⥤ C) (h : F.cones ≅ G.cones) [has_limit F] : has_limit G := ⟨_, is_limit.of_nat_iso ((is_limit.nat_iso (limit.is_limit F)) ≪≫ h)⟩ section pre variables (F) [has_limit F] (E : K ⥤ J) [has_limit (E ⋙ F)] /-- The canonical morphism from the chosen limit of `F` to the chosen limit of `E ⋙ F`. -/ def limit.pre : limit F ⟶ limit (E ⋙ F) := limit.lift (E ⋙ F) { X := limit F, π := { app := λ k, limit.π F (E.obj k) } } @[simp] lemma limit.pre_π (k : K) : limit.pre F E ≫ limit.π (E ⋙ F) k = limit.π F (E.obj k) := by erw is_limit.fac @[simp] lemma limit.lift_pre (c : cone F) : limit.lift F c ≫ limit.pre F E = limit.lift (E ⋙ F) (c.whisker E) := by ext; simp variables {L : Type v} [small_category L] variables (D : L ⥤ K) [has_limit (D ⋙ E ⋙ F)] @[simp] lemma limit.pre_pre : limit.pre F E ≫ limit.pre (E ⋙ F) D = limit.pre F (D ⋙ E) := by ext j; erw [assoc, limit.pre_π, limit.pre_π, limit.pre_π]; refl end pre section post variables {D : Type u'} [category.{v} D] variables (F) [has_limit F] (G : C ⥤ D) [has_limit (F ⋙ G)] /-- The canonical morphism from `G` applied to the chosen limit of `F` to the chosen limit of `F ⋙ G`. -/ def limit.post : G.obj (limit F) ⟶ limit (F ⋙ G) := limit.lift (F ⋙ G) { X := G.obj (limit F), π := { app := λ j, G.map (limit.π F j), naturality' := by intros j j' f; erw [←G.map_comp, limits.cone.w, id_comp]; refl } } @[simp] lemma limit.post_π (j : J) : limit.post F G ≫ limit.π (F ⋙ G) j = G.map (limit.π F j) := by erw is_limit.fac @[simp] lemma limit.lift_post (c : cone F) : G.map (limit.lift F c) ≫ limit.post F G = limit.lift (F ⋙ G) (G.map_cone c) := by ext; rw [assoc, limit.post_π, ←G.map_comp, limit.lift_π, limit.lift_π]; refl @[simp] lemma limit.post_post {E : Type u''} [category.{v} E] (H : D ⥤ E) [has_limit ((F ⋙ G) ⋙ H)] : /- H G (limit F) ⟶ H (limit (F ⋙ G)) ⟶ limit ((F ⋙ G) ⋙ H) equals -/ /- H G (limit F) ⟶ limit (F ⋙ (G ⋙ H)) -/ H.map (limit.post F G) ≫ limit.post (F ⋙ G) H = limit.post F (G ⋙ H) := by ext; erw [assoc, limit.post_π, ←H.map_comp, limit.post_π, limit.post_π]; refl end post lemma limit.pre_post {D : Type u'} [category.{v} D] (E : K ⥤ J) (F : J ⥤ C) (G : C ⥤ D) [has_limit F] [has_limit (E ⋙ F)] [has_limit (F ⋙ G)] [has_limit ((E ⋙ F) ⋙ G)] : /- G (limit F) ⟶ G (limit (E ⋙ F)) ⟶ limit ((E ⋙ F) ⋙ G) vs -/ /- G (limit F) ⟶ limit F ⋙ G ⟶ limit (E ⋙ (F ⋙ G)) or -/ G.map (limit.pre F E) ≫ limit.post (E ⋙ F) G = limit.post F G ≫ limit.pre (F ⋙ G) E := by ext; erw [assoc, limit.post_π, ←G.map_comp, limit.pre_π, assoc, limit.pre_π, limit.post_π]; refl open category_theory.equivalence instance has_limit_equivalence_comp (e : K ≌ J) [has_limit F] : has_limit (e.functor ⋙ F) := { cone := cone.whisker e.functor (limit.cone F), is_limit := let e' := cones.postcompose (e.inv_fun_id_assoc F).hom in { lift := λ s, limit.lift F (e'.obj (cone.whisker e.inverse s)), fac' := λ s j, begin dsimp, rw [limit.lift_π], dsimp [e'], erw [inv_fun_id_assoc_hom_app, counit_functor, ←s.π.naturality, id_comp] end, uniq' := λ s m w, begin apply limit.hom_ext, intro j, erw [limit.lift_π, ←limit.w F (e.counit_iso.hom.app j)], slice_lhs 1 2 { erw [w (e.inverse.obj j)] }, simp end } } local attribute [elab_simple] inv_fun_id_assoc -- not entirely sure why this is needed /-- If a `E ⋙ F` has a chosen limit, and `E` is an equivalence, we can construct a chosen limit of `F`. -/ def has_limit_of_equivalence_comp (e : K ≌ J) [has_limit (e.functor ⋙ F)] : has_limit F := begin haveI : has_limit (e.inverse ⋙ e.functor ⋙ F) := limits.has_limit_equivalence_comp e.symm, apply has_limit_of_iso (e.inv_fun_id_assoc F), end -- `has_limit_comp_equivalence` and `has_limit_of_comp_equivalence` -- are proved in `category_theory/adjunction/limits.lean`. section lim_functor variables [has_limits_of_shape J C] /-- `limit F` is functorial in `F`, when `C` has all limits of shape `J`. -/ def lim : (J ⥤ C) ⥤ C := { obj := λ F, limit F, map := λ F G α, limit.lift G { X := limit F, π := { app := λ j, limit.π F j ≫ α.app j, naturality' := λ j j' f, by erw [id_comp, assoc, ←α.naturality, ←assoc, limit.w] } }, map_comp' := λ F G H α β, by ext; erw [assoc, is_limit.fac, is_limit.fac, ←assoc, is_limit.fac, assoc]; refl } variables {F} {G : J ⥤ C} (α : F ⟶ G) @[simp, reassoc] lemma limit.map_π (j : J) : lim.map α ≫ limit.π G j = limit.π F j ≫ α.app j := by apply is_limit.fac @[simp] lemma limit.lift_map (c : cone F) : limit.lift F c ≫ lim.map α = limit.lift G ((cones.postcompose α).obj c) := by ext; rw [assoc, limit.map_π, ←assoc, limit.lift_π, limit.lift_π]; refl lemma limit.map_pre [has_limits_of_shape K C] (E : K ⥤ J) : lim.map α ≫ limit.pre G E = limit.pre F E ≫ lim.map (whisker_left E α) := by ext; rw [assoc, limit.pre_π, limit.map_π, assoc, limit.map_π, ←assoc, limit.pre_π]; refl lemma limit.map_pre' [has_limits_of_shape.{v} K C] (F : J ⥤ C) {E₁ E₂ : K ⥤ J} (α : E₁ ⟶ E₂) : limit.pre F E₂ = limit.pre F E₁ ≫ lim.map (whisker_right α F) := by ext1; simp [← category.assoc] lemma limit.id_pre (F : J ⥤ C) : limit.pre F (𝟭 _) = lim.map (functor.left_unitor F).inv := by tidy lemma limit.map_post {D : Type u'} [category.{v} D] [has_limits_of_shape J D] (H : C ⥤ D) : /- H (limit F) ⟶ H (limit G) ⟶ limit (G ⋙ H) vs H (limit F) ⟶ limit (F ⋙ H) ⟶ limit (G ⋙ H) -/ H.map (lim.map α) ≫ limit.post G H = limit.post F H ≫ lim.map (whisker_right α H) := begin ext, rw [assoc, limit.post_π, ←H.map_comp, limit.map_π, H.map_comp], rw [assoc, limit.map_π, ←assoc, limit.post_π], refl end /-- The isomorphism between morphisms from `W` to the cone point of the limit cone for `F` and cones over `F` with cone point `W` is natural in `F`. -/ def lim_yoneda : lim ⋙ yoneda ≅ category_theory.cones J C := nat_iso.of_components (λ F, nat_iso.of_components (λ W, limit.hom_iso F (unop W)) (by tidy)) (by tidy) end lim_functor /-- We can transport chosen limits of shape `J` along an equivalence `J ≌ J'`. -/ def has_limits_of_shape_of_equivalence {J' : Type v} [small_category J'] (e : J ≌ J') [has_limits_of_shape J C] : has_limits_of_shape J' C := by { constructor, intro F, apply has_limit_of_equivalence_comp e, apply_instance } end limit section colimit /-- `has_colimit F` represents a particular chosen colimit of the diagram `F`. -/ class has_colimit (F : J ⥤ C) := (cocone : cocone F) (is_colimit : is_colimit cocone) variables (J C) /-- `C` has colimits of shape `J` if we have chosen a particular colimit of every functor `F : J ⥤ C`. -/ class has_colimits_of_shape := (has_colimit : Π F : J ⥤ C, has_colimit F) /-- `C` has all (small) colimits if it has colimits of every shape. -/ class has_colimits := (has_colimits_of_shape : Π (J : Type v) [𝒥 : small_category J], has_colimits_of_shape J C) variables {J C} @[priority 100] -- see Note [lower instance priority] instance has_colimit_of_has_colimits_of_shape {J : Type v} [small_category J] [H : has_colimits_of_shape J C] (F : J ⥤ C) : has_colimit F := has_colimits_of_shape.has_colimit F @[priority 100] -- see Note [lower instance priority] instance has_colimits_of_shape_of_has_colimits {J : Type v} [small_category J] [H : has_colimits.{v} C] : has_colimits_of_shape J C := has_colimits.has_colimits_of_shape J /- Interface to the `has_colimit` class. -/ /-- The chosen colimit cocone of a functor. -/ def colimit.cocone (F : J ⥤ C) [has_colimit F] : cocone F := has_colimit.cocone /-- The chosen colimit object of a functor. -/ def colimit (F : J ⥤ C) [has_colimit F] := (colimit.cocone F).X /-- The coprojection from a value of the functor to the chosen colimit object. -/ def colimit.ι (F : J ⥤ C) [has_colimit F] (j : J) : F.obj j ⟶ colimit F := (colimit.cocone F).ι.app j @[simp] lemma colimit.cocone_ι {F : J ⥤ C} [has_colimit F] (j : J) : (colimit.cocone F).ι.app j = colimit.ι _ j := rfl @[simp] lemma colimit.w (F : J ⥤ C) [has_colimit F] {j j' : J} (f : j ⟶ j') : F.map f ≫ colimit.ι F j' = colimit.ι F j := (colimit.cocone F).w f /-- Evidence that the chosen cocone is a colimit cocone. -/ def colimit.is_colimit (F : J ⥤ C) [has_colimit F] : is_colimit (colimit.cocone F) := has_colimit.is_colimit.{v} /-- The morphism from the chosen colimit object to the cone point of any other cocone. -/ def colimit.desc (F : J ⥤ C) [has_colimit F] (c : cocone F) : colimit F ⟶ c.X := (colimit.is_colimit F).desc c @[simp] lemma colimit.is_colimit_desc {F : J ⥤ C} [has_colimit F] (c : cocone F) : (colimit.is_colimit F).desc c = colimit.desc F c := rfl /-- We have lots of lemmas describing how to simplify `colimit.ι F j ≫ _`, and combined with `colimit.ext` we rely on these lemmas for many calculations. However, since `category.assoc` is a `@[simp]` lemma, often expressions are right associated, and it's hard to apply these lemmas about `colimit.ι`. We thus use `reassoc` to define additional `@[simp]` lemmas, with an arbitrary extra morphism. (see `tactic/reassoc_axiom.lean`) -/ @[simp, reassoc] lemma colimit.ι_desc {F : J ⥤ C} [has_colimit F] (c : cocone F) (j : J) : colimit.ι F j ≫ colimit.desc F c = c.ι.app j := is_colimit.fac _ c j /-- The cocone morphism from the chosen colimit cocone to any cocone. -/ def colimit.cocone_morphism {F : J ⥤ C} [has_colimit F] (c : cocone F) : (colimit.cocone F) ⟶ c := (colimit.is_colimit F).desc_cocone_morphism c @[simp] lemma colimit.cocone_morphism_hom {F : J ⥤ C} [has_colimit F] (c : cocone F) : (colimit.cocone_morphism c).hom = colimit.desc F c := rfl lemma colimit.ι_cocone_morphism {F : J ⥤ C} [has_colimit F] (c : cocone F) (j : J) : colimit.ι F j ≫ (colimit.cocone_morphism c).hom = c.ι.app j := by simp @[ext] lemma colimit.hom_ext {F : J ⥤ C} [has_colimit F] {X : C} {f f' : colimit F ⟶ X} (w : ∀ j, colimit.ι F j ≫ f = colimit.ι F j ≫ f') : f = f' := (colimit.is_colimit F).hom_ext w /-- The isomorphism (in `Type`) between morphisms from the colimit object to a specified object `W`, and cocones with cone point `W`. -/ def colimit.hom_iso (F : J ⥤ C) [has_colimit F] (W : C) : (colimit F ⟶ W) ≅ (F.cocones.obj W) := (colimit.is_colimit F).hom_iso W @[simp] lemma colimit.hom_iso_hom (F : J ⥤ C) [has_colimit F] {W : C} (f : colimit F ⟶ W) : (colimit.hom_iso F W).hom f = (colimit.cocone F).ι ≫ (const J).map f := (colimit.is_colimit F).hom_iso_hom f /-- The isomorphism (in `Type`) between morphisms from the colimit object to a specified object `W`, and an explicit componentwise description of cocones with cone point `W`. -/ def colimit.hom_iso' (F : J ⥤ C) [has_colimit F] (W : C) : ((colimit F ⟶ W) : Type v) ≅ { p : Π j, F.obj j ⟶ W // ∀ {j j'} (f : j ⟶ j'), F.map f ≫ p j' = p j } := (colimit.is_colimit F).hom_iso' W lemma colimit.desc_extend (F : J ⥤ C) [has_colimit F] (c : cocone F) {X : C} (f : c.X ⟶ X) : colimit.desc F (c.extend f) = colimit.desc F c ≫ f := begin ext1, rw [←category.assoc], simp end /-- If we've chosen a colimit for a functor `F`, we can transport that choice across a natural isomorphism. -/ -- This has the isomorphism pointing in the opposite direction than in `has_limit_of_iso`. -- This is intentional; it seems to help with elaboration. def has_colimit_of_iso {F G : J ⥤ C} [has_colimit F] (α : G ≅ F) : has_colimit G := { cocone := (cocones.precompose α.hom).obj (colimit.cocone F), is_colimit := { desc := λ s, colimit.desc F ((cocones.precompose α.inv).obj s), fac' := λ s j, begin rw [cocones.precompose_obj_ι, nat_trans.comp_app, colimit.cocone_ι], rw [category.assoc, colimit.ι_desc, ←nat_iso.app_hom, ←iso.eq_inv_comp], refl end, uniq' := λ s m w, begin apply colimit.hom_ext, intro j, rw [colimit.ι_desc, cocones.precompose_obj_ι, nat_trans.comp_app, ←nat_iso.app_inv, iso.eq_inv_comp], simpa using w j end } } /-- If a functor `G` has the same collection of cocones as a functor `F` which has a colimit, then `G` also has a colimit. -/ def has_colimit.of_cocones_iso {J K : Type v} [small_category J] [small_category K] (F : J ⥤ C) (G : K ⥤ C) (h : F.cocones ≅ G.cocones) [has_colimit F] : has_colimit G := ⟨_, is_colimit.of_nat_iso ((is_colimit.nat_iso (colimit.is_colimit F)) ≪≫ h)⟩ section pre variables (F) [has_colimit F] (E : K ⥤ J) [has_colimit (E ⋙ F)] /-- The canonical morphism from the chosen colimit of `E ⋙ F` to the chosen colimit of `F`. -/ def colimit.pre : colimit (E ⋙ F) ⟶ colimit F := colimit.desc (E ⋙ F) { X := colimit F, ι := { app := λ k, colimit.ι F (E.obj k) } } @[simp, reassoc] lemma colimit.ι_pre (k : K) : colimit.ι (E ⋙ F) k ≫ colimit.pre F E = colimit.ι F (E.obj k) := by erw is_colimit.fac @[simp] lemma colimit.pre_desc (c : cocone F) : colimit.pre F E ≫ colimit.desc F c = colimit.desc (E ⋙ F) (c.whisker E) := by ext; rw [←assoc, colimit.ι_pre]; simp variables {L : Type v} [small_category L] variables (D : L ⥤ K) [has_colimit (D ⋙ E ⋙ F)] @[simp] lemma colimit.pre_pre : colimit.pre (E ⋙ F) D ≫ colimit.pre F E = colimit.pre F (D ⋙ E) := begin ext j, rw [←assoc, colimit.ι_pre, colimit.ι_pre], letI : has_colimit ((D ⋙ E) ⋙ F) := show has_colimit (D ⋙ E ⋙ F), by apply_instance, exact (colimit.ι_pre F (D ⋙ E) j).symm end end pre section post variables {D : Type u'} [category.{v} D] variables (F) [has_colimit F] (G : C ⥤ D) [has_colimit (F ⋙ G)] /-- The canonical morphism from `G` applied to the chosen colimit of `F ⋙ G` to `G` applied to the chosen colimit of `F`. -/ def colimit.post : colimit (F ⋙ G) ⟶ G.obj (colimit F) := colimit.desc (F ⋙ G) { X := G.obj (colimit F), ι := { app := λ j, G.map (colimit.ι F j), naturality' := by intros j j' f; erw [←G.map_comp, limits.cocone.w, comp_id]; refl } } @[simp, reassoc] lemma colimit.ι_post (j : J) : colimit.ι (F ⋙ G) j ≫ colimit.post F G = G.map (colimit.ι F j) := by erw is_colimit.fac @[simp] lemma colimit.post_desc (c : cocone F) : colimit.post F G ≫ G.map (colimit.desc F c) = colimit.desc (F ⋙ G) (G.map_cocone c) := by ext; rw [←assoc, colimit.ι_post, ←G.map_comp, colimit.ι_desc, colimit.ι_desc]; refl @[simp] lemma colimit.post_post {E : Type u''} [category.{v} E] (H : D ⥤ E) [has_colimit ((F ⋙ G) ⋙ H)] : /- H G (colimit F) ⟶ H (colimit (F ⋙ G)) ⟶ colimit ((F ⋙ G) ⋙ H) equals -/ /- H G (colimit F) ⟶ colimit (F ⋙ (G ⋙ H)) -/ colimit.post (F ⋙ G) H ≫ H.map (colimit.post F G) = colimit.post F (G ⋙ H) := begin ext, rw [←assoc, colimit.ι_post, ←H.map_comp, colimit.ι_post], exact (colimit.ι_post F (G ⋙ H) j).symm end end post lemma colimit.pre_post {D : Type u'} [category.{v} D] (E : K ⥤ J) (F : J ⥤ C) (G : C ⥤ D) [has_colimit F] [has_colimit (E ⋙ F)] [has_colimit (F ⋙ G)] [has_colimit ((E ⋙ F) ⋙ G)] : /- G (colimit F) ⟶ G (colimit (E ⋙ F)) ⟶ colimit ((E ⋙ F) ⋙ G) vs -/ /- G (colimit F) ⟶ colimit F ⋙ G ⟶ colimit (E ⋙ (F ⋙ G)) or -/ colimit.post (E ⋙ F) G ≫ G.map (colimit.pre F E) = colimit.pre (F ⋙ G) E ≫ colimit.post F G := begin ext, rw [←assoc, colimit.ι_post, ←G.map_comp, colimit.ι_pre, ←assoc], letI : has_colimit (E ⋙ F ⋙ G) := show has_colimit ((E ⋙ F) ⋙ G), by apply_instance, erw [colimit.ι_pre (F ⋙ G) E j, colimit.ι_post] end open category_theory.equivalence instance has_colimit_equivalence_comp (e : K ≌ J) [has_colimit F] : has_colimit (e.functor ⋙ F) := { cocone := cocone.whisker e.functor (colimit.cocone F), is_colimit := let e' := cocones.precompose (e.inv_fun_id_assoc F).inv in { desc := λ s, colimit.desc F (e'.obj (cocone.whisker e.inverse s)), fac' := λ s j, begin dsimp, rw [colimit.ι_desc], dsimp [e'], erw [inv_fun_id_assoc_inv_app, ←functor_unit, s.ι.naturality, comp_id], refl end, uniq' := λ s m w, begin apply colimit.hom_ext, intro j, erw [colimit.ι_desc], have := w (e.inverse.obj j), simp at this, erw [←colimit.w F (e.counit_iso.hom.app j)] at this, erw [assoc, ←iso.eq_inv_comp (F.map_iso $ e.counit_iso.app j)] at this, erw [this], simp end } } /-- If a `E ⋙ F` has a chosen colimit, and `E` is an equivalence, we can construct a chosen colimit of `F`. -/ def has_colimit_of_equivalence_comp (e : K ≌ J) [has_colimit (e.functor ⋙ F)] : has_colimit F := begin haveI : has_colimit (e.inverse ⋙ e.functor ⋙ F) := limits.has_colimit_equivalence_comp e.symm, apply has_colimit_of_iso (e.inv_fun_id_assoc F).symm, end section colim_functor variables [has_colimits_of_shape J C] /-- `colimit F` is functorial in `F`, when `C` has all colimits of shape `J`. -/ def colim : (J ⥤ C) ⥤ C := { obj := λ F, colimit F, map := λ F G α, colimit.desc F { X := colimit G, ι := { app := λ j, α.app j ≫ colimit.ι G j, naturality' := λ j j' f, by erw [comp_id, ←assoc, α.naturality, assoc, colimit.w] } }, map_comp' := λ F G H α β, by ext; erw [←assoc, is_colimit.fac, is_colimit.fac, assoc, is_colimit.fac, ←assoc]; refl } variables {F} {G : J ⥤ C} (α : F ⟶ G) @[simp, reassoc] lemma colimit.ι_map (j : J) : colimit.ι F j ≫ colim.map α = α.app j ≫ colimit.ι G j := by apply is_colimit.fac @[simp] lemma colimit.map_desc (c : cocone G) : colim.map α ≫ colimit.desc G c = colimit.desc F ((cocones.precompose α).obj c) := by ext; rw [←assoc, colimit.ι_map, assoc, colimit.ι_desc, colimit.ι_desc]; refl lemma colimit.pre_map [has_colimits_of_shape K C] (E : K ⥤ J) : colimit.pre F E ≫ colim.map α = colim.map (whisker_left E α) ≫ colimit.pre G E := by ext; rw [←assoc, colimit.ι_pre, colimit.ι_map, ←assoc, colimit.ι_map, assoc, colimit.ι_pre]; refl lemma colimit.pre_map' [has_colimits_of_shape.{v} K C] (F : J ⥤ C) {E₁ E₂ : K ⥤ J} (α : E₁ ⟶ E₂) : colimit.pre F E₁ = colim.map (whisker_right α F) ≫ colimit.pre F E₂ := by ext1; simp [← category.assoc] lemma colimit.pre_id (F : J ⥤ C) : colimit.pre F (𝟭 _) = colim.map (functor.left_unitor F).hom := by tidy lemma colimit.map_post {D : Type u'} [category.{v} D] [has_colimits_of_shape J D] (H : C ⥤ D) : /- H (colimit F) ⟶ H (colimit G) ⟶ colimit (G ⋙ H) vs H (colimit F) ⟶ colimit (F ⋙ H) ⟶ colimit (G ⋙ H) -/ colimit.post F H ≫ H.map (colim.map α) = colim.map (whisker_right α H) ≫ colimit.post G H:= begin ext, rw [←assoc, colimit.ι_post, ←H.map_comp, colimit.ι_map, H.map_comp], rw [←assoc, colimit.ι_map, assoc, colimit.ι_post], refl end /-- The isomorphism between morphisms from the cone point of the chosen colimit cocone for `F` to `W` and cocones over `F` with cone point `W` is natural in `F`. -/ def colim_coyoneda : colim.op ⋙ coyoneda ≅ category_theory.cocones J C := nat_iso.of_components (λ F, nat_iso.of_components (colimit.hom_iso (unop F)) (by tidy)) (by tidy) end colim_functor /-- We can transport chosen colimits of shape `J` along an equivalence `J ≌ J'`. -/ def has_colimits_of_shape_of_equivalence {J' : Type v} [small_category J'] (e : J ≌ J') [has_colimits_of_shape J C] : has_colimits_of_shape J' C := by { constructor, intro F, apply has_colimit_of_equivalence_comp e, apply_instance } end colimit end category_theory.limits
11983d0767237a6816ec1258862db10adb4b6410
9028d228ac200bbefe3a711342514dd4e4458bff
/src/order/bounds.lean
3ee7148f38c6423b20df963dfa3cc5c0b9c919cc
[ "Apache-2.0" ]
permissive
mcncm/mathlib
8d25099344d9d2bee62822cb9ed43aa3e09fa05e
fde3d78cadeec5ef827b16ae55664ef115e66f57
refs/heads/master
1,672,743,316,277
1,602,618,514,000
1,602,618,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
29,277
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, Yury Kudryashov -/ import data.set.intervals.basic import algebra.ordered_group /-! # Upper / lower bounds In this file we define: * `upper_bounds`, `lower_bounds` : the set of upper bounds (resp., lower bounds) of a set; * `bdd_above s`, `bdd_below s` : the set `s` is bounded above (resp., below), i.e., the set of upper (resp., lower) bounds of `s` is nonempty; * `is_least s a`, `is_greatest s a` : `a` is a least (resp., greatest) element of `s`; for a partial order, it is unique if exists; * `is_lub s a`, `is_glb s a` : `a` is a least upper bound (resp., a greatest lower bound) of `s`; for a partial order, it is unique if exists. We also prove various lemmas about monotonicity, behaviour under `∪`, `∩`, `insert`, and provide formulas for `∅`, `univ`, and intervals. -/ open set universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} section variables [preorder α] [preorder β] {s t : set α} {a b : α} /-! ### Definitions -/ /-- The set of upper bounds of a set. -/ def upper_bounds (s : set α) : set α := { x | ∀ ⦃a⦄, a ∈ s → a ≤ x } /-- The set of lower bounds of a set. -/ def lower_bounds (s : set α) : set α := { x | ∀ ⦃a⦄, a ∈ s → x ≤ a } /-- A set is bounded above if there exists an upper bound. -/ def bdd_above (s : set α) := (upper_bounds s).nonempty /-- A set is bounded below if there exists a lower bound. -/ def bdd_below (s : set α) := (lower_bounds s).nonempty /-- `a` is a least element of a set `s`; for a partial order, it is unique if exists. -/ def is_least (s : set α) (a : α) : Prop := a ∈ s ∧ a ∈ lower_bounds s /-- `a` is a greatest element of a set `s`; for a partial order, it is unique if exists -/ def is_greatest (s : set α) (a : α) : Prop := a ∈ s ∧ a ∈ upper_bounds s /-- `a` is a least upper bound of a set `s`; for a partial order, it is unique if exists. -/ def is_lub (s : set α) : α → Prop := is_least (upper_bounds s) /-- `a` is a greatest lower bound of a set `s`; for a partial order, it is unique if exists. -/ def is_glb (s : set α) : α → Prop := is_greatest (lower_bounds s) lemma mem_upper_bounds : a ∈ upper_bounds s ↔ ∀ x ∈ s, x ≤ a := iff.rfl lemma mem_lower_bounds : a ∈ lower_bounds s ↔ ∀ x ∈ s, a ≤ x := iff.rfl /-- A set `s` is not bounded above if and only if for each `x` there exists `y ∈ s` such that `x` is not greater than or equal to `y`. This version only assumes `preorder` structure and uses `¬(y ≤ x)`. A version for linear orders is called `not_bdd_above_iff`. -/ lemma not_bdd_above_iff' : ¬bdd_above s ↔ ∀ x, ∃ y ∈ s, ¬(y ≤ x) := by simp [bdd_above, upper_bounds, set.nonempty] /-- A set `s` is not bounded below if and only if for each `x` there exists `y ∈ s` such that `x` is not less than or equal to `y`. This version only assumes `preorder` structure and uses `¬(x ≤ y)`. A version for linear orders is called `not_bdd_below_iff`. -/ lemma not_bdd_below_iff' : ¬bdd_below s ↔ ∀ x, ∃ y ∈ s, ¬(x ≤ y) := @not_bdd_above_iff' (order_dual α) _ _ /-- A set `s` is not bounded above if and only if for each `x` there exists `y ∈ s` that is greater than `x`. A version for preorders is called `not_bdd_above_iff'`. -/ lemma not_bdd_above_iff {α : Type*} [linear_order α] {s : set α} : ¬bdd_above s ↔ ∀ x, ∃ y ∈ s, x < y := by simp only [not_bdd_above_iff', not_le] /-- A set `s` is not bounded below if and only if for each `x` there exists `y ∈ s` that is less than `x`. A version for preorders is called `not_bdd_below_iff'`. -/ lemma not_bdd_below_iff {α : Type*} [linear_order α] {s : set α} : ¬bdd_below s ↔ ∀ x, ∃ y ∈ s, y < x := @not_bdd_above_iff (order_dual α) _ _ /-! ### Monotonicity -/ lemma upper_bounds_mono_set ⦃s t : set α⦄ (hst : s ⊆ t) : upper_bounds t ⊆ upper_bounds s := λ b hb x h, hb $ hst h lemma lower_bounds_mono_set ⦃s t : set α⦄ (hst : s ⊆ t) : lower_bounds t ⊆ lower_bounds s := λ b hb x h, hb $ hst h lemma upper_bounds_mono_mem ⦃a b⦄ (hab : a ≤ b) : a ∈ upper_bounds s → b ∈ upper_bounds s := λ ha x h, le_trans (ha h) hab lemma lower_bounds_mono_mem ⦃a b⦄ (hab : a ≤ b) : b ∈ lower_bounds s → a ∈ lower_bounds s := λ hb x h, le_trans hab (hb h) lemma upper_bounds_mono ⦃s t : set α⦄ (hst : s ⊆ t) ⦃a b⦄ (hab : a ≤ b) : a ∈ upper_bounds t → b ∈ upper_bounds s := λ ha, upper_bounds_mono_set hst $ upper_bounds_mono_mem hab ha lemma lower_bounds_mono ⦃s t : set α⦄ (hst : s ⊆ t) ⦃a b⦄ (hab : a ≤ b) : b ∈ lower_bounds t → a ∈ lower_bounds s := λ hb, lower_bounds_mono_set hst $ lower_bounds_mono_mem hab hb /-- If `s ⊆ t` and `t` is bounded above, then so is `s`. -/ lemma bdd_above.mono ⦃s t : set α⦄ (h : s ⊆ t) : bdd_above t → bdd_above s := nonempty.mono $ upper_bounds_mono_set h /-- If `s ⊆ t` and `t` is bounded below, then so is `s`. -/ lemma bdd_below.mono ⦃s t : set α⦄ (h : s ⊆ t) : bdd_below t → bdd_below s := nonempty.mono $ lower_bounds_mono_set h /-- If `a` is a least upper bound for sets `s` and `p`, then it is a least upper bound for any set `t`, `s ⊆ t ⊆ p`. -/ lemma is_lub.of_subset_of_superset {s t p : set α} (hs : is_lub s a) (hp : is_lub p a) (hst : s ⊆ t) (htp : t ⊆ p) : is_lub t a := ⟨upper_bounds_mono_set htp hp.1, lower_bounds_mono_set (upper_bounds_mono_set hst) hs.2⟩ /-- If `a` is a greatest lower bound for sets `s` and `p`, then it is a greater lower bound for any set `t`, `s ⊆ t ⊆ p`. -/ lemma is_glb.of_subset_of_superset {s t p : set α} (hs : is_glb s a) (hp : is_glb p a) (hst : s ⊆ t) (htp : t ⊆ p) : is_glb t a := @is_lub.of_subset_of_superset (order_dual α) _ a s t p hs hp hst htp lemma is_least.mono (ha : is_least s a) (hb : is_least t b) (hst : s ⊆ t) : b ≤ a := hb.2 (hst ha.1) lemma is_greatest.mono (ha : is_greatest s a) (hb : is_greatest t b) (hst : s ⊆ t) : a ≤ b := hb.2 (hst ha.1) lemma is_lub.mono (ha : is_lub s a) (hb : is_lub t b) (hst : s ⊆ t) : a ≤ b := hb.mono ha $ upper_bounds_mono_set hst lemma is_glb.mono (ha : is_glb s a) (hb : is_glb t b) (hst : s ⊆ t) : b ≤ a := hb.mono ha $ lower_bounds_mono_set hst /-! ### Conversions -/ lemma is_least.is_glb (h : is_least s a) : is_glb s a := ⟨h.2, λ b hb, hb h.1⟩ lemma is_greatest.is_lub (h : is_greatest s a) : is_lub s a := ⟨h.2, λ b hb, hb h.1⟩ lemma is_lub.upper_bounds_eq (h : is_lub s a) : upper_bounds s = Ici a := set.ext $ λ b, ⟨λ hb, h.2 hb, λ hb, upper_bounds_mono_mem hb h.1⟩ lemma is_glb.lower_bounds_eq (h : is_glb s a) : lower_bounds s = Iic a := @is_lub.upper_bounds_eq (order_dual α) _ _ _ h lemma is_least.lower_bounds_eq (h : is_least s a) : lower_bounds s = Iic a := h.is_glb.lower_bounds_eq lemma is_greatest.upper_bounds_eq (h : is_greatest s a) : upper_bounds s = Ici a := h.is_lub.upper_bounds_eq lemma is_lub_le_iff (h : is_lub s a) : a ≤ b ↔ b ∈ upper_bounds s := by { rw h.upper_bounds_eq, refl } lemma le_is_glb_iff (h : is_glb s a) : b ≤ a ↔ b ∈ lower_bounds s := by { rw h.lower_bounds_eq, refl } /-- If `s` has a least upper bound, then it is bounded above. -/ lemma is_lub.bdd_above (h : is_lub s a) : bdd_above s := ⟨a, h.1⟩ /-- If `s` has a greatest lower bound, then it is bounded below. -/ lemma is_glb.bdd_below (h : is_glb s a) : bdd_below s := ⟨a, h.1⟩ /-- If `s` has a greatest element, then it is bounded above. -/ lemma is_greatest.bdd_above (h : is_greatest s a) : bdd_above s := ⟨a, h.2⟩ /-- If `s` has a least element, then it is bounded below. -/ lemma is_least.bdd_below (h : is_least s a) : bdd_below s := ⟨a, h.2⟩ lemma is_least.nonempty (h : is_least s a) : s.nonempty := ⟨a, h.1⟩ lemma is_greatest.nonempty (h : is_greatest s a) : s.nonempty := ⟨a, h.1⟩ /-! ### Union and intersection -/ @[simp] lemma upper_bounds_union : upper_bounds (s ∪ t) = upper_bounds s ∩ upper_bounds t := subset.antisymm (λ b hb, ⟨λ x hx, hb (or.inl hx), λ x hx, hb (or.inr hx)⟩) (λ b hb x hx, hx.elim (λ hs, hb.1 hs) (λ ht, hb.2 ht)) @[simp] lemma lower_bounds_union : lower_bounds (s ∪ t) = lower_bounds s ∩ lower_bounds t := @upper_bounds_union (order_dual α) _ s t lemma union_upper_bounds_subset_upper_bounds_inter : upper_bounds s ∪ upper_bounds t ⊆ upper_bounds (s ∩ t) := union_subset (upper_bounds_mono_set $ inter_subset_left _ _) (upper_bounds_mono_set $ inter_subset_right _ _) lemma union_lower_bounds_subset_lower_bounds_inter : lower_bounds s ∪ lower_bounds t ⊆ lower_bounds (s ∩ t) := @union_upper_bounds_subset_upper_bounds_inter (order_dual α) _ s t lemma is_least_union_iff {a : α} {s t : set α} : is_least (s ∪ t) a ↔ (is_least s a ∧ a ∈ lower_bounds t ∨ a ∈ lower_bounds s ∧ is_least t a) := by simp [is_least, lower_bounds_union, or_and_distrib_right, and_comm (a ∈ t), and_assoc] lemma is_greatest_union_iff : is_greatest (s ∪ t) a ↔ (is_greatest s a ∧ a ∈ upper_bounds t ∨ a ∈ upper_bounds s ∧ is_greatest t a) := @is_least_union_iff (order_dual α) _ a s t /-- If `s` is bounded, then so is `s ∩ t` -/ lemma bdd_above.inter_of_left (h : bdd_above s) : bdd_above (s ∩ t) := h.mono $ inter_subset_left s t /-- If `t` is bounded, then so is `s ∩ t` -/ lemma bdd_above.inter_of_right (h : bdd_above t) : bdd_above (s ∩ t) := h.mono $ inter_subset_right s t /-- If `s` is bounded, then so is `s ∩ t` -/ lemma bdd_below.inter_of_left (h : bdd_below s) : bdd_below (s ∩ t) := h.mono $ inter_subset_left s t /-- If `t` is bounded, then so is `s ∩ t` -/ lemma bdd_below.inter_of_right (h : bdd_below t) : bdd_below (s ∩ t) := h.mono $ inter_subset_right s t /-- If `s` and `t` are bounded above sets in a `semilattice_sup`, then so is `s ∪ t`. -/ lemma bdd_above.union [semilattice_sup γ] {s t : set γ} : bdd_above s → bdd_above t → bdd_above (s ∪ t) := begin rintros ⟨bs, hs⟩ ⟨bt, ht⟩, use bs ⊔ bt, rw upper_bounds_union, exact ⟨upper_bounds_mono_mem le_sup_left hs, upper_bounds_mono_mem le_sup_right ht⟩ end /-- The union of two sets is bounded above if and only if each of the sets is. -/ lemma bdd_above_union [semilattice_sup γ] {s t : set γ} : bdd_above (s ∪ t) ↔ bdd_above s ∧ bdd_above t := ⟨λ h, ⟨h.mono $ subset_union_left s t, h.mono $ subset_union_right s t⟩, λ h, h.1.union h.2⟩ lemma bdd_below.union [semilattice_inf γ] {s t : set γ} : bdd_below s → bdd_below t → bdd_below (s ∪ t) := @bdd_above.union (order_dual γ) _ s t /--The union of two sets is bounded above if and only if each of the sets is.-/ lemma bdd_below_union [semilattice_inf γ] {s t : set γ} : bdd_below (s ∪ t) ↔ bdd_below s ∧ bdd_below t := @bdd_above_union (order_dual γ) _ s t /-- If `a` is the least upper bound of `s` and `b` is the least upper bound of `t`, then `a ⊔ b` is the least upper bound of `s ∪ t`. -/ lemma is_lub.union [semilattice_sup γ] {a b : γ} {s t : set γ} (hs : is_lub s a) (ht : is_lub t b) : is_lub (s ∪ t) (a ⊔ b) := ⟨assume c h, h.cases_on (λ h, le_sup_left_of_le $ hs.left h) (λ h, le_sup_right_of_le $ ht.left h), assume c hc, sup_le (hs.right $ assume d hd, hc $ or.inl hd) (ht.right $ assume d hd, hc $ or.inr hd)⟩ /-- If `a` is the greatest lower bound of `s` and `b` is the greatest lower bound of `t`, then `a ⊓ b` is the greatest lower bound of `s ∪ t`. -/ lemma is_glb.union [semilattice_inf γ] {a₁ a₂ : γ} {s t : set γ} (hs : is_glb s a₁) (ht : is_glb t a₂) : is_glb (s ∪ t) (a₁ ⊓ a₂) := @is_lub.union (order_dual γ) _ _ _ _ _ hs ht /-- If `a` is the least element of `s` and `b` is the least element of `t`, then `min a b` is the least element of `s ∪ t`. -/ lemma is_least.union [decidable_linear_order γ] {a b : γ} {s t : set γ} (ha : is_least s a) (hb : is_least t b) : is_least (s ∪ t) (min a b) := ⟨by cases (le_total a b) with h h; simp [h, ha.1, hb.1], (ha.is_glb.union hb.is_glb).1⟩ /-- If `a` is the greatest element of `s` and `b` is the greatest element of `t`, then `max a b` is the greatest element of `s ∪ t`. -/ lemma is_greatest.union [decidable_linear_order γ] {a b : γ} {s t : set γ} (ha : is_greatest s a) (hb : is_greatest t b) : is_greatest (s ∪ t) (max a b) := ⟨by cases (le_total a b) with h h; simp [h, ha.1, hb.1], (ha.is_lub.union hb.is_lub).1⟩ /-! ### Specific sets #### Unbounded intervals -/ lemma is_least_Ici : is_least (Ici a) a := ⟨left_mem_Ici, λ x, id⟩ lemma is_greatest_Iic : is_greatest (Iic a) a := ⟨right_mem_Iic, λ x, id⟩ lemma is_lub_Iic : is_lub (Iic a) a := is_greatest_Iic.is_lub lemma is_glb_Ici : is_glb (Ici a) a := is_least_Ici.is_glb lemma upper_bounds_Iic : upper_bounds (Iic a) = Ici a := is_lub_Iic.upper_bounds_eq lemma lower_bounds_Ici : lower_bounds (Ici a) = Iic a := is_glb_Ici.lower_bounds_eq lemma bdd_above_Iic : bdd_above (Iic a) := is_lub_Iic.bdd_above lemma bdd_below_Ici : bdd_below (Ici a) := is_glb_Ici.bdd_below lemma bdd_above_Iio : bdd_above (Iio a) := ⟨a, λ x hx, le_of_lt hx⟩ lemma bdd_below_Ioi : bdd_below (Ioi a) := ⟨a, λ x hx, le_of_lt hx⟩ section variables [linear_order γ] [densely_ordered γ] lemma is_lub_Iio {a : γ} : is_lub (Iio a) a := ⟨λ x hx, le_of_lt hx, λ y hy, le_of_forall_ge_of_dense hy⟩ lemma is_glb_Ioi {a : γ} : is_glb (Ioi a) a := @is_lub_Iio (order_dual γ) _ _ a lemma upper_bounds_Iio {a : γ} : upper_bounds (Iio a) = Ici a := is_lub_Iio.upper_bounds_eq lemma lower_bounds_Ioi {a : γ} : lower_bounds (Ioi a) = Iic a := is_glb_Ioi.lower_bounds_eq end /-! #### Singleton -/ lemma is_greatest_singleton : is_greatest {a} a := ⟨mem_singleton a, λ x hx, le_of_eq $ eq_of_mem_singleton hx⟩ lemma is_least_singleton : is_least {a} a := @is_greatest_singleton (order_dual α) _ a lemma is_lub_singleton : is_lub {a} a := is_greatest_singleton.is_lub lemma is_glb_singleton : is_glb {a} a := is_least_singleton.is_glb lemma bdd_above_singleton : bdd_above ({a} : set α) := is_lub_singleton.bdd_above lemma bdd_below_singleton : bdd_below ({a} : set α) := is_glb_singleton.bdd_below @[simp] lemma upper_bounds_singleton : upper_bounds {a} = Ici a := is_lub_singleton.upper_bounds_eq @[simp] lemma lower_bounds_singleton : lower_bounds {a} = Iic a := is_glb_singleton.lower_bounds_eq /-! #### Bounded intervals -/ lemma bdd_above_Icc : bdd_above (Icc a b) := ⟨b, λ _, and.right⟩ lemma bdd_above_Ico : bdd_above (Ico a b) := bdd_above_Icc.mono Ico_subset_Icc_self lemma bdd_above_Ioc : bdd_above (Ioc a b) := bdd_above_Icc.mono Ioc_subset_Icc_self lemma bdd_above_Ioo : bdd_above (Ioo a b) := bdd_above_Icc.mono Ioo_subset_Icc_self lemma is_greatest_Icc (h : a ≤ b) : is_greatest (Icc a b) b := ⟨right_mem_Icc.2 h, λ x, and.right⟩ lemma is_lub_Icc (h : a ≤ b) : is_lub (Icc a b) b := (is_greatest_Icc h).is_lub lemma upper_bounds_Icc (h : a ≤ b) : upper_bounds (Icc a b) = Ici b := (is_lub_Icc h).upper_bounds_eq lemma is_least_Icc (h : a ≤ b) : is_least (Icc a b) a := ⟨left_mem_Icc.2 h, λ x, and.left⟩ lemma is_glb_Icc (h : a ≤ b) : is_glb (Icc a b) a := (is_least_Icc h).is_glb lemma lower_bounds_Icc (h : a ≤ b) : lower_bounds (Icc a b) = Iic a := (is_glb_Icc h).lower_bounds_eq lemma is_greatest_Ioc (h : a < b) : is_greatest (Ioc a b) b := ⟨right_mem_Ioc.2 h, λ x, and.right⟩ lemma is_lub_Ioc (h : a < b) : is_lub (Ioc a b) b := (is_greatest_Ioc h).is_lub lemma upper_bounds_Ioc (h : a < b) : upper_bounds (Ioc a b) = Ici b := (is_lub_Ioc h).upper_bounds_eq lemma is_least_Ico (h : a < b) : is_least (Ico a b) a := ⟨left_mem_Ico.2 h, λ x, and.left⟩ lemma is_glb_Ico (h : a < b) : is_glb (Ico a b) a := (is_least_Ico h).is_glb lemma lower_bounds_Ico (h : a < b) : lower_bounds (Ico a b) = Iic a := (is_glb_Ico h).lower_bounds_eq section variables [linear_order γ] [densely_ordered γ] lemma is_glb_Ioo {a b : γ} (hab : a < b) : is_glb (Ioo a b) a := begin refine ⟨λx hx, le_of_lt hx.1, λy hy, le_of_not_lt $ λ h, _⟩, letI := classical.DLO γ, have : a < min b y, by { rw lt_min_iff, exact ⟨hab, h⟩ }, rcases exists_between this with ⟨z, az, zy⟩, rw lt_min_iff at zy, exact lt_irrefl _ (lt_of_le_of_lt (hy ⟨az, zy.1⟩) zy.2) end lemma lower_bounds_Ioo {a b : γ} (hab : a < b) : lower_bounds (Ioo a b) = Iic a := (is_glb_Ioo hab).lower_bounds_eq lemma is_glb_Ioc {a b : γ} (hab : a < b) : is_glb (Ioc a b) a := (is_glb_Ioo hab).of_subset_of_superset (is_glb_Icc $ le_of_lt hab) Ioo_subset_Ioc_self Ioc_subset_Icc_self lemma lower_bound_Ioc {a b : γ} (hab : a < b) : lower_bounds (Ioc a b) = Iic a := (is_glb_Ioc hab).lower_bounds_eq lemma is_lub_Ioo {a b : γ} (hab : a < b) : is_lub (Ioo a b) b := by simpa only [dual_Ioo] using @is_glb_Ioo (order_dual γ) _ _ b a hab lemma upper_bounds_Ioo {a b : γ} (hab : a < b) : upper_bounds (Ioo a b) = Ici b := (is_lub_Ioo hab).upper_bounds_eq lemma is_lub_Ico {a b : γ} (hab : a < b) : is_lub (Ico a b) b := by simpa only [dual_Ioc] using @is_glb_Ioc (order_dual γ) _ _ b a hab lemma upper_bounds_Ico {a b : γ} (hab : a < b) : upper_bounds (Ico a b) = Ici b := (is_lub_Ico hab).upper_bounds_eq end lemma bdd_below_iff_subset_Ici : bdd_below s ↔ ∃ a, s ⊆ Ici a := iff.rfl lemma bdd_above_iff_subset_Iic : bdd_above s ↔ ∃ a, s ⊆ Iic a := iff.rfl lemma bdd_below_bdd_above_iff_subset_Icc : bdd_below s ∧ bdd_above s ↔ ∃ a b, s ⊆ Icc a b := by simp only [Ici_inter_Iic.symm, subset_inter_iff, bdd_below_iff_subset_Ici, bdd_above_iff_subset_Iic, exists_and_distrib_left, exists_and_distrib_right] /-! ### Univ -/ lemma order_top.upper_bounds_univ [order_top γ] : upper_bounds (univ : set γ) = {⊤} := set.ext $ λ b, iff.trans ⟨λ hb, top_unique $ hb trivial, λ hb x hx, hb.symm ▸ le_top⟩ mem_singleton_iff.symm lemma is_greatest_univ [order_top γ] : is_greatest (univ : set γ) ⊤ := by simp only [is_greatest, order_top.upper_bounds_univ, mem_univ, mem_singleton, true_and] lemma is_lub_univ [order_top γ] : is_lub (univ : set γ) ⊤ := is_greatest_univ.is_lub lemma order_bot.lower_bounds_univ [order_bot γ] : lower_bounds (univ : set γ) = {⊥} := @order_top.upper_bounds_univ (order_dual γ) _ lemma is_least_univ [order_bot γ] : is_least (univ : set γ) ⊥ := @is_greatest_univ (order_dual γ) _ lemma is_glb_univ [order_bot γ] : is_glb (univ : set γ) ⊥ := is_least_univ.is_glb lemma no_top_order.upper_bounds_univ [no_top_order α] : upper_bounds (univ : set α) = ∅ := eq_empty_of_subset_empty $ λ b hb, let ⟨x, hx⟩ := no_top b in not_le_of_lt hx (hb trivial) lemma no_bot_order.lower_bounds_univ [no_bot_order α] : lower_bounds (univ : set α) = ∅ := @no_top_order.upper_bounds_univ (order_dual α) _ _ /-! ### Empty set -/ @[simp] lemma upper_bounds_empty : upper_bounds (∅ : set α) = univ := by simp only [upper_bounds, eq_univ_iff_forall, mem_set_of_eq, ball_empty_iff, forall_true_iff] @[simp] lemma lower_bounds_empty : lower_bounds (∅ : set α) = univ := @upper_bounds_empty (order_dual α) _ @[simp] lemma bdd_above_empty [nonempty α] : bdd_above (∅ : set α) := by simp only [bdd_above, upper_bounds_empty, univ_nonempty] @[simp] lemma bdd_below_empty [nonempty α] : bdd_below (∅ : set α) := by simp only [bdd_below, lower_bounds_empty, univ_nonempty] lemma is_glb_empty [order_top γ] : is_glb ∅ (⊤:γ) := by simp only [is_glb, lower_bounds_empty, is_greatest_univ] lemma is_lub_empty [order_bot γ] : is_lub ∅ (⊥:γ) := @is_glb_empty (order_dual γ) _ lemma is_lub.nonempty [no_bot_order α] (hs : is_lub s a) : s.nonempty := let ⟨a', ha'⟩ := no_bot a in ne_empty_iff_nonempty.1 $ assume h, have a ≤ a', from hs.right $ by simp only [h, upper_bounds_empty], not_le_of_lt ha' this lemma is_glb.nonempty [no_top_order α] (hs : is_glb s a) : s.nonempty := @is_lub.nonempty (order_dual α) _ _ _ _ hs lemma nonempty_of_not_bdd_above [ha : nonempty α] (h : ¬bdd_above s) : s.nonempty := nonempty.elim ha $ λ x, (not_bdd_above_iff'.1 h x).imp $ λ a ha, ha.fst lemma nonempty_of_not_bdd_below [ha : nonempty α] (h : ¬bdd_below s) : s.nonempty := @nonempty_of_not_bdd_above (order_dual α) _ _ _ h /-! ### insert -/ /-- Adding a point to a set preserves its boundedness above. -/ @[simp] lemma bdd_above_insert [semilattice_sup γ] (a : γ) {s : set γ} : bdd_above (insert a s) ↔ bdd_above s := by simp only [insert_eq, bdd_above_union, bdd_above_singleton, true_and] lemma bdd_above.insert [semilattice_sup γ] (a : γ) {s : set γ} (hs : bdd_above s) : bdd_above (insert a s) := (bdd_above_insert a).2 hs /--Adding a point to a set preserves its boundedness below.-/ @[simp] lemma bdd_below_insert [semilattice_inf γ] (a : γ) {s : set γ} : bdd_below (insert a s) ↔ bdd_below s := by simp only [insert_eq, bdd_below_union, bdd_below_singleton, true_and] lemma bdd_below.insert [semilattice_inf γ] (a : γ) {s : set γ} (hs : bdd_below s) : bdd_below (insert a s) := (bdd_below_insert a).2 hs lemma is_lub.insert [semilattice_sup γ] (a) {b} {s : set γ} (hs : is_lub s b) : is_lub (insert a s) (a ⊔ b) := by { rw insert_eq, exact is_lub_singleton.union hs } lemma is_glb.insert [semilattice_inf γ] (a) {b} {s : set γ} (hs : is_glb s b) : is_glb (insert a s) (a ⊓ b) := by { rw insert_eq, exact is_glb_singleton.union hs } lemma is_greatest.insert [decidable_linear_order γ] (a) {b} {s : set γ} (hs : is_greatest s b) : is_greatest (insert a s) (max a b) := by { rw insert_eq, exact is_greatest_singleton.union hs } lemma is_least.insert [decidable_linear_order γ] (a) {b} {s : set γ} (hs : is_least s b) : is_least (insert a s) (min a b) := by { rw insert_eq, exact is_least_singleton.union hs } @[simp] lemma upper_bounds_insert (a : α) (s : set α) : upper_bounds (insert a s) = Ici a ∩ upper_bounds s := by rw [insert_eq, upper_bounds_union, upper_bounds_singleton] @[simp] lemma lower_bounds_insert (a : α) (s : set α) : lower_bounds (insert a s) = Iic a ∩ lower_bounds s := by rw [insert_eq, lower_bounds_union, lower_bounds_singleton] /-- When there is a global maximum, every set is bounded above. -/ @[simp] protected lemma order_top.bdd_above [order_top γ] (s : set γ) : bdd_above s := ⟨⊤, assume a ha, order_top.le_top a⟩ /-- When there is a global minimum, every set is bounded below. -/ @[simp] protected lemma order_bot.bdd_below [order_bot γ] (s : set γ) : bdd_below s := ⟨⊥, assume a ha, order_bot.bot_le a⟩ /-! ### Pair -/ lemma is_lub_pair [semilattice_sup γ] {a b : γ} : is_lub {a, b} (a ⊔ b) := is_lub_singleton.insert _ lemma is_glb_pair [semilattice_inf γ] {a b : γ} : is_glb {a, b} (a ⊓ b) := is_glb_singleton.insert _ lemma is_least_pair [decidable_linear_order γ] {a b : γ} : is_least {a, b} (min a b) := is_least_singleton.insert _ lemma is_greatest_pair [decidable_linear_order γ] {a b : γ} : is_greatest {a, b} (max a b) := is_greatest_singleton.insert _ end /-! ### (In)equalities with the least upper bound and the greatest lower bound -/ section preorder variables [preorder α] {s : set α} {a b : α} lemma lower_bounds_le_upper_bounds (ha : a ∈ lower_bounds s) (hb : b ∈ upper_bounds s) : s.nonempty → a ≤ b | ⟨c, hc⟩ := le_trans (ha hc) (hb hc) lemma is_glb_le_is_lub (ha : is_glb s a) (hb : is_lub s b) (hs : s.nonempty) : a ≤ b := lower_bounds_le_upper_bounds ha.1 hb.1 hs lemma is_lub_lt_iff (ha : is_lub s a) : a < b ↔ ∃ c ∈ upper_bounds s, c < b := ⟨λ hb, ⟨a, ha.1, hb⟩, λ ⟨c, hcs, hcb⟩, lt_of_le_of_lt (ha.2 hcs) hcb⟩ lemma lt_is_glb_iff (ha : is_glb s a) : b < a ↔ ∃ c ∈ lower_bounds s, b < c := @is_lub_lt_iff (order_dual α) _ s _ _ ha end preorder section partial_order variables [partial_order α] {s : set α} {a b : α} lemma is_least.unique (Ha : is_least s a) (Hb : is_least s b) : a = b := le_antisymm (Ha.right Hb.left) (Hb.right Ha.left) lemma is_least.is_least_iff_eq (Ha : is_least s a) : is_least s b ↔ a = b := iff.intro Ha.unique (assume h, h ▸ Ha) lemma is_greatest.unique (Ha : is_greatest s a) (Hb : is_greatest s b) : a = b := le_antisymm (Hb.right Ha.left) (Ha.right Hb.left) lemma is_greatest.is_greatest_iff_eq (Ha : is_greatest s a) : is_greatest s b ↔ a = b := iff.intro Ha.unique (assume h, h ▸ Ha) lemma is_lub.unique (Ha : is_lub s a) (Hb : is_lub s b) : a = b := Ha.unique Hb lemma is_glb.unique (Ha : is_glb s a) (Hb : is_glb s b) : a = b := Ha.unique Hb end partial_order section linear_order variables [linear_order α] {s : set α} {a b : α} lemma lt_is_lub_iff (h : is_lub s a) : b < a ↔ ∃ c ∈ s, b < c := by haveI := classical.dec; simpa [upper_bounds, not_ball] using not_congr (@is_lub_le_iff _ _ _ _ b h) lemma is_glb_lt_iff (h : is_glb s a) : a < b ↔ ∃ c ∈ s, c < b := @lt_is_lub_iff (order_dual α) _ _ _ _ h end linear_order /-! ### Least upper bound and the greatest lower bound in linear ordered additive commutative groups -/ section decidable_linear_ordered_add_comm_group variables [decidable_linear_ordered_add_comm_group α] {s : set α} {a ε : α} (h₃ : 0 < ε) include h₃ lemma is_glb.exists_between_self_add (h₁ : is_glb s a) : ∃ b, b ∈ s ∧ a ≤ b ∧ b < a + ε := begin have h' : a + ε ∉ lower_bounds s, { set A := a + ε, have : a < A := by { simp [A, h₃] }, intros hA, exact lt_irrefl a (lt_of_lt_of_le this (h₁.2 hA)) }, obtain ⟨b, hb, hb'⟩ : ∃ b ∈ s, b < a + ε, by simpa [lower_bounds] using h', exact ⟨b, hb, h₁.1 hb, hb'⟩ end lemma is_glb.exists_between_self_add' (h₁ : is_glb s a) (h₂ : a ∉ s) : ∃ b, b ∈ s ∧ a < b ∧ b < a + ε := begin rcases h₁.exists_between_self_add h₃ with ⟨b, b_in, hb₁, hb₂⟩, have h₅ : a ≠ b, { intros contra, apply h₂, rwa ← contra at b_in }, exact ⟨b, b_in, lt_of_le_of_ne (h₁.1 b_in) h₅, hb₂⟩ end lemma is_lub.exists_between_sub_self (h₁ : is_lub s a) : ∃ b, b ∈ s ∧ a - ε < b ∧ b ≤ a := begin have h' : a - ε ∉ upper_bounds s, { set A := a - ε, have : A < a := sub_lt_self a h₃, intros hA, exact lt_irrefl a (lt_of_le_of_lt (h₁.2 hA) this) }, obtain ⟨b, hb, hb'⟩ : ∃ (x : α), x ∈ s ∧ a - ε < x, by simpa [upper_bounds] using h', exact ⟨b, hb, hb', h₁.1 hb⟩ end lemma is_lub.exists_between_sub_self' (h₁ : is_lub s a) (h₂ : a ∉ s) : ∃ b, b ∈ s ∧ a - ε < b ∧ b < a := begin rcases h₁.exists_between_sub_self h₃ with ⟨b, b_in, hb₁, hb₂⟩, have h₅ : a ≠ b, { intros contra, apply h₂, rwa ← contra at b_in }, exact ⟨b, b_in, hb₁, lt_of_le_of_ne (h₁.1 b_in) h₅.symm⟩ end end decidable_linear_ordered_add_comm_group /-! ### Images of upper/lower bounds under monotone functions -/ namespace monotone variables [preorder α] [preorder β] {f : α → β} (Hf : monotone f) {a : α} {s : set α} lemma mem_upper_bounds_image (Ha : a ∈ upper_bounds s) : f a ∈ upper_bounds (f '' s) := ball_image_of_ball (assume x H, Hf (Ha ‹x ∈ s›)) lemma mem_lower_bounds_image (Ha : a ∈ lower_bounds s) : f a ∈ lower_bounds (f '' s) := ball_image_of_ball (assume x H, Hf (Ha ‹x ∈ s›)) /-- The image under a monotone function of a set which is bounded above is bounded above. -/ lemma map_bdd_above (hf : monotone f) : bdd_above s → bdd_above (f '' s) | ⟨C, hC⟩ := ⟨f C, hf.mem_upper_bounds_image hC⟩ /-- The image under a monotone function of a set which is bounded below is bounded below. -/ lemma map_bdd_below (hf : monotone f) : bdd_below s → bdd_below (f '' s) | ⟨C, hC⟩ := ⟨f C, hf.mem_lower_bounds_image hC⟩ /-- A monotone map sends a least element of a set to a least element of its image. -/ lemma map_is_least (Ha : is_least s a) : is_least (f '' s) (f a) := ⟨mem_image_of_mem _ Ha.1, Hf.mem_lower_bounds_image Ha.2⟩ /-- A monotone map sends a greatest element of a set to a greatest element of its image. -/ lemma map_is_greatest (Ha : is_greatest s a) : is_greatest (f '' s) (f a) := ⟨mem_image_of_mem _ Ha.1, Hf.mem_upper_bounds_image Ha.2⟩ lemma is_lub_image_le (Ha : is_lub s a) {b : β} (Hb : is_lub (f '' s) b) : b ≤ f a := Hb.2 (Hf.mem_upper_bounds_image Ha.1) lemma le_is_glb_image (Ha : is_glb s a) {b : β} (Hb : is_glb (f '' s) b) : f a ≤ b := Hb.2 (Hf.mem_lower_bounds_image Ha.1) end monotone lemma is_glb.of_image [preorder α] [preorder β] {f : α → β} (hf : ∀ {x y}, f x ≤ f y ↔ x ≤ y) {s : set α} {x : α} (hx : is_glb (f '' s) (f x)) : is_glb s x := ⟨λ y hy, hf.1 $ hx.1 $ mem_image_of_mem _ hy, λ y hy, hf.1 $ hx.2 $ monotone.mem_lower_bounds_image (λ x y, hf.2) hy⟩ lemma is_lub.of_image [preorder α] [preorder β] {f : α → β} (hf : ∀ {x y}, f x ≤ f y ↔ x ≤ y) {s : set α} {x : α} (hx : is_lub (f '' s) (f x)) : is_lub s x := @is_glb.of_image (order_dual α) (order_dual β) _ _ f (λ x y, hf) _ _ hx
8cef40044ca852d771d280ecf47834db4ad18ac0
271e26e338b0c14544a889c31c30b39c989f2e0f
/src/Init/Lean/Environment.lean
79abe699e07f04bae06ca625e0d01d106758a47f
[ "Apache-2.0" ]
permissive
dgorokho/lean4
805f99b0b60c545b64ac34ab8237a8504f89d7d4
e949a052bad59b1c7b54a82d24d516a656487d8a
refs/heads/master
1,607,061,363,851
1,578,006,086,000
1,578,006,086,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
25,899
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.System.IO import Init.Util import Init.Data.ByteArray import Init.Lean.Data.SMap import Init.Lean.Util.Path import Init.Lean.Declaration import Init.Lean.LocalContext namespace Lean /- Opaque environment extension state. It is essentially the Lean version of a C `void *` TODO: mark opaque -/ def EnvExtensionState : Type := NonScalar instance EnvExtensionState.inhabited : Inhabited EnvExtensionState := inferInstanceAs (Inhabited NonScalar) /- TODO: mark opaque. -/ def ModuleIdx := Nat instance ModuleIdx.inhabited : Inhabited ModuleIdx := inferInstanceAs (Inhabited Nat) abbrev ConstMap := SMap Name ConstantInfo structure Import := (module : Name) (runtimeOnly : Bool := false) instance : HasToString Import := ⟨fun imp => toString imp.module ++ if imp.runtimeOnly then " (runtime)" else ""⟩ /- Environment fields that are not used often. -/ structure EnvironmentHeader := (trustLevel : UInt32 := 0) (quotInit : Bool := false) (mainModule : Name := arbitrary _) (imports : Array Import := #[]) /- TODO: mark opaque. -/ structure Environment := (const2ModIdx : HashMap Name ModuleIdx) (constants : ConstMap) (extensions : Array EnvExtensionState) (header : EnvironmentHeader := {}) namespace Environment instance : Inhabited Environment := ⟨{ const2ModIdx := {}, constants := {}, extensions := #[] }⟩ def addAux (env : Environment) (cinfo : ConstantInfo) : Environment := { constants := env.constants.insert cinfo.name cinfo, .. env } @[export lean_environment_find] def find? (env : Environment) (n : Name) : Option ConstantInfo := /- It is safe to use `find'` because we never overwrite imported declarations. -/ env.constants.find?' n def contains (env : Environment) (n : Name) : Bool := env.constants.contains n def imports (env : Environment) : Array Import := env.header.imports @[export lean_environment_set_main_module] def setMainModule (env : Environment) (m : Name) : Environment := { header := { mainModule := m, .. env.header }, .. env } @[export lean_environment_main_module] def mainModule (env : Environment) : Name := env.header.mainModule @[export lean_environment_mark_quot_init] private def markQuotInit (env : Environment) : Environment := { header := { quotInit := true, .. env.header } , .. env } @[export lean_environment_quot_init] private def isQuotInit (env : Environment) : Bool := env.header.quotInit @[export lean_environment_trust_level] private def getTrustLevel (env : Environment) : UInt32 := env.header.trustLevel def getModuleIdxFor? (env : Environment) (c : Name) : Option ModuleIdx := env.const2ModIdx.find? c def isConstructor (env : Environment) (c : Name) : Bool := match env.find? c with | ConstantInfo.ctorInfo _ => true | _ => false end Environment inductive KernelException | unknownConstant (env : Environment) (name : Name) | alreadyDeclared (env : Environment) (name : Name) | declTypeMismatch (env : Environment) (decl : Declaration) (givenType : Expr) | declHasMVars (env : Environment) (name : Name) (expr : Expr) | declHasFVars (env : Environment) (name : Name) (expr : Expr) | funExpected (env : Environment) (lctx : LocalContext) (expr : Expr) | typeExpected (env : Environment) (lctx : LocalContext) (expr : Expr) | letTypeMismatch (env : Environment) (lctx : LocalContext) (name : Name) (givenType : Expr) (expectedType : Expr) | exprTypeMismatch (env : Environment) (lctx : LocalContext) (expr : Expr) (expectedType : Expr) | appTypeMismatch (env : Environment) (lctx : LocalContext) (app : Expr) (funType : Expr) (argType : Expr) | invalidProj (env : Environment) (lctx : LocalContext) (proj : Expr) | other (msg : String) namespace Environment /- Type check given declaration and add it to the environment -/ @[extern "lean_add_decl"] constant addDecl (env : Environment) (decl : @& Declaration) : Except KernelException Environment := arbitrary _ /- Compile the given declaration, it assumes the declaration has already been added to the environment using `addDecl`. -/ @[extern "lean_compile_decl"] constant compileDecl (env : Environment) (opt : @& Options) (decl : @& Declaration) : Except KernelException Environment := arbitrary _ def addAndCompile (env : Environment) (opt : Options) (decl : Declaration) : Except KernelException Environment := do env ← addDecl env decl; compileDecl env opt decl end Environment /- "Raw" environment extension. TODO: mark opaque. -/ structure EnvExtension (σ : Type) := (idx : Nat) (mkInitial : IO σ) (stateInh : σ) namespace EnvExtension unsafe def setStateUnsafe {σ : Type} (ext : EnvExtension σ) (env : Environment) (s : σ) : Environment := { extensions := env.extensions.set! ext.idx (unsafeCast s), .. env } @[implementedBy setStateUnsafe] constant setState {σ : Type} (ext : EnvExtension σ) (env : Environment) (s : σ) : Environment := arbitrary _ unsafe def getStateUnsafe {σ : Type} (ext : EnvExtension σ) (env : Environment) : σ := let s : EnvExtensionState := env.extensions.get! ext.idx; @unsafeCast _ _ ⟨ext.stateInh⟩ s @[implementedBy getStateUnsafe] constant getState {σ : Type} (ext : EnvExtension σ) (env : Environment) : σ := ext.stateInh @[inline] unsafe def modifyStateUnsafe {σ : Type} (ext : EnvExtension σ) (env : Environment) (f : σ → σ) : Environment := { extensions := env.extensions.modify ext.idx $ fun s => let s : σ := (@unsafeCast _ _ ⟨ext.stateInh⟩ s); let s : σ := f s; unsafeCast s, .. env } @[implementedBy modifyStateUnsafe] constant modifyState {σ : Type} (ext : EnvExtension σ) (env : Environment) (f : σ → σ) : Environment := arbitrary _ end EnvExtension private def mkEnvExtensionsRef : IO (IO.Ref (Array (EnvExtension EnvExtensionState))) := IO.mkRef #[] @[init mkEnvExtensionsRef] private constant envExtensionsRef : IO.Ref (Array (EnvExtension EnvExtensionState)) := arbitrary _ instance EnvExtension.Inhabited (σ : Type) [Inhabited σ] : Inhabited (EnvExtension σ) := ⟨{ idx := 0, stateInh := arbitrary _, mkInitial := arbitrary _ }⟩ unsafe def registerEnvExtensionUnsafe {σ : Type} [Inhabited σ] (mkInitial : IO σ) : IO (EnvExtension σ) := do initializing ← IO.initializing; unless initializing $ throw (IO.userError ("failed to register environment, extensions can only be registered during initialization")); exts ← envExtensionsRef.get; let idx := exts.size; let ext : EnvExtension σ := { idx := idx, mkInitial := mkInitial, stateInh := arbitrary _ }; envExtensionsRef.modify (fun exts => exts.push (unsafeCast ext)); pure ext /- Environment extensions can only be registered during initialization. Reasons: 1- Our implementation assumes the number of extensions does not change after an environment object is created. 2- We do not use any synchronization primitive to access `envExtensionsRef`. -/ @[implementedBy registerEnvExtensionUnsafe] constant registerEnvExtension {σ : Type} [Inhabited σ] (mkInitial : IO σ) : IO (EnvExtension σ) := arbitrary _ private def mkInitialExtensionStates : IO (Array EnvExtensionState) := do exts ← envExtensionsRef.get; exts.mapM $ fun ext => ext.mkInitial @[export lean_mk_empty_environment] def mkEmptyEnvironment (trustLevel : UInt32 := 0) : IO Environment := do initializing ← IO.initializing; when initializing $ throw (IO.userError "environment objects cannot be created during initialization"); exts ← mkInitialExtensionStates; pure { const2ModIdx := {}, constants := {}, header := { trustLevel := trustLevel }, extensions := exts } structure PersistentEnvExtensionState (α : Type) (σ : Type) := (importedEntries : Array (Array α)) -- entries per imported module (state : σ) /- An environment extension with support for storing/retrieving entries from a .olean file. - α is the type of the entries that are stored in .olean files. - β is the type of values used to update the state. - σ is the actual state. Remark: for most extensions α and β coincide. Note that `addEntryFn` is not in `IO`. This is intentional, and allows us to write simple functions such as ``` def addAlias (env : Environment) (a : Name) (e : Name) : Environment := aliasExtension.addEntry env (a, e) ``` without using `IO`. We have many functions like `addAlias`. `α` and ‵β` do not coincide for extensions where the data used to update the state contains, for example, closures which we currently cannot store in files. -/ structure PersistentEnvExtension (α : Type) (β : Type) (σ : Type) extends EnvExtension (PersistentEnvExtensionState α σ) := (name : Name) (addImportedFn : Environment → Array (Array α) → IO σ) (addEntryFn : σ → β → σ) (exportEntriesFn : σ → Array α) (statsFn : σ → Format) /- Opaque persistent environment extension entry. It is essentially a C `void *` TODO: mark opaque -/ def EnvExtensionEntry := NonScalar instance EnvExtensionEntry.inhabited : Inhabited EnvExtensionEntry := inferInstanceAs (Inhabited NonScalar) instance PersistentEnvExtensionState.inhabited {α σ} [Inhabited σ] : Inhabited (PersistentEnvExtensionState α σ) := ⟨{importedEntries := #[], state := arbitrary _ }⟩ instance PersistentEnvExtension.inhabited {α β σ} [Inhabited σ] : Inhabited (PersistentEnvExtension α β σ) := ⟨{ toEnvExtension := { idx := 0, stateInh := arbitrary _, mkInitial := arbitrary _ }, name := arbitrary _, addImportedFn := fun _ _ => arbitrary _, addEntryFn := fun s _ => s, exportEntriesFn := fun _ => #[], statsFn := fun _ => Format.nil }⟩ namespace PersistentEnvExtension def getModuleEntries {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) (m : ModuleIdx) : Array α := (ext.toEnvExtension.getState env).importedEntries.get! m def addEntry {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) (b : β) : Environment := ext.toEnvExtension.modifyState env $ fun s => let state := ext.addEntryFn s.state b; { state := state, .. s } def getState {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) : σ := (ext.toEnvExtension.getState env).state def setState {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) (s : σ) : Environment := ext.toEnvExtension.modifyState env $ fun ps => { state := s, .. ps } def modifyState {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) (f : σ → σ) : Environment := ext.toEnvExtension.modifyState env $ fun ps => { state := f (ps.state), .. ps } end PersistentEnvExtension private def mkPersistentEnvExtensionsRef : IO (IO.Ref (Array (PersistentEnvExtension EnvExtensionEntry EnvExtensionEntry EnvExtensionState))) := IO.mkRef #[] @[init mkPersistentEnvExtensionsRef] private constant persistentEnvExtensionsRef : IO.Ref (Array (PersistentEnvExtension EnvExtensionEntry EnvExtensionEntry EnvExtensionState)) := arbitrary _ structure PersistentEnvExtensionDescr (α β σ : Type) := (name : Name) (mkInitial : IO σ) (addImportedFn : Environment → Array (Array α) → IO σ) (addEntryFn : σ → β → σ) (exportEntriesFn : σ → Array α) (statsFn : σ → Format := fun _ => Format.nil) unsafe def registerPersistentEnvExtensionUnsafe {α β σ : Type} [Inhabited σ] (descr : PersistentEnvExtensionDescr α β σ) : IO (PersistentEnvExtension α β σ) := do pExts ← persistentEnvExtensionsRef.get; when (pExts.any (fun ext => ext.name == descr.name)) $ throw (IO.userError ("invalid environment extension, '" ++ toString descr.name ++ "' has already been used")); ext ← registerEnvExtension $ do { initial ← descr.mkInitial; let s : PersistentEnvExtensionState α σ := { importedEntries := #[], state := initial }; pure s }; let pExt : PersistentEnvExtension α β σ := { toEnvExtension := ext, name := descr.name, addImportedFn := descr.addImportedFn, addEntryFn := descr.addEntryFn, exportEntriesFn := descr.exportEntriesFn, statsFn := descr.statsFn }; persistentEnvExtensionsRef.modify $ fun pExts => pExts.push (unsafeCast pExt); pure pExt @[implementedBy registerPersistentEnvExtensionUnsafe] constant registerPersistentEnvExtension {α β σ : Type} [Inhabited σ] (descr : PersistentEnvExtensionDescr α β σ) : IO (PersistentEnvExtension α β σ) := arbitrary _ /- Simple PersistentEnvExtension that implements exportEntriesFn using a list of entries. -/ def SimplePersistentEnvExtension (α σ : Type) := PersistentEnvExtension α α (List α × σ) @[specialize] def mkStateFromImportedEntries {α σ : Type} (addEntryFn : σ → α → σ) (initState : σ) (as : Array (Array α)) : σ := as.foldl (fun r es => es.foldl (fun r e => addEntryFn r e) r) initState structure SimplePersistentEnvExtensionDescr (α σ : Type) := (name : Name) (addEntryFn : σ → α → σ) (addImportedFn : Array (Array α) → σ) (toArrayFn : List α → Array α := fun es => es.toArray) def registerSimplePersistentEnvExtension {α σ : Type} [Inhabited σ] (descr : SimplePersistentEnvExtensionDescr α σ) : IO (SimplePersistentEnvExtension α σ) := registerPersistentEnvExtension { name := descr.name, mkInitial := pure ([], descr.addImportedFn #[]), addImportedFn := fun _ as => pure ([], descr.addImportedFn as), addEntryFn := fun s e => match s with | (entries, s) => (e::entries, descr.addEntryFn s e), exportEntriesFn := fun s => descr.toArrayFn s.1.reverse, statsFn := fun s => format "number of local entries: " ++ format s.1.length } namespace SimplePersistentEnvExtension instance {α σ : Type} [Inhabited σ] : Inhabited (SimplePersistentEnvExtension α σ) := inferInstanceAs (Inhabited (PersistentEnvExtension α α (List α × σ))) def getEntries {α σ : Type} (ext : SimplePersistentEnvExtension α σ) (env : Environment) : List α := (PersistentEnvExtension.getState ext env).1 def getState {α σ : Type} (ext : SimplePersistentEnvExtension α σ) (env : Environment) : σ := (PersistentEnvExtension.getState ext env).2 def setState {α σ : Type} (ext : SimplePersistentEnvExtension α σ) (env : Environment) (s : σ) : Environment := PersistentEnvExtension.modifyState ext env (fun ⟨entries, _⟩ => (entries, s)) def modifyState {α σ : Type} (ext : SimplePersistentEnvExtension α σ) (env : Environment) (f : σ → σ) : Environment := PersistentEnvExtension.modifyState ext env (fun ⟨entries, s⟩ => (entries, f s)) end SimplePersistentEnvExtension /-- Environment extension for tagging declarations. Declarations must only be tagged in the module where they were declared. -/ def TagDeclarationExtension := SimplePersistentEnvExtension Name NameSet def mkTagDeclarationExtension (name : Name) : IO TagDeclarationExtension := registerSimplePersistentEnvExtension { name := name, addImportedFn := fun as => {}, addEntryFn := fun s n => s.insert n, toArrayFn := fun es => es.toArray.qsort Name.quickLt } namespace TagDeclarationExtension instance : Inhabited TagDeclarationExtension := inferInstanceAs (Inhabited (SimplePersistentEnvExtension Name NameSet)) def tag (ext : TagDeclarationExtension) (env : Environment) (n : Name) : Environment := ext.addEntry env n def isTagged (ext : TagDeclarationExtension) (env : Environment) (n : Name) : Bool := match env.getModuleIdxFor? n with | some modIdx => (ext.getModuleEntries env modIdx).binSearchContains n Name.quickLt | none => (ext.getState env).contains n end TagDeclarationExtension /- API for creating extensions in C++. This API will eventually be deleted. -/ def CPPExtensionState := NonScalar instance CPPExtensionState.inhabited : Inhabited CPPExtensionState := inferInstanceAs (Inhabited NonScalar) section /- It is not safe to use "extract closed term" optimization in the following code because of `unsafeIO`. If `compiler.extract_closed` is set to true, then the compiler will cache the result of `exts ← envExtensionsRef.get` during initialization which is incorrect. -/ set_option compiler.extract_closed false @[export lean_register_extension] unsafe def registerCPPExtension (initial : CPPExtensionState) : Option Nat := (unsafeIO (do ext ← registerEnvExtension (pure initial); pure ext.idx)).toOption @[export lean_set_extension] unsafe def setCPPExtensionState (env : Environment) (idx : Nat) (s : CPPExtensionState) : Option Environment := (unsafeIO (do exts ← envExtensionsRef.get; pure $ (exts.get! idx).setState env s)).toOption @[export lean_get_extension] unsafe def getCPPExtensionState (env : Environment) (idx : Nat) : Option CPPExtensionState := (unsafeIO (do exts ← envExtensionsRef.get; pure $ (exts.get! idx).getState env)).toOption end /- Legacy support for Modification objects -/ /- Opaque modification object. It is essentially a C `void *`. In Lean 3, a .olean file is essentially a collection of modification objects. This type represents the modification objects implemented in C++. We will eventually delete this type as soon as we port the remaining Lean 3 legacy code. TODO: mark opaque -/ def Modification := NonScalar instance Modification.inhabited : Inhabited Modification := inferInstanceAs (Inhabited NonScalar) def regModListExtension : IO (EnvExtension (List Modification)) := registerEnvExtension (pure []) @[init regModListExtension] constant modListExtension : EnvExtension (List Modification) := arbitrary _ /- The C++ code uses this function to store the given modification object into the environment. -/ @[export lean_environment_add_modification] def addModification (env : Environment) (mod : Modification) : Environment := modListExtension.modifyState env $ fun mods => mod :: mods /- mkModuleData invokes this function to convert a list of modification objects into a serialized byte array. -/ @[extern 2 "lean_serialize_modifications"] constant serializeModifications : List Modification → IO ByteArray := arbitrary _ @[extern 3 "lean_perform_serialized_modifications"] constant performModifications : Environment → ByteArray → IO Environment := arbitrary _ /- Content of a .olean file. We use `compact.cpp` to generate the image of this object in disk. -/ structure ModuleData := (imports : Array Import) (constants : Array ConstantInfo) (entries : Array (Name × Array EnvExtensionEntry)) (serialized : ByteArray) -- Legacy support: serialized modification objects instance ModuleData.inhabited : Inhabited ModuleData := ⟨{imports := arbitrary _, constants := arbitrary _, entries := arbitrary _, serialized := arbitrary _}⟩ @[extern 3 "lean_save_module_data"] constant saveModuleData (fname : @& String) (m : ModuleData) : IO Unit := arbitrary _ @[extern 2 "lean_read_module_data"] constant readModuleData (fname : @& String) : IO ModuleData := arbitrary _ def mkModuleData (env : Environment) : IO ModuleData := do pExts ← persistentEnvExtensionsRef.get; let entries : Array (Name × Array EnvExtensionEntry) := pExts.size.fold (fun i result => let state := (pExts.get! i).getState env; let exportEntriesFn := (pExts.get! i).exportEntriesFn; let extName := (pExts.get! i).name; result.push (extName, exportEntriesFn state)) #[]; bytes ← serializeModifications (modListExtension.getState env); pure { imports := env.header.imports, constants := env.constants.foldStage2 (fun cs _ c => cs.push c) #[], entries := entries, serialized := bytes } @[export lean_write_module] def writeModule (env : Environment) (fname : String) : IO Unit := do modData ← mkModuleData env; saveModuleData fname modData partial def importModulesAux : List Import → (NameSet × Array ModuleData) → IO (NameSet × Array ModuleData) | [], r => pure r | i::is, (s, mods) => if i.runtimeOnly || s.contains i.module then importModulesAux is (s, mods) else do let s := s.insert i.module; mFile ← findOLean i.module; mod ← readModuleData mFile; (s, mods) ← importModulesAux mod.imports.toList (s, mods); let mods := mods.push mod; importModulesAux is (s, mods) private partial def getEntriesFor (mod : ModuleData) (extId : Name) : Nat → Array EnvExtensionState | i => if i < mod.entries.size then let curr := mod.entries.get! i; if curr.1 == extId then curr.2 else getEntriesFor (i+1) else #[] private def setImportedEntries (env : Environment) (mods : Array ModuleData) : IO Environment := do pExtDescrs ← persistentEnvExtensionsRef.get; pure $ mods.iterate env $ fun _ mod env => pExtDescrs.iterate env $ fun _ extDescr env => let entries := getEntriesFor mod extDescr.name 0; extDescr.toEnvExtension.modifyState env $ fun s => { importedEntries := s.importedEntries.push entries, .. s } private def finalizePersistentExtensions (env : Environment) : IO Environment := do pExtDescrs ← persistentEnvExtensionsRef.get; pExtDescrs.iterateM env $ fun _ extDescr env => do let s := extDescr.toEnvExtension.getState env; newState ← extDescr.addImportedFn env s.importedEntries; pure $ extDescr.toEnvExtension.setState env { state := newState, .. s } @[export lean_import_modules] def importModules (imports : List Import) (trustLevel : UInt32 := 0) : IO Environment := do (_, mods) ← importModulesAux imports ({}, #[]); let const2ModIdx := mods.iterate {} $ fun (modIdx) (mod : ModuleData) (m : HashMap Name ModuleIdx) => mod.constants.iterate m $ fun _ cinfo m => m.insert cinfo.name modIdx.val; constants ← mods.iterateM SMap.empty $ fun _ (mod : ModuleData) (cs : ConstMap) => mod.constants.iterateM cs $ fun _ cinfo cs => do { when (cs.contains cinfo.name) $ throw (IO.userError ("import failed, environment already contains '" ++ toString cinfo.name ++ "'")); pure $ cs.insert cinfo.name cinfo }; let constants := constants.switch; exts ← mkInitialExtensionStates; let env : Environment := { const2ModIdx := const2ModIdx, constants := constants, extensions := exts, header := { quotInit := !imports.isEmpty, -- We assume `core.lean` initializes quotient module trustLevel := trustLevel, imports := imports.toArray } }; env ← setImportedEntries env mods; env ← finalizePersistentExtensions env; env ← mods.iterateM env $ fun _ mod env => performModifications env mod.serialized; pure env def regNamespacesExtension : IO (SimplePersistentEnvExtension Name NameSet) := registerSimplePersistentEnvExtension { name := `namespaces, addImportedFn := fun as => mkStateFromImportedEntries NameSet.insert {} as, addEntryFn := fun s n => s.insert n } @[init regNamespacesExtension] constant namespacesExt : SimplePersistentEnvExtension Name NameSet := arbitrary _ def registerNamespace (env : Environment) (n : Name) : Environment := if (namespacesExt.getState env).contains n then env else namespacesExt.addEntry env n def isNamespace (env : Environment) (n : Name) : Bool := (namespacesExt.getState env).contains n def getNamespaceSet (env : Environment) : NameSet := namespacesExt.getState env namespace Environment private def isNamespaceName : Name → Bool | Name.str Name.anonymous _ _ => true | Name.str p _ _ => isNamespaceName p | _ => false private def registerNamePrefixes : Environment → Name → Environment | env, Name.str p _ _ => if isNamespaceName p then registerNamePrefixes (registerNamespace env p) p else env | env, _ => env @[export lean_environment_add] def add (env : Environment) (cinfo : ConstantInfo) : Environment := let env := registerNamePrefixes env cinfo.name; env.addAux cinfo @[export lean_display_stats] def displayStats (env : Environment) : IO Unit := do pExtDescrs ← persistentEnvExtensionsRef.get; let numModules := ((pExtDescrs.get! 0).toEnvExtension.getState env).importedEntries.size; IO.println ("direct imports: " ++ toString env.header.imports); IO.println ("number of imported modules: " ++ toString numModules); IO.println ("number of consts: " ++ toString env.constants.size); IO.println ("number of imported consts: " ++ toString env.constants.stageSizes.1); IO.println ("number of local consts: " ++ toString env.constants.stageSizes.2); IO.println ("number of buckets for imported consts: " ++ toString env.constants.numBuckets); IO.println ("trust level: " ++ toString env.header.trustLevel); IO.println ("number of extensions: " ++ toString env.extensions.size); pExtDescrs.forM $ fun extDescr => do { IO.println ("extension '" ++ toString extDescr.name ++ "'"); let s := extDescr.toEnvExtension.getState env; let fmt := extDescr.statsFn s.state; unless fmt.isNil (IO.println (" " ++ toString (Format.nest 2 (extDescr.statsFn s.state)))); IO.println (" number of imported entries: " ++ toString (s.importedEntries.foldl (fun sum es => sum + es.size) 0)); pure () }; pure () @[extern "lean_eval_const"] unsafe constant evalConst (α) (env : @& Environment) (constName : @& Name) : Except String α := arbitrary _ end Environment /- Helper functions for accessing environment -/ @[inline] def matchConst {α : Type} (env : Environment) (e : Expr) (failK : Unit → α) (k : ConstantInfo → List Level → α) : α := match e with | Expr.const n lvls _ => match env.find? n with | some cinfo => k cinfo lvls | _ => failK () | _ => failK () end Lean
6171cfd8baff2dab52ab70150e56c24b0afb3a02
845976968546725c9fa2976823b4102f4827056d
/src/problem_sheets/sheet_1/sht01Q01.lean
f803e080b0296f93934a4656d1f3870953838f89
[ "Apache-2.0" ]
permissive
PatrickMassot/M1P1-lean
37b2f56af7ce9765dbef1940062487914eb3b712
4000dc5f449020e4f1a4820fc807383a3df42d85
refs/heads/master
1,587,280,512,253
1,548,801,138,000
1,548,801,138,000
168,042,050
0
0
null
1,548,711,613,000
1,548,711,613,000
null
UTF-8
Lean
false
false
1,757
lean
-- This import gives us a working copy of the real numbers ℝ, -- and functions such as abs : ℝ → ℝ import data.real.basic -- This next import gives us several tactics of use to mathematicians: -- (1) norm_num [to prove basic facts about reals like 2+2 = 4] -- (2) ring [to prove basic algebra identities like (a+b)^2 = a^2+2ab+b^2] -- (3) linarith [to prove basic inequalities like x > 0 -> x/2 > 0] import tactic.linarith -- These lines switch Lean into "maths proof mode" -- don't worry about them. -- Basically they tell Lean to use the axiom of choice and the -- law of the excluded middle, two standard maths facts. noncomputable theory local attribute [instance, priority 0] classical.prop_decidable -- the maths starts here. -- We introduce the usual mathematical notation for absolute value local notation `|` x `|` := abs x theorem Q1a (x y : ℝ) : | x + y | ≤ | x | + | y | := begin -- Lean's definition of abs is abs x = max (x, -x) -- [or max x (-x), as the computer scientists would write it] unfold abs, -- lean's definition of max a b is "if a<=b then b else a" unfold max, -- We now have a complicated statement with three "if"s in. split_ifs, -- We now have 2^3=8 goals corresponding to all the possibilities -- x>=0/x<0, y>=0/y<0, (x+y)>=0/(x+y)<0. repeat {linarith}, -- all of them are easily solvable using the linarith tactic. end -- Example of how to apply this theorem Q1h (x y z : ℝ) : | x - y | ≤ | z - y | + | z - x | := calc | x - y | = | (z - y) + (x - z) | : by ring ... ≤ | z - y | + | x - z | : by refine Q1a _ _ -- applying triangle inequality ... = | z - y | + | -(x - z) | : by rw abs_neg -- this lemma says |-x| = |x| ... = | z - y | + | z - x | : by simp
c68f55aaeb2529f42fe01d54e39cddd470a13c89
f083c4ed5d443659f3ed9b43b1ca5bb037ddeb58
/group_theory/subgroup.lean
80a5c25aef375fe81dda62e8458f7914ff776c07
[ "Apache-2.0" ]
permissive
semorrison/mathlib
1be6f11086e0d24180fec4b9696d3ec58b439d10
20b4143976dad48e664c4847b75a85237dca0a89
refs/heads/master
1,583,799,212,170
1,535,634,130,000
1,535,730,505,000
129,076,205
0
0
Apache-2.0
1,551,697,998,000
1,523,442,265,000
Lean
UTF-8
Lean
false
false
15,211
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mitchell Rowett, Scott Morrison, Johan Commelin, Mario Carneiro -/ import group_theory.submonoid open set function variables {α : Type*} {β : Type*} {a a₁ a₂ b c: α} section group variables [group α] [add_group β] @[to_additive injective_add] lemma injective_mul {a : α} : injective ((*) a) := assume a₁ a₂ h, have a⁻¹ * a * a₁ = a⁻¹ * a * a₂, by rw [mul_assoc, mul_assoc, h], by rwa [inv_mul_self, one_mul, one_mul] at this /-- `s` is a subgroup: a set containing 1 and closed under multiplication and inverse. -/ class is_subgroup (s : set α) extends is_submonoid s : Prop := (inv_mem {a} : a ∈ s → a⁻¹ ∈ s) /-- `s` is an additive subgroup: a set containing 0 and closed under addition and negation. -/ class is_add_subgroup (s : set β) extends is_add_submonoid s : Prop := (neg_mem {a} : a ∈ s → -a ∈ s) attribute [to_additive is_add_subgroup] is_subgroup attribute [to_additive is_add_subgroup.to_is_add_submonoid] is_subgroup.to_is_submonoid attribute [to_additive is_add_subgroup.neg_mem] is_subgroup.inv_mem attribute [to_additive is_add_subgroup.mk] is_subgroup.mk instance additive.is_add_subgroup (s : set α) [is_subgroup s] : @is_add_subgroup (additive α) _ s := ⟨@is_subgroup.inv_mem _ _ _ _⟩ theorem additive.is_add_subgroup_iff {s : set α} : @is_add_subgroup (additive α) _ s ↔ is_subgroup s := ⟨by rintro ⟨⟨h₁, h₂⟩, h₃⟩; exact @is_subgroup.mk α _ _ ⟨h₁, @h₂⟩ @h₃, λ h, by resetI; apply_instance⟩ instance multiplicative.is_subgroup (s : set β) [is_add_subgroup s] : @is_subgroup (multiplicative β) _ s := ⟨@is_add_subgroup.neg_mem _ _ _ _⟩ theorem multiplicative.is_subgroup_iff {s : set β} : @is_subgroup (multiplicative β) _ s ↔ is_add_subgroup s := ⟨by rintro ⟨⟨h₁, h₂⟩, h₃⟩; exact @is_add_subgroup.mk β _ _ ⟨h₁, @h₂⟩ @h₃, λ h, by resetI; apply_instance⟩ instance subtype.group {s : set α} [is_subgroup s] : group s := { inv := λa, ⟨(a.1)⁻¹, is_subgroup.inv_mem a.2⟩, mul_left_inv := λa, subtype.eq $ mul_left_inv _, .. subtype.monoid } instance subtype.add_group {s : set β} [is_add_subgroup s] : add_group s := { neg := λa, ⟨-(a.1), is_add_subgroup.neg_mem a.2⟩, add_left_neg := λa, subtype.eq $ add_left_neg _, .. subtype.add_monoid } attribute [to_additive subtype.add_group] subtype.group theorem is_subgroup.of_div (s : set α) (one_mem : (1:α) ∈ s) (div_mem : ∀{a b:α}, a ∈ s → b ∈ s → a * b⁻¹ ∈ s): is_subgroup s := have inv_mem : ∀a, a ∈ s → a⁻¹ ∈ s, from assume a ha, have 1 * a⁻¹ ∈ s, from div_mem one_mem ha, by simpa, { inv_mem := inv_mem, mul_mem := assume a b ha hb, have a * b⁻¹⁻¹ ∈ s, from div_mem ha (inv_mem b hb), by simpa, one_mem := one_mem } theorem is_add_subgroup.of_sub (s : set β) (zero_mem : (0:β) ∈ s) (sub_mem : ∀{a b:β}, a ∈ s → b ∈ s → a - b ∈ s): is_add_subgroup s := multiplicative.is_subgroup_iff.1 $ @is_subgroup.of_div (multiplicative β) _ _ zero_mem @sub_mem def gpowers (x : α) : set α := {y | ∃i:ℤ, x^i = y} def gmultiples (x : β) : set β := {y | ∃i:ℤ, gsmul i x = y} attribute [to_additive gmultiples] gpowers instance gpowers.is_subgroup (x : α) : is_subgroup (gpowers x) := { one_mem := ⟨(0:ℤ), by simp⟩, mul_mem := assume x₁ x₂ ⟨i₁, h₁⟩ ⟨i₂, h₂⟩, ⟨i₁ + i₂, by simp [gpow_add, *]⟩, inv_mem := assume x₀ ⟨i, h⟩, ⟨-i, by simp [h.symm]⟩ } instance gmultiples.is_add_subgroup (x : β) : is_add_subgroup (gmultiples x) := multiplicative.is_subgroup_iff.1 $ gpowers.is_subgroup _ attribute [to_additive gmultiples.is_add_subgroup] gpowers.is_subgroup lemma is_subgroup.gpow_mem {a : α} {s : set α} [is_subgroup s] (h : a ∈ s) : ∀{i:ℤ}, a ^ i ∈ s | (n : ℕ) := is_submonoid.pow_mem h | -[1+ n] := is_subgroup.inv_mem (is_submonoid.pow_mem h) lemma is_add_subgroup.gsmul_mem {a : β} {s : set β} [is_add_subgroup s] : a ∈ s → ∀{i:ℤ}, gsmul i a ∈ s := @is_subgroup.gpow_mem (multiplicative β) _ _ _ _ lemma mem_gpowers {a : α} : a ∈ gpowers a := ⟨1, by simp⟩ lemma mem_gmultiples {a : β} : a ∈ gmultiples a := ⟨1, by simp⟩ attribute [to_additive mem_gmultiples] mem_gpowers end group namespace is_subgroup open is_submonoid variables [group α] (s : set α) [is_subgroup s] @[to_additive is_add_subgroup.neg_mem_iff] lemma inv_mem_iff : a⁻¹ ∈ s ↔ a ∈ s := ⟨λ h, by simpa using inv_mem h, inv_mem⟩ @[to_additive is_add_subgroup.add_mem_cancel_left] lemma mul_mem_cancel_left (h : a ∈ s) : b * a ∈ s ↔ b ∈ s := ⟨λ hba, by simpa using mul_mem hba (inv_mem h), λ hb, mul_mem hb h⟩ @[to_additive is_add_subgroup.add_mem_cancel_right] lemma mul_mem_cancel_right (h : a ∈ s) : a * b ∈ s ↔ b ∈ s := ⟨λ hab, by simpa using mul_mem (inv_mem h) hab, mul_mem h⟩ end is_subgroup namespace group open is_submonoid is_subgroup variables [group α] {s : set α} inductive in_closure (s : set α) : α → Prop | basic {a : α} : a ∈ s → in_closure a | one : in_closure 1 | inv {a : α} : in_closure a → in_closure a⁻¹ | mul {a b : α} : in_closure a → in_closure b → in_closure (a * b) /-- `group.closure s` is the subgroup closed over `s`, i.e. the smallest subgroup containg s. -/ def closure (s : set α) : set α := {a | in_closure s a } lemma mem_closure {a : α} : a ∈ s → a ∈ closure s := in_closure.basic instance closure.is_subgroup (s : set α) : is_subgroup (closure s) := { one_mem := in_closure.one s, mul_mem := assume a b, in_closure.mul, inv_mem := assume a, in_closure.inv } theorem subset_closure {s : set α} : s ⊆ closure s := λ a, mem_closure theorem closure_subset {s t : set α} [is_subgroup t] (h : s ⊆ t) : closure s ⊆ t := assume a ha, by induction ha; simp [h _, *, one_mem, mul_mem, inv_mem_iff] theorem gpowers_eq_closure {a : α} : gpowers a = closure {a} := subset.antisymm (assume x h, match x, h with _, ⟨i, rfl⟩ := gpow_mem (mem_closure $ by simp) end) (closure_subset $ by simp [mem_gpowers]) end group namespace add_group open is_add_submonoid is_add_subgroup variables [add_group α] {s : set α} /-- `add_group.closure s` is the additive subgroup closed over `s`, i.e. the smallest subgroup containg s. -/ def closure (s : set α) : set α := @group.closure (multiplicative α) _ s attribute [to_additive add_group.closure] group.closure lemma mem_closure {a : α} : a ∈ s → a ∈ closure s := group.mem_closure attribute [to_additive add_group.mem_closure] group.mem_closure instance closure.is_add_subgroup (s : set α) : is_add_subgroup (closure s) := multiplicative.is_subgroup_iff.1 $ group.closure.is_subgroup _ attribute [to_additive add_group.closure.is_add_subgroup] group.closure.is_subgroup attribute [to_additive add_group.subset_closure] group.subset_closure theorem closure_subset {s t : set α} [is_add_subgroup t] : s ⊆ t → closure s ⊆ t := group.closure_subset attribute [to_additive add_group.closure_subset] group.closure_subset theorem gmultiples_eq_closure {a : α} : gmultiples a = closure {a} := group.gpowers_eq_closure attribute [to_additive add_group.gmultiples_eq_closure] group.gpowers_eq_closure end add_group class normal_subgroup [group α] (s : set α) extends is_subgroup s : Prop := (normal : ∀ n ∈ s, ∀ g : α, g * n * g⁻¹ ∈ s) class normal_add_subgroup [add_group α] (s : set α) extends is_add_subgroup s : Prop := (normal : ∀ n ∈ s, ∀ g : α, g + n - g ∈ s) attribute [to_additive normal_add_subgroup] normal_subgroup attribute [to_additive normal_add_subgroup.to_is_add_subgroup] normal_subgroup.to_is_subgroup attribute [to_additive normal_add_subgroup.normal] normal_subgroup.normal attribute [to_additive normal_add_subgroup.mk] normal_subgroup.mk @[to_additive normal_add_subgroup_of_add_comm_group] lemma normal_subgroup_of_comm_group [comm_group α] (s : set α) [hs : is_subgroup s] : normal_subgroup s := { normal := λ n hn g, by rwa [mul_right_comm, mul_right_inv, one_mul], ..hs } instance additive.normal_add_subgroup [group α] (s : set α) [normal_subgroup s] : @normal_add_subgroup (additive α) _ s := ⟨@normal_subgroup.normal _ _ _ _⟩ theorem additive.normal_add_subgroup_iff [group α] {s : set α} : @normal_add_subgroup (additive α) _ s ↔ normal_subgroup s := ⟨by rintro ⟨h₁, h₂⟩; exact @normal_subgroup.mk α _ _ (additive.is_add_subgroup_iff.1 h₁) @h₂, λ h, by resetI; apply_instance⟩ instance multiplicative.normal_subgroup [add_group α] (s : set α) [normal_add_subgroup s] : @normal_subgroup (multiplicative α) _ s := ⟨@normal_add_subgroup.normal _ _ _ _⟩ theorem multiplicative.normal_subgroup_iff [add_group α] {s : set α} : @normal_subgroup (multiplicative α) _ s ↔ normal_add_subgroup s := ⟨by rintro ⟨h₁, h₂⟩; exact @normal_add_subgroup.mk α _ _ (multiplicative.is_subgroup_iff.1 h₁) @h₂, λ h, by resetI; apply_instance⟩ namespace is_subgroup variable [group α] -- Normal subgroup properties lemma mem_norm_comm {s : set α} [normal_subgroup s] {a b : α} (hab : a * b ∈ s) : b * a ∈ s := have h : a⁻¹ * (a * b) * a⁻¹⁻¹ ∈ s, from normal_subgroup.normal (a * b) hab a⁻¹, by simp at h; exact h lemma mem_norm_comm_iff {s : set α} [normal_subgroup s] {a b : α} : a * b ∈ s ↔ b * a ∈ s := ⟨mem_norm_comm, mem_norm_comm⟩ /-- The trivial subgroup -/ def trivial (α : Type*) [group α] : set α := {1} @[simp] lemma mem_trivial [group α] {g : α} : g ∈ trivial α ↔ g = 1 := mem_singleton_iff instance trivial_normal : normal_subgroup (trivial α) := by refine {..}; simp [trivial] {contextual := tt} lemma trivial_eq_closure : trivial α = group.closure ∅ := subset.antisymm (by simp [set.subset_def, is_submonoid.one_mem]) (group.closure_subset $ by simp) instance univ_subgroup : normal_subgroup (@univ α) := by refine {..}; simp def center (α : Type*) [group α] : set α := {z | ∀ g, g * z = z * g} lemma mem_center {a : α} : a ∈ center α ↔ ∀g, g * a = a * g := iff.rfl instance center_normal : normal_subgroup (center α) := { one_mem := by simp [center], mul_mem := assume a b ha hb g, by rw [←mul_assoc, mem_center.2 ha g, mul_assoc, mem_center.2 hb g, ←mul_assoc], inv_mem := assume a ha g, calc g * a⁻¹ = a⁻¹ * (g * a) * a⁻¹ : by simp [ha g] ... = a⁻¹ * g : by rw [←mul_assoc, mul_assoc]; simp, normal := assume n ha g h, calc h * (g * n * g⁻¹) = h * n : by simp [ha g, mul_assoc] ... = g * g⁻¹ * n * h : by rw ha h; simp ... = g * n * g⁻¹ * h : by rw [mul_assoc g, ha g⁻¹, ←mul_assoc] } end is_subgroup namespace is_add_subgroup variable [add_group α] attribute [to_additive is_add_subgroup.mem_norm_comm] is_subgroup.mem_norm_comm attribute [to_additive is_add_subgroup.mem_norm_comm_iff] is_subgroup.mem_norm_comm_iff /-- The trivial subgroup -/ def trivial (α : Type*) [add_group α] : set α := {0} attribute [to_additive is_add_subgroup.trivial] is_subgroup.trivial attribute [to_additive is_add_subgroup.mem_trivial] is_subgroup.mem_trivial instance trivial_normal : normal_add_subgroup (trivial α) := multiplicative.normal_subgroup_iff.1 is_subgroup.trivial_normal attribute [to_additive is_add_subgroup.trivial_normal] is_subgroup.trivial_normal attribute [to_additive is_add_subgroup.trivial_eq_closure] is_subgroup.trivial_eq_closure instance univ_add_subgroup : normal_add_subgroup (@univ α) := multiplicative.normal_subgroup_iff.1 is_subgroup.univ_subgroup attribute [to_additive is_add_subgroup.univ_add_subgroup] is_subgroup.univ_subgroup def center (α : Type*) [add_group α] : set α := {z | ∀ g, g + z = z + g} attribute [to_additive is_add_subgroup.center] is_subgroup.center attribute [to_additive is_add_subgroup.mem_center] is_subgroup.mem_center instance center_normal : normal_add_subgroup (center α) := multiplicative.normal_subgroup_iff.1 is_subgroup.center_normal end is_add_subgroup -- Homomorphism subgroups namespace is_group_hom open is_submonoid is_subgroup variables [group α] [group β] def ker (f : α → β) [is_group_hom f] : set α := preimage f (trivial β) lemma mem_ker (f : α → β) [is_group_hom f] {x : α} : x ∈ ker f ↔ f x = 1 := mem_trivial lemma one_ker_inv (f : α → β) [is_group_hom f] {a b : α} (h : f (a * b⁻¹) = 1) : f a = f b := begin rw [mul f, inv f] at h, rw [←inv_inv (f b), eq_inv_of_mul_eq_one h] end lemma inv_ker_one (f : α → β) [is_group_hom f] {a b : α} (h : f a = f b) : f (a * b⁻¹) = 1 := have f a * (f b)⁻¹ = 1, by rw [h, mul_right_inv], by rwa [←inv f, ←mul f] at this lemma one_iff_ker_inv (f : α → β) [is_group_hom f] (a b : α) : f a = f b ↔ f (a * b⁻¹) = 1 := ⟨inv_ker_one f, one_ker_inv f⟩ lemma inv_iff_ker (f : α → β) [w : is_group_hom f] (a b : α) : f a = f b ↔ a * b⁻¹ ∈ ker f := by rw [mem_ker]; exact one_iff_ker_inv _ _ _ instance image_subgroup (f : α → β) [is_group_hom f] (s : set α) [is_subgroup s] : is_subgroup (f '' s) := { mul_mem := assume a₁ a₂ ⟨b₁, hb₁, eq₁⟩ ⟨b₂, hb₂, eq₂⟩, ⟨b₁ * b₂, mul_mem hb₁ hb₂, by simp [eq₁, eq₂, mul f]⟩, one_mem := ⟨1, one_mem s, one f⟩, inv_mem := assume a ⟨b, hb, eq⟩, ⟨b⁻¹, inv_mem hb, by rw inv f; simp *⟩ } instance range_subgroup (f : α → β) [is_group_hom f] : is_subgroup (set.range f) := @set.image_univ _ _ f ▸ is_group_hom.image_subgroup f set.univ local attribute [simp] one_mem inv_mem mul_mem normal_subgroup.normal instance preimage (f : α → β) [is_group_hom f] (s : set β) [is_subgroup s] : is_subgroup (f ⁻¹' s) := by refine {..}; simp [mul f, one f, inv f, @inv_mem β _ s] {contextual:=tt} instance preimage_normal (f : α → β) [is_group_hom f] (s : set β) [normal_subgroup s] : normal_subgroup (f ⁻¹' s) := ⟨by simp [mul f, inv f] {contextual:=tt}⟩ instance normal_subgroup_ker (f : α → β) [is_group_hom f] : normal_subgroup (ker f) := is_group_hom.preimage_normal f (trivial β) lemma inj_of_trivial_ker (f : α → β) [is_group_hom f] (h : ker f = trivial α) : function.injective f := begin intros a₁ a₂ hfa, simp [ext_iff, ker, is_subgroup.trivial] at h, have ha : a₁ * a₂⁻¹ = 1, by rw ←h; exact inv_ker_one f hfa, rw [eq_inv_of_mul_eq_one ha, inv_inv a₂] end lemma trivial_ker_of_inj (f : α → β) [is_group_hom f] (h : function.injective f) : ker f = trivial α := set.ext $ assume x, iff.intro (assume hx, suffices f x = f 1, by simpa using h this, by simp [one f]; rwa [mem_ker] at hx) (by simp [mem_ker, is_group_hom.one f] {contextual := tt}) lemma inj_iff_trivial_ker (f : α → β) [is_group_hom f] : function.injective f ↔ ker f = trivial α := ⟨trivial_ker_of_inj f, inj_of_trivial_ker f⟩ end is_group_hom
f2e044b8a0ce58c691ac0fca877ffd4345ef4b83
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/data/mv_polynomial/cardinal.lean
2d1b7b0fbda670df20622e36d3df96b3f7e9639b
[ "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
4,380
lean
/- Copyright (c) 2021 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import data.W.cardinal import data.mv_polynomial.basic /-! # Cardinality of Polynomial Ring The main result in this file is `mv_polynomial.cardinal_mk_le_max`, which says that the cardinality of `mv_polynomial σ R` is bounded above by the maximum of `#R`, `#σ` and `ω`. -/ universes u /- The definitions `mv_polynomial_fun` and `arity` are motivated by defining the following inductive type as a `W_type` in order to be able to use theorems about the cardinality of `W_type`. inductive mv_polynomial_term (σ R : Type u) : Type u | of_ring : R → mv_polynomial_term | X : σ → mv_polynomial_term | add : mv_polynomial_term → mv_polynomial_term → mv_polynomial_term | mul : mv_polynomial_term → mv_polynomial_term → mv_polynomial_term `W_type (arity σ R)` is isomorphic to the above type. -/ open cardinal open_locale cardinal /-- A type used to prove theorems about the cardinality of `mv_polynomial σ R`. The `W_type (arity σ R)` has a constant for every element of `R` and `σ` and two binary functions. -/ private def mv_polynomial_fun (σ R : Type u) : Type u := R ⊕ σ ⊕ ulift.{u} bool variables (σ R : Type u) /-- A function used to prove theorems about the cardinality of `mv_polynomial σ R`. The type ``W_type (arity σ R)` has a constant for every element of `R` and `σ` and two binary functions. -/ private def arity : mv_polynomial_fun σ R → Type u | (sum.inl _) := pempty | (sum.inr (sum.inl _)) := pempty | (sum.inr (sum.inr ⟨ff⟩)) := ulift bool | (sum.inr (sum.inr ⟨tt⟩)) := ulift bool private def arity_fintype (x : mv_polynomial_fun σ R) : fintype (arity σ R x) := by rcases x with x | x | ⟨_ | _⟩; dsimp [arity]; apply_instance local attribute [instance] arity_fintype variables {σ R} variables [comm_semiring R] /-- The surjection from `W_type (arity σ R)` into `mv_polynomial σ R`. -/ private noncomputable def to_mv_polynomial : W_type (arity σ R) → mv_polynomial σ R | ⟨sum.inl r, _⟩ := mv_polynomial.C r | ⟨sum.inr (sum.inl i), _⟩ := mv_polynomial.X i | ⟨sum.inr (sum.inr ⟨ff⟩), f⟩ := to_mv_polynomial (f (ulift.up tt)) * to_mv_polynomial (f (ulift.up ff)) | ⟨sum.inr (sum.inr ⟨tt⟩), f⟩ := to_mv_polynomial (f (ulift.up tt)) + to_mv_polynomial (f (ulift.up ff)) private lemma to_mv_polynomial_surjective : function.surjective (@to_mv_polynomial σ R _) := begin intro p, induction p using mv_polynomial.induction_on with x p₁ p₂ ih₁ ih₂ p i ih, { exact ⟨W_type.mk (sum.inl x) pempty.elim, rfl⟩ }, { rcases ih₁ with ⟨w₁, rfl⟩, rcases ih₂ with ⟨w₂, rfl⟩, exact ⟨W_type.mk (sum.inr (sum.inr ⟨tt⟩)) (λ x, cond x.down w₁ w₂), by simp [to_mv_polynomial]⟩ }, { rcases ih with ⟨w, rfl⟩, exact ⟨W_type.mk (sum.inr (sum.inr ⟨ff⟩)) (λ x, cond x.down w (W_type.mk (sum.inr (sum.inl i)) pempty.elim)), by simp [to_mv_polynomial]⟩ } end private lemma cardinal_mv_polynomial_fun_le : #(mv_polynomial_fun σ R) ≤ max (max (#R) (#σ)) ω := calc #(mv_polynomial_fun σ R) = #R + #σ + #(ulift bool) : by dsimp [mv_polynomial_fun]; simp only [← add_def, add_assoc, cardinal.mk_ulift] ... ≤ max (max (#R + #σ) (#(ulift bool))) ω : add_le_max _ _ ... ≤ max (max (max (max (#R) (#σ)) ω) (#(ulift bool))) ω : max_le_max (max_le_max (add_le_max _ _) (le_refl _)) (le_refl _) ... ≤ _ : begin have : #(ulift.{u} bool) ≤ ω, from le_of_lt (lt_omega_iff_fintype.2 ⟨infer_instance⟩), simp only [max_comm omega.{u}, max_assoc, max_left_comm omega.{u}, max_self, max_eq_left this], end namespace mv_polynomial /-- The cardinality of the multivariate polynomial ring, `mv_polynomial σ R` is at most the maximum of `#R`, `#σ` and `ω` -/ lemma cardinal_mk_le_max {σ R : Type u} [comm_semiring R] : #(mv_polynomial σ R) ≤ max (max (#R) (#σ)) ω := calc #(mv_polynomial σ R) ≤ #(W_type (arity σ R)) : cardinal.mk_le_of_surjective to_mv_polynomial_surjective ... ≤ max (#(mv_polynomial_fun σ R)) ω : W_type.cardinal_mk_le_max_omega_of_fintype ... ≤ _ : max_le_max cardinal_mv_polynomial_fun_le (le_refl _) ... ≤ _ : by simp only [max_assoc, max_self] end mv_polynomial
60ed8ea0fcbc842b9ca05a0fcc0502f8e3c58688
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/808.lean
7d53c9751adc6088ef38e6dc5d77e25126a06b00
[ "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
195
lean
notation 1 := eq postfix `x`:(max+1) := eq postfix [priority 1] `y`:max := eq definition foo [instance] [priority 1] : inhabited nat := inhabited.mk nat.zero definition bar [unfold 1] := @eq
48b4e528f5b79bb6bcb2ff099e9b653ce422ddaf
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/trace.lean
16c1701797e600683768e220d887c7ab3383a4b8
[ "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,572
lean
import Lean.CoreM open Lean structure MyState := (trace_state : TraceState := {}) (s : Nat := 0) abbrev M := CoreM def tst1 : M Unit := do trace[module] (m!"hello" ++ MessageData.nest 9 (m!"\n" ++ "world")); trace[module.aux] "another message"; pure () def tst2 (b : Bool) : M Unit := withTraceNode `module (fun _ => return "message") do tst1; trace[bughunt] "at test2"; if b then throwError "error"; tst1; pure () partial def ack : Nat → Nat → Nat | 0, n => n+1 | m+1, 0 => ack m 1 | m+1, n+1 => ack m (ack (m+1) n) def slow (b : Bool) : Nat := ack 4 (cond b 0 1) def tst3 (b : Bool) : M Unit := do withTraceNode `module.slow (fun _ => return m!"slow: {slow b}") do { tst2 b; tst1 }; trace[bughunt] "at end of tst3"; -- Messages are computed lazily. The following message will only be computed -- if `trace.slow is active. trace[slow] (m!"slow message: " ++ toString (slow b)) -- This is true even if it is a monad computation: trace[slow] (m!"slow message: " ++ (← pure (toString (slow b)))) def run (x : M Unit) : M Unit := withReader (fun ctx => -- Try commeting/uncommeting the following `setBool`s let opts := ctx.options; let opts := opts.setBool `trace.module true; -- let opts := opts.setBool `trace.module.aux false; let opts := opts.setBool `trace.bughunt true; -- let opts := opts.setBool `trace.slow true; { ctx with options := opts }) (tryCatch (tryFinally x printTraces) (fun _ => IO.println "ERROR")) #eval run (tst3 true) #eval run (tst3 false)
f98c55a56de58fa74b46da92becfeb539228e67b
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/category_theory/comma.lean
b14457530f44c421b0261be6ea339ee4c2abb1ee
[ "Apache-2.0" ]
permissive
kmill/mathlib
ea5a007b67ae4e9e18dd50d31d8aa60f650425ee
1a419a9fea7b959317eddd556e1bb9639f4dcc05
refs/heads/master
1,668,578,197,719
1,593,629,163,000
1,593,629,163,000
276,482,939
0
0
null
1,593,637,960,000
1,593,637,959,000
null
UTF-8
Lean
false
false
17,358
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Johan Commelin, Bhavik Mehta -/ import category_theory.punit import category_theory.reflect_isomorphisms /-! # Comma categories A comma category is a construction in category theory, which builds a category out of two functors with a common codomain. Specifically, for functors `L : A ⥤ T` and `R : B ⥤ T`, an object in `comma L R` is a morphism `hom : L.obj left ⟶ R.obj right` for some objects `left : A` and `right : B`, and a morphism in `comma L R` between `hom : L.obj left ⟶ R.obj right` and `hom' : L.obj left' ⟶ R.obj right'` is a commutative square L.obj left ⟶ L.obj left' | | hom | | hom' ↓ ↓ R.obj right ⟶ R.obj right', where the top and bottom morphism come from morphisms `left ⟶ left'` and `right ⟶ right'`, respectively. Several important constructions are special cases of this construction. * If `L` is the identity functor and `R` is a constant functor, then `comma L R` is the "slice" or "over" category over the object `R` maps to. * Conversely, if `L` is a constant functor and `R` is the identity functor, then `comma L R` is the "coslice" or "under" category under the object `L` maps to. * If `L` and `R` both are the identity functor, then `comma L R` is the arrow category of `T`. ## Main definitions * `comma L R`: the comma category of the functors `L` and `R`. * `over X`: the over category of the object `X`. * `under X`: the under category of the object `X`. * `arrow T`: the arrow category of the category `T`. ## References * https://ncatlab.org/nlab/show/comma+category ## Tags comma, slice, coslice, over, under, arrow -/ namespace category_theory universes v₁ v₂ v₃ u₁ u₂ u₃ -- declare the `v`'s first; see `category_theory.category` for an explanation variables {A : Type u₁} [category.{v₁} A] variables {B : Type u₂} [category.{v₂} B] variables {T : Type u₃} [category.{v₃} T] /-- The objects of the comma category are triples of an object `left : A`, an object `right : B` and a morphism `hom : L.obj left ⟶ R.obj right`. -/ structure comma (L : A ⥤ T) (R : B ⥤ T) : Type (max u₁ u₂ v₃) := (left : A . obviously) (right : B . obviously) (hom : L.obj left ⟶ R.obj right) -- Satisfying the inhabited linter instance comma.inhabited [inhabited T] : inhabited (comma (𝟭 T) (𝟭 T)) := { default := { left := default T, right := default T, hom := 𝟙 (default T) } } variables {L : A ⥤ T} {R : B ⥤ T} /-- A morphism between two objects in the comma category is a commutative square connecting the morphisms coming from the two objects using morphisms in the image of the functors `L` and `R`. -/ @[ext] structure comma_morphism (X Y : comma L R) := (left : X.left ⟶ Y.left . obviously) (right : X.right ⟶ Y.right . obviously) (w' : L.map left ≫ Y.hom = X.hom ≫ R.map right . obviously) -- Satisfying the inhabited linter instance comma_morphism.inhabited [inhabited (comma L R)] : inhabited (comma_morphism (default (comma L R)) (default (comma L R))) := { default := { left := 𝟙 _, right := 𝟙 _ } } restate_axiom comma_morphism.w' attribute [simp, reassoc] comma_morphism.w instance comma_category : category (comma L R) := { hom := comma_morphism, id := λ X, { left := 𝟙 X.left, right := 𝟙 X.right }, comp := λ X Y Z f g, { left := f.left ≫ g.left, right := f.right ≫ g.right } } namespace comma section variables {X Y Z : comma L R} {f : X ⟶ Y} {g : Y ⟶ Z} @[simp] lemma id_left : ((𝟙 X) : comma_morphism X X).left = 𝟙 X.left := rfl @[simp] lemma id_right : ((𝟙 X) : comma_morphism X X).right = 𝟙 X.right := rfl @[simp] lemma comp_left : (f ≫ g).left = f.left ≫ g.left := rfl @[simp] lemma comp_right : (f ≫ g).right = f.right ≫ g.right := rfl end variables (L) (R) /-- The functor sending an object `X` in the comma category to `X.left`. -/ @[simps] def fst : comma L R ⥤ A := { obj := λ X, X.left, map := λ _ _ f, f.left } /-- The functor sending an object `X` in the comma category to `X.right`. -/ @[simps] def snd : comma L R ⥤ B := { obj := λ X, X.right, map := λ _ _ f, f.right } /-- We can interpret the commutative square constituting a morphism in the comma category as a natural transformation between the functors `fst ⋙ L` and `snd ⋙ R` from the comma category to `T`, where the components are given by the morphism that constitutes an object of the comma category. -/ @[simps] def nat_trans : fst L R ⋙ L ⟶ snd L R ⋙ R := { app := λ X, X.hom } section variables {L₁ L₂ L₃ : A ⥤ T} {R₁ R₂ R₃ : B ⥤ T} /-- A natural transformation `L₁ ⟶ L₂` induces a functor `comma L₂ R ⥤ comma L₁ R`. -/ @[simps] def map_left (l : L₁ ⟶ L₂) : comma L₂ R ⥤ comma L₁ R := { obj := λ X, { left := X.left, right := X.right, hom := l.app X.left ≫ X.hom }, map := λ X Y f, { left := f.left, right := f.right } } /-- The functor `comma L R ⥤ comma L R` induced by the identity natural transformation on `L` is naturally isomorphic to the identity functor. -/ @[simps] def map_left_id : map_left R (𝟙 L) ≅ 𝟭 _ := { hom := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } }, inv := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } } } /-- The functor `comma L₁ R ⥤ comma L₃ R` induced by the composition of two natural transformations `l : L₁ ⟶ L₂` and `l' : L₂ ⟶ L₃` is naturally isomorphic to the composition of the two functors induced by these natural transformations. -/ @[simps] def map_left_comp (l : L₁ ⟶ L₂) (l' : L₂ ⟶ L₃) : (map_left R (l ≫ l')) ≅ (map_left R l') ⋙ (map_left R l) := { hom := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } }, inv := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } } } /-- A natural transformation `R₁ ⟶ R₂` induces a functor `comma L R₁ ⥤ comma L R₂`. -/ @[simps] def map_right (r : R₁ ⟶ R₂) : comma L R₁ ⥤ comma L R₂ := { obj := λ X, { left := X.left, right := X.right, hom := X.hom ≫ r.app X.right }, map := λ X Y f, { left := f.left, right := f.right } } /-- The functor `comma L R ⥤ comma L R` induced by the identity natural transformation on `R` is naturally isomorphic to the identity functor. -/ @[simps] def map_right_id : map_right L (𝟙 R) ≅ 𝟭 _ := { hom := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } }, inv := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } } } /-- The functor `comma L R₁ ⥤ comma L R₃` induced by the composition of the natural transformations `r : R₁ ⟶ R₂` and `r' : R₂ ⟶ R₃` is naturally isomorphic to the composition of the functors induced by these natural transformations. -/ @[simps] def map_right_comp (r : R₁ ⟶ R₂) (r' : R₂ ⟶ R₃) : (map_right L (r ≫ r')) ≅ (map_right L r) ⋙ (map_right L r') := { hom := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } }, inv := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } } } end end comma /-- The over category has as objects arrows in `T` with codomain `X` and as morphisms commutative triangles. -/ @[derive category] def over (X : T) := comma.{v₃ 0 v₃} (𝟭 T) (functor.from_punit X) -- Satisfying the inhabited linter instance over.inhabited [inhabited T] : inhabited (over (default T)) := { default := { left := default T, hom := 𝟙 _ } } namespace over variables {X : T} @[ext] lemma over_morphism.ext {X : T} {U V : over X} {f g : U ⟶ V} (h : f.left = g.left) : f = g := by tidy @[simp] lemma over_right (U : over X) : U.right = punit.star := by tidy -- @[simp] lemma over_morphism_right {U V : over X} (f : U ⟶ V) : f.right = sorry := -- begin -- end @[simp] lemma id_left (U : over X) : comma_morphism.left (𝟙 U) = 𝟙 U.left := rfl @[simp] lemma comp_left (a b c : over X) (f : a ⟶ b) (g : b ⟶ c) : (f ≫ g).left = f.left ≫ g.left := rfl @[simp, reassoc] lemma w {A B : over X} (f : A ⟶ B) : f.left ≫ B.hom = A.hom := by have := f.w; tidy /-- To give an object in the over category, it suffices to give a morphism with codomain `X`. -/ def mk {X Y : T} (f : Y ⟶ X) : over X := { left := Y, hom := f } @[simp] lemma mk_left {X Y : T} (f : Y ⟶ X) : (mk f).left = Y := rfl @[simp] lemma mk_hom {X Y : T} (f : Y ⟶ X) : (mk f).hom = f := rfl /-- To give a morphism in the over category, it suffices to give an arrow fitting in a commutative triangle. -/ @[simps] def hom_mk {U V : over X} (f : U.left ⟶ V.left) (w : f ≫ V.hom = U.hom . obviously) : U ⟶ V := { left := f } /-- The forgetful functor mapping an arrow to its domain. -/ def forget : (over X) ⥤ T := comma.fst _ _ @[simp] lemma forget_obj {U : over X} : forget.obj U = U.left := rfl @[simp] lemma forget_map {U V : over X} {f : U ⟶ V} : forget.map f = f.left := rfl /-- A morphism `f : X ⟶ Y` induces a functor `over X ⥤ over Y` in the obvious way. -/ def map {Y : T} (f : X ⟶ Y) : over X ⥤ over Y := comma.map_right _ $ discrete.nat_trans (λ _, f) section variables {Y : T} {f : X ⟶ Y} {U V : over X} {g : U ⟶ V} @[simp] lemma map_obj_left : ((map f).obj U).left = U.left := rfl @[simp] lemma map_obj_hom : ((map f).obj U).hom = U.hom ≫ f := rfl @[simp] lemma map_map_left : ((map f).map g).left = g.left := rfl end instance forget_reflects_iso : reflects_isomorphisms (forget : over X ⥤ T) := { reflects := λ X Y f t, by exactI { inv := over.hom_mk t.inv ((as_iso (forget.map f)).inv_comp_eq.2 (over.w f).symm) } } section iterated_slice variables (f : over X) /-- Given f : Y ⟶ X, this is the obvious functor from (T/X)/f to T/Y -/ @[simps] def iterated_slice_forward : over f ⥤ over f.left := { obj := λ α, over.mk α.hom.left, map := λ α β κ, over.hom_mk κ.left.left (by { rw auto_param_eq, rw ← over.w κ, refl }) } /-- Given f : Y ⟶ X, this is the obvious functor from T/Y to (T/X)/f -/ @[simps] def iterated_slice_backward : over f.left ⥤ over f := { obj := λ g, mk (hom_mk g.hom : mk (g.hom ≫ f.hom) ⟶ f), map := λ g h α, hom_mk (hom_mk α.left (w_assoc α f.hom)) (over_morphism.ext (w α)) } /-- Given f : Y ⟶ X, we have an equivalence between (T/X)/f and T/Y -/ @[simps] def iterated_slice_equiv : over f ≌ over f.left := { functor := iterated_slice_forward f, inverse := iterated_slice_backward f, unit_iso := nat_iso.of_components (λ g, ⟨hom_mk (hom_mk (𝟙 g.left.left)) (by apply_auto_param), hom_mk (hom_mk (𝟙 g.left.left)) (by apply_auto_param), by { ext, dsimp, simp }, by { ext, dsimp, simp }⟩) (λ X Y g, by { ext, dsimp, simp }), counit_iso := nat_iso.of_components (λ g, ⟨hom_mk (𝟙 g.left) (by apply_auto_param), hom_mk (𝟙 g.left) (by apply_auto_param), by { ext, dsimp, simp }, by { ext, dsimp, simp }⟩) (λ X Y g, by { ext, dsimp, simp }) } lemma iterated_slice_forward_forget : iterated_slice_forward f ⋙ forget = forget ⋙ forget := rfl lemma iterated_slice_backward_forget_forget : iterated_slice_backward f ⋙ forget ⋙ forget = forget := rfl end iterated_slice section variables {D : Type u₃} [category.{v₃} D] /-- A functor `F : T ⥤ D` induces a functor `over X ⥤ over (F.obj X)` in the obvious way. -/ def post (F : T ⥤ D) : over X ⥤ over (F.obj X) := { obj := λ Y, mk $ F.map Y.hom, map := λ Y₁ Y₂ f, { left := F.map f.left, w' := by tidy; erw [← F.map_comp, w] } } end end over /-- The under category has as objects arrows with domain `X` and as morphisms commutative triangles. -/ @[derive category] def under (X : T) := comma.{0 v₃ v₃} (functor.from_punit X) (𝟭 T) -- Satisfying the inhabited linter instance under.inhabited [inhabited T] : inhabited (under (default T)) := { default := { right := default T, hom := 𝟙 _ } } namespace under variables {X : T} @[ext] lemma under_morphism.ext {X : T} {U V : under X} {f g : U ⟶ V} (h : f.right = g.right) : f = g := by tidy @[simp] lemma under_left (U : under X) : U.left = punit.star := by tidy @[simp] lemma id_right (U : under X) : comma_morphism.right (𝟙 U) = 𝟙 U.right := rfl @[simp] lemma comp_right (a b c : under X) (f : a ⟶ b) (g : b ⟶ c) : (f ≫ g).right = f.right ≫ g.right := rfl @[simp] lemma w {A B : under X} (f : A ⟶ B) : A.hom ≫ f.right = B.hom := by have := f.w; tidy /-- To give an object in the under category, it suffices to give an arrow with domain `X`. -/ @[simps] def mk {X Y : T} (f : X ⟶ Y) : under X := { right := Y, hom := f } /-- To give a morphism in the under category, it suffices to give a morphism fitting in a commutative triangle. -/ @[simps] def hom_mk {U V : under X} (f : U.right ⟶ V.right) (w : U.hom ≫ f = V.hom . obviously) : U ⟶ V := { right := f } /-- The forgetful functor mapping an arrow to its domain. -/ def forget : (under X) ⥤ T := comma.snd _ _ @[simp] lemma forget_obj {U : under X} : forget.obj U = U.right := rfl @[simp] lemma forget_map {U V : under X} {f : U ⟶ V} : forget.map f = f.right := rfl /-- A morphism `X ⟶ Y` induces a functor `under Y ⥤ under X` in the obvious way. -/ def map {Y : T} (f : X ⟶ Y) : under Y ⥤ under X := comma.map_left _ $ discrete.nat_trans (λ _, f) section variables {Y : T} {f : X ⟶ Y} {U V : under Y} {g : U ⟶ V} @[simp] lemma map_obj_right : ((map f).obj U).right = U.right := rfl @[simp] lemma map_obj_hom : ((map f).obj U).hom = f ≫ U.hom := rfl @[simp] lemma map_map_right : ((map f).map g).right = g.right := rfl end section variables {D : Type u₃} [category.{v₃} D] /-- A functor `F : T ⥤ D` induces a functor `under X ⥤ under (F.obj X)` in the obvious way. -/ def post {X : T} (F : T ⥤ D) : under X ⥤ under (F.obj X) := { obj := λ Y, mk $ F.map Y.hom, map := λ Y₁ Y₂ f, { right := F.map f.right, w' := by tidy; erw [← F.map_comp, w] } } end end under section variables (T) /-- The arrow category of `T` has as objects all morphisms in `T` and as morphisms commutative squares in `T`. -/ @[derive category] def arrow := comma.{v₃ v₃ v₃} (𝟭 T) (𝟭 T) -- Satisfying the inhabited linter instance arrow.inhabited [inhabited T] : inhabited (arrow T) := { default := show comma (𝟭 T) (𝟭 T), from default (comma (𝟭 T) (𝟭 T)) } end namespace arrow @[simp] lemma id_left (f : arrow T) : comma_morphism.left (𝟙 f) = 𝟙 (f.left) := rfl @[simp] lemma id_right (f : arrow T) : comma_morphism.right (𝟙 f) = 𝟙 (f.right) := rfl /-- An object in the arrow category is simply a morphism in `T`. -/ @[simps] def mk {X Y : T} (f : X ⟶ Y) : arrow T := { left := X, right := Y, hom := f } /-- A morphism in the arrow category is a commutative square connecting two objects of the arrow category. -/ @[simps] def hom_mk {f g : arrow T} {u : f.left ⟶ g.left} {v : f.right ⟶ g.right} (w : u ≫ g.hom = f.hom ≫ v) : f ⟶ g := { left := u, right := v, w' := w } /-- We can also build a morphism in the arrow category out of any commutative square in `T`. -/ @[simps] def hom_mk' {X Y : T} {f : X ⟶ Y} {P Q : T} {g : P ⟶ Q} {u : X ⟶ P} {v : Y ⟶ Q} (w : u ≫ g = f ≫ v) : arrow.mk f ⟶ arrow.mk g := { left := u, right := v, w' := w } @[reassoc] lemma w {f g : arrow T} (sq : f ⟶ g) : sq.left ≫ g.hom = f.hom ≫ sq.right := sq.w /-- A lift of a commutative square is a diagonal morphism making the two triangles commute. -/ @[ext] class has_lift {f g : arrow T} (sq : f ⟶ g) := (lift : f.right ⟶ g.left) (fac_left : f.hom ≫ lift = sq.left) (fac_right : lift ≫ g.hom = sq.right) attribute [simp, reassoc] has_lift.fac_left has_lift.fac_right /-- If we have chosen a lift of a commutative square `sq`, we can access it by saying `lift sq`. -/ abbreviation lift {f g : arrow T} (sq : f ⟶ g) [has_lift sq] : f.right ⟶ g.left := has_lift.lift sq lemma lift.fac_left {f g : arrow T} (sq : f ⟶ g) [has_lift sq] : f.hom ≫ lift sq = sq.left := by simp lemma lift.fac_right {f g : arrow T} (sq : f ⟶ g) [has_lift sq] : lift sq ≫ g.hom = sq.right := by simp @[simp, reassoc] lemma lift_mk'_left {X Y P Q : T} {f : X ⟶ Y} {g : P ⟶ Q} {u : X ⟶ P} {v : Y ⟶ Q} (h : u ≫ g = f ≫ v) [has_lift $ arrow.hom_mk' h] : f ≫ lift (arrow.hom_mk' h) = u := by simp only [←arrow.mk_hom f, lift.fac_left, arrow.hom_mk'_left] @[simp, reassoc] lemma lift_mk'_right {X Y P Q : T} {f : X ⟶ Y} {g : P ⟶ Q} {u : X ⟶ P} {v : Y ⟶ Q} (h : u ≫ g = f ≫ v) [has_lift $ arrow.hom_mk' h] : lift (arrow.hom_mk' h) ≫ g = v := by simp only [←arrow.mk_hom g, lift.fac_right, arrow.hom_mk'_right] section instance subsingleton_has_lift_of_epi {f g : arrow T} (sq : f ⟶ g) [epi f.hom] : subsingleton (has_lift sq) := subsingleton.intro $ λ a b, has_lift.ext a b $ (cancel_epi f.hom).1 $ by simp instance subsingleton_has_lift_of_mono {f g : arrow T} (sq : f ⟶ g) [mono g.hom] : subsingleton (has_lift sq) := subsingleton.intro $ λ a b, has_lift.ext a b $ (cancel_mono g.hom).1 $ by simp end end arrow end category_theory
c8238d68e3ab60c5e5215d652967ffc1365f06c1
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/src/Init/Control/Option.lean
af1dac4aa51844374aa564b7bc37252b99ef4771
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,879
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ prelude import Init.Data.Option.Basic import Init.Control.Basic import Init.Control.Except universes u v instance {α} : ToBool (Option α) := ⟨Option.toBool⟩ def OptionT (m : Type u → Type v) (α : Type u) : Type v := m (Option α) @[inline] def OptionT.run {m : Type u → Type v} {α : Type u} (x : OptionT m α) : m (Option α) := x namespace OptionT variable {m : Type u → Type v} [Monad m] {α β : Type u} @[inline] protected def bind (x : OptionT m α) (f : α → OptionT m β) : OptionT m β := id (α := m (Option β)) do match (← x) with | some a => f a | none => pure none @[inline] protected def pure (a : α) : OptionT m α := id (α := m (Option α)) do pure (some a) instance : Monad (OptionT m) := { pure := OptionT.pure bind := OptionT.bind } @[inline] protected def orElse (x : OptionT m α) (y : OptionT m α) : OptionT m α := id (α := m (Option α)) do match (← x) with | some a => pure (some a) | _ => y @[inline] protected def fail : OptionT m α := id (α := m (Option α)) do pure none instance : Alternative (OptionT m) := { failure := OptionT.fail orElse := OptionT.orElse } @[inline] protected def lift (x : m α) : OptionT m α := id (α := m (Option α)) do return some (← x) instance : MonadLift m (OptionT m) := ⟨OptionT.lift⟩ instance : MonadFunctor m (OptionT m) := ⟨fun f x => f x⟩ @[inline] protected def tryCatch (x : OptionT m α) (handle : Unit → OptionT m α) : OptionT m α := id (α := m (Option α)) do let some a ← x | handle () pure a instance : MonadExceptOf Unit (OptionT m) := { throw := fun _ => OptionT.fail tryCatch := OptionT.tryCatch } end OptionT
2b839101eb9b6d6d28f162cb9bc44f7f0f641cb2
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/data/real/cau_seq.lean
11b8b99907912ae996695d195e93f029d58a5bc0
[ "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
23,703
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import algebra.order.absolute_value import algebra.big_operators.order /-! # Cauchy sequences A basic theory of Cauchy sequences, used in the construction of the reals and p-adic numbers. Where applicable, lemmas that will be reused in other contexts have been stated in extra generality. There are other "versions" of Cauchyness in the library, in particular Cauchy filters in topology. This is a concrete implementation that is useful for simplicity and computability reasons. ## Important definitions * `is_cau_seq`: a predicate that says `f : ℕ → β` is Cauchy. * `cau_seq`: the type of Cauchy sequences valued in type `β` with respect to an absolute value function `abv`. ## Tags sequence, cauchy, abs val, absolute value -/ open_locale big_operators open is_absolute_value theorem exists_forall_ge_and {α} [linear_order α] {P Q : α → Prop} : (∃ i, ∀ j ≥ i, P j) → (∃ i, ∀ j ≥ i, Q j) → ∃ i, ∀ j ≥ i, P j ∧ Q j | ⟨a, h₁⟩ ⟨b, h₂⟩ := let ⟨c, ac, bc⟩ := exists_ge_of_linear a b in ⟨c, λ j hj, ⟨h₁ _ (le_trans ac hj), h₂ _ (le_trans bc hj)⟩⟩ section variables {α : Type*} [linear_ordered_field α] {β : Type*} [ring β] (abv : β → α) [is_absolute_value abv] theorem rat_add_continuous_lemma {ε : α} (ε0 : 0 < ε) : ∃ δ > 0, ∀ {a₁ a₂ b₁ b₂ : β}, abv (a₁ - b₁) < δ → abv (a₂ - b₂) < δ → abv (a₁ + a₂ - (b₁ + b₂)) < ε := ⟨ε / 2, half_pos ε0, λ a₁ a₂ b₁ b₂ h₁ h₂, by simpa [add_halves, sub_eq_add_neg, add_comm, add_left_comm, add_assoc] using lt_of_le_of_lt (abv_add abv _ _) (add_lt_add h₁ h₂)⟩ theorem rat_mul_continuous_lemma {ε K₁ K₂ : α} (ε0 : 0 < ε) : ∃ δ > 0, ∀ {a₁ a₂ b₁ b₂ : β}, abv a₁ < K₁ → abv b₂ < K₂ → abv (a₁ - b₁) < δ → abv (a₂ - b₂) < δ → abv (a₁ * a₂ - b₁ * b₂) < ε := begin have K0 : (0 : α) < max 1 (max K₁ K₂) := lt_of_lt_of_le zero_lt_one (le_max_left _ _), have εK := div_pos (half_pos ε0) K0, refine ⟨_, εK, λ a₁ a₂ b₁ b₂ ha₁ hb₂ h₁ h₂, _⟩, replace ha₁ := lt_of_lt_of_le ha₁ (le_trans (le_max_left _ K₂) (le_max_right 1 _)), replace hb₂ := lt_of_lt_of_le hb₂ (le_trans (le_max_right K₁ _) (le_max_right 1 _)), have := add_lt_add (mul_lt_mul' (le_of_lt h₁) hb₂ (abv_nonneg abv _) εK) (mul_lt_mul' (le_of_lt h₂) ha₁ (abv_nonneg abv _) εK), rw [← abv_mul abv, mul_comm, div_mul_cancel _ (ne_of_gt K0), ← abv_mul abv, add_halves] at this, simpa [mul_add, add_mul, sub_eq_add_neg, add_comm, add_left_comm] using lt_of_le_of_lt (abv_add abv _ _) this end theorem rat_inv_continuous_lemma {β : Type*} [field β] (abv : β → α) [is_absolute_value abv] {ε K : α} (ε0 : 0 < ε) (K0 : 0 < K) : ∃ δ > 0, ∀ {a b : β}, K ≤ abv a → K ≤ abv b → abv (a - b) < δ → abv (a⁻¹ - b⁻¹) < ε := begin have KK := mul_pos K0 K0, have εK := mul_pos ε0 KK, refine ⟨_, εK, λ a b ha hb h, _⟩, have a0 := lt_of_lt_of_le K0 ha, have b0 := lt_of_lt_of_le K0 hb, rw [inv_sub_inv ((abv_pos abv).1 a0) ((abv_pos abv).1 b0), abv_div abv, abv_mul abv, mul_comm, abv_sub abv, ← mul_div_cancel ε (ne_of_gt KK)], exact div_lt_div h (mul_le_mul hb ha (le_of_lt K0) (abv_nonneg abv _)) (le_of_lt $ mul_pos ε0 KK) KK end end /-- A sequence is Cauchy if the distance between its entries tends to zero. -/ def is_cau_seq {α : Type*} [linear_ordered_field α] {β : Type*} [ring β] (abv : β → α) (f : ℕ → β) : Prop := ∀ ε > 0, ∃ i, ∀ j ≥ i, abv (f j - f i) < ε namespace is_cau_seq variables {α : Type*} [linear_ordered_field α] {β : Type*} [ring β] {abv : β → α} [is_absolute_value abv] {f : ℕ → β} @[nolint ge_or_gt] -- see Note [nolint_ge] theorem cauchy₂ (hf : is_cau_seq abv f) {ε : α} (ε0 : 0 < ε) : ∃ i, ∀ j k ≥ i, abv (f j - f k) < ε := begin refine (hf _ (half_pos ε0)).imp (λ i hi j k ij ik, _), rw ← add_halves ε, refine lt_of_le_of_lt (abv_sub_le abv _ _ _) (add_lt_add (hi _ ij) _), rw abv_sub abv, exact hi _ ik end theorem cauchy₃ (hf : is_cau_seq abv f) {ε : α} (ε0 : 0 < ε) : ∃ i, ∀ j ≥ i, ∀ k ≥ j, abv (f k - f j) < ε := let ⟨i, H⟩ := hf.cauchy₂ ε0 in ⟨i, λ j ij k jk, H _ _ (le_trans ij jk) ij⟩ end is_cau_seq /-- `cau_seq β abv` is the type of `β`-valued Cauchy sequences, with respect to the absolute value function `abv`. -/ def cau_seq {α : Type*} [linear_ordered_field α] (β : Type*) [ring β] (abv : β → α) : Type* := {f : ℕ → β // is_cau_seq abv f} namespace cau_seq variables {α : Type*} [linear_ordered_field α] section ring variables {β : Type*} [ring β] {abv : β → α} instance : has_coe_to_fun (cau_seq β abv) (λ _, ℕ → β) := ⟨subtype.val⟩ @[simp] theorem mk_to_fun (f) (hf : is_cau_seq abv f) : @coe_fn (cau_seq β abv) _ _ ⟨f, hf⟩ = f := rfl theorem ext {f g : cau_seq β abv} (h : ∀ i, f i = g i) : f = g := subtype.eq (funext h) theorem is_cau (f : cau_seq β abv) : is_cau_seq abv f := f.2 theorem cauchy (f : cau_seq β abv) : ∀ {ε}, 0 < ε → ∃ i, ∀ j ≥ i, abv (f j - f i) < ε := f.2 /-- Given a Cauchy sequence `f`, create a Cauchy sequence from a sequence `g` with the same values as `f`. -/ def of_eq (f : cau_seq β abv) (g : ℕ → β) (e : ∀ i, f i = g i) : cau_seq β abv := ⟨g, λ ε, by rw [show g = f, from (funext e).symm]; exact f.cauchy⟩ variable [is_absolute_value abv] @[nolint ge_or_gt] -- see Note [nolint_ge] theorem cauchy₂ (f : cau_seq β abv) {ε} : 0 < ε → ∃ i, ∀ j k ≥ i, abv (f j - f k) < ε := f.2.cauchy₂ theorem cauchy₃ (f : cau_seq β abv) {ε} : 0 < ε → ∃ i, ∀ j ≥ i, ∀ k ≥ j, abv (f k - f j) < ε := f.2.cauchy₃ theorem bounded (f : cau_seq β abv) : ∃ r, ∀ i, abv (f i) < r := begin cases f.cauchy zero_lt_one with i h, let R := ∑ j in finset.range (i+1), abv (f j), have : ∀ j ≤ i, abv (f j) ≤ R, { intros j ij, change (λ j, abv (f j)) j ≤ R, apply finset.single_le_sum, { intros, apply abv_nonneg abv }, { rwa [finset.mem_range, nat.lt_succ_iff] } }, refine ⟨R + 1, λ j, _⟩, cases lt_or_le j i with ij ij, { exact lt_of_le_of_lt (this _ (le_of_lt ij)) (lt_add_one _) }, { have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add_of_le_of_lt (this _ (le_refl _)) (h _ ij)), rw [add_sub, add_comm] at this, simpa } end theorem bounded' (f : cau_seq β abv) (x : α) : ∃ r > x, ∀ i, abv (f i) < r := let ⟨r, h⟩ := f.bounded in ⟨max r (x+1), lt_of_lt_of_le (lt_add_one _) (le_max_right _ _), λ i, lt_of_lt_of_le (h i) (le_max_left _ _)⟩ instance : has_add (cau_seq β abv) := ⟨λ f g, ⟨λ i, (f i + g i : β), λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_add_continuous_lemma abv ε0, ⟨i, H⟩ := exists_forall_ge_and (f.cauchy₃ δ0) (g.cauchy₃ δ0) in ⟨i, λ j ij, let ⟨H₁, H₂⟩ := H _ (le_refl _) in Hδ (H₁ _ ij) (H₂ _ ij)⟩⟩⟩ @[simp] theorem add_apply (f g : cau_seq β abv) (i : ℕ) : (f + g) i = f i + g i := rfl variable (abv) /-- The constant Cauchy sequence. -/ def const (x : β) : cau_seq β abv := ⟨λ i, x, λ ε ε0, ⟨0, λ j ij, by simpa [abv_zero abv] using ε0⟩⟩ variable {abv} local notation `const` := const abv @[simp] theorem const_apply (x : β) (i : ℕ) : (const x : ℕ → β) i = x := rfl theorem const_inj {x y : β} : (const x : cau_seq β abv) = const y ↔ x = y := ⟨λ h, congr_arg (λ f:cau_seq β abv, (f:ℕ→β) 0) h, congr_arg _⟩ instance : has_zero (cau_seq β abv) := ⟨const 0⟩ instance : has_one (cau_seq β abv) := ⟨const 1⟩ instance : inhabited (cau_seq β abv) := ⟨0⟩ @[simp] theorem zero_apply (i) : (0 : cau_seq β abv) i = 0 := rfl @[simp] theorem one_apply (i) : (1 : cau_seq β abv) i = 1 := rfl @[simp] theorem const_zero : const 0 = 0 := rfl theorem const_add (x y : β) : const (x + y) = const x + const y := ext $ λ i, rfl instance : has_mul (cau_seq β abv) := ⟨λ f g, ⟨λ i, (f i * g i : β), λ ε ε0, let ⟨F, F0, hF⟩ := f.bounded' 0, ⟨G, G0, hG⟩ := g.bounded' 0, ⟨δ, δ0, Hδ⟩ := rat_mul_continuous_lemma abv ε0, ⟨i, H⟩ := exists_forall_ge_and (f.cauchy₃ δ0) (g.cauchy₃ δ0) in ⟨i, λ j ij, let ⟨H₁, H₂⟩ := H _ (le_refl _) in Hδ (hF j) (hG i) (H₁ _ ij) (H₂ _ ij)⟩⟩⟩ @[simp] theorem mul_apply (f g : cau_seq β abv) (i : ℕ) : (f * g) i = f i * g i := rfl theorem const_mul (x y : β) : const (x * y) = const x * const y := ext $ λ i, rfl instance : has_neg (cau_seq β abv) := ⟨λ f, of_eq (const (-1) * f) (λ x, -f x) (λ i, by simp)⟩ @[simp] theorem neg_apply (f : cau_seq β abv) (i) : (-f) i = -f i := rfl theorem const_neg (x : β) : const (-x) = -const x := ext $ λ i, rfl instance : has_sub (cau_seq β abv) := ⟨λ f g, of_eq (f + -g) (λ x, f x - g x) (λ i, by simp [sub_eq_add_neg])⟩ @[simp] theorem sub_apply (f g : cau_seq β abv) (i : ℕ) : (f - g) i = f i - g i := rfl theorem const_sub (x y : β) : const (x - y) = const x - const y := ext $ λ i, rfl instance : ring (cau_seq β abv) := by refine_struct { neg := has_neg.neg, add := (+), zero := (0 : cau_seq β abv), mul := (*), one := 1, sub := has_sub.sub, npow := @npow_rec (cau_seq β abv) ⟨1⟩ ⟨(*)⟩, nsmul := @nsmul_rec (cau_seq β abv) ⟨0⟩ ⟨(+)⟩, zsmul := @zsmul_rec (cau_seq β abv) ⟨0⟩ ⟨(+)⟩ ⟨has_neg.neg⟩ }; intros; try { refl }; apply ext; simp [mul_add, mul_assoc, add_mul, add_comm, add_left_comm, sub_eq_add_neg] instance {β : Type*} [comm_ring β] {abv : β → α} [is_absolute_value abv] : comm_ring (cau_seq β abv) := { mul_comm := by intros; apply ext; simp [mul_left_comm, mul_comm], ..cau_seq.ring } /-- `lim_zero f` holds when `f` approaches 0. -/ def lim_zero {abv : β → α} (f : cau_seq β abv) : Prop := ∀ ε > 0, ∃ i, ∀ j ≥ i, abv (f j) < ε theorem add_lim_zero {f g : cau_seq β abv} (hf : lim_zero f) (hg : lim_zero g) : lim_zero (f + g) | ε ε0 := (exists_forall_ge_and (hf _ $ half_pos ε0) (hg _ $ half_pos ε0)).imp $ λ i H j ij, let ⟨H₁, H₂⟩ := H _ ij in by simpa [add_halves ε] using lt_of_le_of_lt (abv_add abv _ _) (add_lt_add H₁ H₂) theorem mul_lim_zero_right (f : cau_seq β abv) {g} (hg : lim_zero g) : lim_zero (f * g) | ε ε0 := let ⟨F, F0, hF⟩ := f.bounded' 0 in (hg _ $ div_pos ε0 F0).imp $ λ i H j ij, by have := mul_lt_mul' (le_of_lt $ hF j) (H _ ij) (abv_nonneg abv _) F0; rwa [mul_comm F, div_mul_cancel _ (ne_of_gt F0), ← abv_mul abv] at this theorem mul_lim_zero_left {f} (g : cau_seq β abv) (hg : lim_zero f) : lim_zero (f * g) | ε ε0 := let ⟨G, G0, hG⟩ := g.bounded' 0 in (hg _ $ div_pos ε0 G0).imp $ λ i H j ij, by have := mul_lt_mul'' (H _ ij) (hG j) (abv_nonneg abv _) (abv_nonneg abv _); rwa [div_mul_cancel _ (ne_of_gt G0), ← abv_mul abv] at this theorem neg_lim_zero {f : cau_seq β abv} (hf : lim_zero f) : lim_zero (-f) := by rw ← neg_one_mul; exact mul_lim_zero_right _ hf theorem sub_lim_zero {f g : cau_seq β abv} (hf : lim_zero f) (hg : lim_zero g) : lim_zero (f - g) := by simpa only [sub_eq_add_neg] using add_lim_zero hf (neg_lim_zero hg) theorem lim_zero_sub_rev {f g : cau_seq β abv} (hfg : lim_zero (f - g)) : lim_zero (g - f) := by simpa using neg_lim_zero hfg theorem zero_lim_zero : lim_zero (0 : cau_seq β abv) | ε ε0 := ⟨0, λ j ij, by simpa [abv_zero abv] using ε0⟩ theorem const_lim_zero {x : β} : lim_zero (const x) ↔ x = 0 := ⟨λ H, (abv_eq_zero abv).1 $ eq_of_le_of_forall_le_of_dense (abv_nonneg abv _) $ λ ε ε0, let ⟨i, hi⟩ := H _ ε0 in le_of_lt $ hi _ (le_refl _), λ e, e.symm ▸ zero_lim_zero⟩ instance equiv : setoid (cau_seq β abv) := ⟨λ f g, lim_zero (f - g), ⟨λ f, by simp [zero_lim_zero], λ f g h, by simpa using neg_lim_zero h, λ f g h fg gh, by simpa [sub_eq_add_neg, add_assoc] using add_lim_zero fg gh⟩⟩ lemma add_equiv_add {f1 f2 g1 g2 : cau_seq β abv} (hf : f1 ≈ f2) (hg : g1 ≈ g2) : f1 + g1 ≈ f2 + g2 := begin change lim_zero ((f1 + g1) - _), convert add_lim_zero hf hg using 1, simp only [sub_eq_add_neg, add_assoc], rw add_comm (-f2), simp only [add_assoc], congr' 2, simp end lemma neg_equiv_neg {f g : cau_seq β abv} (hf : f ≈ g) : -f ≈ -g := begin have hf : lim_zero _ := neg_lim_zero hf, show lim_zero (-f - -g), convert hf using 1, simp end theorem equiv_def₃ {f g : cau_seq β abv} (h : f ≈ g) {ε : α} (ε0 : 0 < ε) : ∃ i, ∀ j ≥ i, ∀ k ≥ j, abv (f k - g j) < ε := (exists_forall_ge_and (h _ $ half_pos ε0) (f.cauchy₃ $ half_pos ε0)).imp $ λ i H j ij k jk, let ⟨h₁, h₂⟩ := H _ ij in by have := lt_of_le_of_lt (abv_add abv (f j - g j) _) (add_lt_add h₁ (h₂ _ jk)); rwa [sub_add_sub_cancel', add_halves] at this theorem lim_zero_congr {f g : cau_seq β abv} (h : f ≈ g) : lim_zero f ↔ lim_zero g := ⟨λ l, by simpa using add_lim_zero (setoid.symm h) l, λ l, by simpa using add_lim_zero h l⟩ theorem abv_pos_of_not_lim_zero {f : cau_seq β abv} (hf : ¬ lim_zero f) : ∃ K > 0, ∃ i, ∀ j ≥ i, K ≤ abv (f j) := begin haveI := classical.prop_decidable, by_contra nk, refine hf (λ ε ε0, _), simp [not_forall] at nk, cases f.cauchy₃ (half_pos ε0) with i hi, rcases nk _ (half_pos ε0) i with ⟨j, ij, hj⟩, refine ⟨j, λ k jk, _⟩, have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add (hi j ij k jk) hj), rwa [sub_add_cancel, add_halves] at this end theorem of_near (f : ℕ → β) (g : cau_seq β abv) (h : ∀ ε > 0, ∃ i, ∀ j ≥ i, abv (f j - g j) < ε) : is_cau_seq abv f | ε ε0 := let ⟨i, hi⟩ := exists_forall_ge_and (h _ (half_pos $ half_pos ε0)) (g.cauchy₃ $ half_pos ε0) in ⟨i, λ j ij, begin cases hi _ (le_refl _) with h₁ h₂, rw abv_sub abv at h₁, have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add (hi _ ij).1 h₁), have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add this (h₂ _ ij)), rwa [add_halves, add_halves, add_right_comm, sub_add_sub_cancel, sub_add_sub_cancel] at this end⟩ lemma not_lim_zero_of_not_congr_zero {f : cau_seq _ abv} (hf : ¬ f ≈ 0) : ¬ lim_zero f := assume : lim_zero f, have lim_zero (f - 0), by simpa, hf this lemma mul_equiv_zero (g : cau_seq _ abv) {f : cau_seq _ abv} (hf : f ≈ 0) : g * f ≈ 0 := have lim_zero (f - 0), from hf, have lim_zero (g*f), from mul_lim_zero_right _ $ by simpa, show lim_zero (g*f - 0), by simpa lemma mul_not_equiv_zero {f g : cau_seq _ abv} (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) : ¬ (f * g) ≈ 0 := assume : lim_zero (f*g - 0), have hlz : lim_zero (f*g), by simpa, have hf' : ¬ lim_zero f, by simpa using (show ¬ lim_zero (f - 0), from hf), have hg' : ¬ lim_zero g, by simpa using (show ¬ lim_zero (g - 0), from hg), begin rcases abv_pos_of_not_lim_zero hf' with ⟨a1, ha1, N1, hN1⟩, rcases abv_pos_of_not_lim_zero hg' with ⟨a2, ha2, N2, hN2⟩, have : 0 < a1 * a2, from mul_pos ha1 ha2, cases hlz _ this with N hN, let i := max N (max N1 N2), have hN' := hN i (le_max_left _ _), have hN1' := hN1 i (le_trans (le_max_left _ _) (le_max_right _ _)), have hN1' := hN2 i (le_trans (le_max_right _ _) (le_max_right _ _)), apply not_le_of_lt hN', change _ ≤ abv (_ * _), rw is_absolute_value.abv_mul abv, apply mul_le_mul; try { assumption }, { apply le_of_lt ha2 }, { apply is_absolute_value.abv_nonneg abv } end theorem const_equiv {x y : β} : const x ≈ const y ↔ x = y := show lim_zero _ ↔ _, by rw [← const_sub, const_lim_zero, sub_eq_zero] end ring section comm_ring variables {β : Type*} [comm_ring β] {abv : β → α} [is_absolute_value abv] lemma mul_equiv_zero' (g : cau_seq _ abv) {f : cau_seq _ abv} (hf : f ≈ 0) : f * g ≈ 0 := by rw mul_comm; apply mul_equiv_zero _ hf end comm_ring section is_domain variables {β : Type*} [ring β] [is_domain β] (abv : β → α) [is_absolute_value abv] lemma one_not_equiv_zero : ¬ (const abv 1) ≈ (const abv 0) := assume h, have ∀ ε > 0, ∃ i, ∀ k, i ≤ k → abv (1 - 0) < ε, from h, have h1 : abv 1 ≤ 0, from le_of_not_gt $ assume h2 : 0 < abv 1, exists.elim (this _ h2) $ λ i hi, lt_irrefl (abv 1) $ by simpa using hi _ (le_refl _), have h2 : 0 ≤ abv 1, from is_absolute_value.abv_nonneg _ _, have abv 1 = 0, from le_antisymm h1 h2, have (1 : β) = 0, from (is_absolute_value.abv_eq_zero abv).1 this, absurd this one_ne_zero end is_domain section field variables {β : Type*} [field β] {abv : β → α} [is_absolute_value abv] theorem inv_aux {f : cau_seq β abv} (hf : ¬ lim_zero f) : ∀ ε > 0, ∃ i, ∀ j ≥ i, abv ((f j)⁻¹ - (f i)⁻¹) < ε | ε ε0 := let ⟨K, K0, HK⟩ := abv_pos_of_not_lim_zero hf, ⟨δ, δ0, Hδ⟩ := rat_inv_continuous_lemma abv ε0 K0, ⟨i, H⟩ := exists_forall_ge_and HK (f.cauchy₃ δ0) in ⟨i, λ j ij, let ⟨iK, H'⟩ := H _ (le_refl _) in Hδ (H _ ij).1 iK (H' _ ij)⟩ /-- Given a Cauchy sequence `f` with nonzero limit, create a Cauchy sequence with values equal to the inverses of the values of `f`. -/ def inv (f : cau_seq β abv) (hf : ¬ lim_zero f) : cau_seq β abv := ⟨_, inv_aux hf⟩ @[simp] theorem inv_apply {f : cau_seq β abv} (hf i) : inv f hf i = (f i)⁻¹ := rfl theorem inv_mul_cancel {f : cau_seq β abv} (hf) : inv f hf * f ≈ 1 := λ ε ε0, let ⟨K, K0, i, H⟩ := abv_pos_of_not_lim_zero hf in ⟨i, λ j ij, by simpa [(abv_pos abv).1 (lt_of_lt_of_le K0 (H _ ij)), abv_zero abv] using ε0⟩ theorem const_inv {x : β} (hx : x ≠ 0) : const abv (x⁻¹) = inv (const abv x) (by rwa const_lim_zero) := ext (assume n, by simp[inv_apply, const_apply]) end field section abs local notation `const` := const abs /-- The entries of a positive Cauchy sequence eventually have a positive lower bound. -/ def pos (f : cau_seq α abs) : Prop := ∃ K > 0, ∃ i, ∀ j ≥ i, K ≤ f j theorem not_lim_zero_of_pos {f : cau_seq α abs} : pos f → ¬ lim_zero f | ⟨F, F0, hF⟩ H := let ⟨i, h⟩ := exists_forall_ge_and hF (H _ F0), ⟨h₁, h₂⟩ := h _ (le_refl _) in not_lt_of_le h₁ (abs_lt.1 h₂).2 theorem const_pos {x : α} : pos (const x) ↔ 0 < x := ⟨λ ⟨K, K0, i, h⟩, lt_of_lt_of_le K0 (h _ (le_refl _)), λ h, ⟨x, h, 0, λ j _, le_refl _⟩⟩ theorem add_pos {f g : cau_seq α abs} : pos f → pos g → pos (f + g) | ⟨F, F0, hF⟩ ⟨G, G0, hG⟩ := let ⟨i, h⟩ := exists_forall_ge_and hF hG in ⟨_, _root_.add_pos F0 G0, i, λ j ij, let ⟨h₁, h₂⟩ := h _ ij in add_le_add h₁ h₂⟩ theorem pos_add_lim_zero {f g : cau_seq α abs} : pos f → lim_zero g → pos (f + g) | ⟨F, F0, hF⟩ H := let ⟨i, h⟩ := exists_forall_ge_and hF (H _ (half_pos F0)) in ⟨_, half_pos F0, i, λ j ij, begin cases h j ij with h₁ h₂, have := add_le_add h₁ (le_of_lt (abs_lt.1 h₂).1), rwa [← sub_eq_add_neg, sub_self_div_two] at this end⟩ protected theorem mul_pos {f g : cau_seq α abs} : pos f → pos g → pos (f * g) | ⟨F, F0, hF⟩ ⟨G, G0, hG⟩ := let ⟨i, h⟩ := exists_forall_ge_and hF hG in ⟨_, _root_.mul_pos F0 G0, i, λ j ij, let ⟨h₁, h₂⟩ := h _ ij in mul_le_mul h₁ h₂ (le_of_lt G0) (le_trans (le_of_lt F0) h₁)⟩ theorem trichotomy (f : cau_seq α abs) : pos f ∨ lim_zero f ∨ pos (-f) := begin cases classical.em (lim_zero f); simp *, rcases abv_pos_of_not_lim_zero h with ⟨K, K0, hK⟩, rcases exists_forall_ge_and hK (f.cauchy₃ K0) with ⟨i, hi⟩, refine (le_total 0 (f i)).imp _ _; refine (λ h, ⟨K, K0, i, λ j ij, _⟩); have := (hi _ ij).1; cases hi _ (le_refl _) with h₁ h₂, { rwa abs_of_nonneg at this, rw abs_of_nonneg h at h₁, exact (le_add_iff_nonneg_right _).1 (le_trans h₁ $ neg_le_sub_iff_le_add'.1 $ le_of_lt (abs_lt.1 $ h₂ _ ij).1) }, { rwa abs_of_nonpos at this, rw abs_of_nonpos h at h₁, rw [← sub_le_sub_iff_right, zero_sub], exact le_trans (le_of_lt (abs_lt.1 $ h₂ _ ij).2) h₁ } end instance : has_lt (cau_seq α abs) := ⟨λ f g, pos (g - f)⟩ instance : has_le (cau_seq α abs) := ⟨λ f g, f < g ∨ f ≈ g⟩ theorem lt_of_lt_of_eq {f g h : cau_seq α abs} (fg : f < g) (gh : g ≈ h) : f < h := show pos (h - f), by simpa [sub_eq_add_neg, add_comm, add_left_comm] using pos_add_lim_zero fg (neg_lim_zero gh) theorem lt_of_eq_of_lt {f g h : cau_seq α abs} (fg : f ≈ g) (gh : g < h) : f < h := by have := pos_add_lim_zero gh (neg_lim_zero fg); rwa [← sub_eq_add_neg, sub_sub_sub_cancel_right] at this theorem lt_trans {f g h : cau_seq α abs} (fg : f < g) (gh : g < h) : f < h := show pos (h - f), by simpa [sub_eq_add_neg, add_comm, add_left_comm] using add_pos fg gh theorem lt_irrefl {f : cau_seq α abs} : ¬ f < f | h := not_lim_zero_of_pos h (by simp [zero_lim_zero]) lemma le_of_eq_of_le {f g h : cau_seq α abs} (hfg : f ≈ g) (hgh : g ≤ h) : f ≤ h := hgh.elim (or.inl ∘ cau_seq.lt_of_eq_of_lt hfg) (or.inr ∘ setoid.trans hfg) lemma le_of_le_of_eq {f g h : cau_seq α abs} (hfg : f ≤ g) (hgh : g ≈ h) : f ≤ h := hfg.elim (λ h, or.inl (cau_seq.lt_of_lt_of_eq h hgh)) (λ h, or.inr (setoid.trans h hgh)) instance : preorder (cau_seq α abs) := { lt := (<), le := λ f g, f < g ∨ f ≈ g, le_refl := λ f, or.inr (setoid.refl _), le_trans := λ f g h fg, match fg with | or.inl fg, or.inl gh := or.inl $ lt_trans fg gh | or.inl fg, or.inr gh := or.inl $ lt_of_lt_of_eq fg gh | or.inr fg, or.inl gh := or.inl $ lt_of_eq_of_lt fg gh | or.inr fg, or.inr gh := or.inr $ setoid.trans fg gh end, lt_iff_le_not_le := λ f g, ⟨λ h, ⟨or.inl h, not_or (mt (lt_trans h) lt_irrefl) (not_lim_zero_of_pos h)⟩, λ ⟨h₁, h₂⟩, h₁.resolve_right (mt (λ h, or.inr (setoid.symm h)) h₂)⟩ } theorem le_antisymm {f g : cau_seq α abs} (fg : f ≤ g) (gf : g ≤ f) : f ≈ g := fg.resolve_left (not_lt_of_le gf) theorem lt_total (f g : cau_seq α abs) : f < g ∨ f ≈ g ∨ g < f := (trichotomy (g - f)).imp_right (λ h, h.imp (λ h, setoid.symm h) (λ h, by rwa neg_sub at h)) theorem le_total (f g : cau_seq α abs) : f ≤ g ∨ g ≤ f := (or.assoc.2 (lt_total f g)).imp_right or.inl theorem const_lt {x y : α} : const x < const y ↔ x < y := show pos _ ↔ _, by rw [← const_sub, const_pos, sub_pos] theorem const_le {x y : α} : const x ≤ const y ↔ x ≤ y := by rw le_iff_lt_or_eq; exact or_congr const_lt const_equiv lemma le_of_exists {f g : cau_seq α abs} (h : ∃ i, ∀ j ≥ i, f j ≤ g j) : f ≤ g := let ⟨i, hi⟩ := h in (or.assoc.2 (cau_seq.lt_total f g)).elim id (λ hgf, false.elim (let ⟨K, hK0, j, hKj⟩ := hgf in not_lt_of_ge (hi (max i j) (le_max_left _ _)) (sub_pos.1 (lt_of_lt_of_le hK0 (hKj _ (le_max_right _ _)))))) theorem exists_gt (f : cau_seq α abs) : ∃ a : α, f < const a := let ⟨K, H⟩ := f.bounded in ⟨K + 1, 1, zero_lt_one, 0, λ i _, begin rw [sub_apply, const_apply, le_sub_iff_add_le', add_le_add_iff_right], exact le_of_lt (abs_lt.1 (H _)).2 end⟩ theorem exists_lt (f : cau_seq α abs) : ∃ a : α, const a < f := let ⟨a, h⟩ := (-f).exists_gt in ⟨-a, show pos _, by rwa [const_neg, sub_neg_eq_add, add_comm, ← sub_neg_eq_add]⟩ end abs end cau_seq
a25093957edfdf2ef7621761f114cc185d165bab
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/polynomial/mirror.lean
a2cf132a655d232c21f5b913a0a876a2c0887848
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
7,486
lean
/- Copyright (c) 2020 Thomas Browning. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning -/ import data.polynomial.ring_division /-! # "Mirror" of a univariate polynomial In this file we define `polynomial.mirror`, a variant of `polynomial.reverse`. The difference between `reverse` and `mirror` is that `reverse` will decrease the degree if the polynomial is divisible by `X`. We also define `polynomial.norm2`, which is the sum of the squares of the coefficients of a polynomial. It is also a coefficient of `p * p.mirror`. ## Main definitions - `polynomial.mirror` - `polynomial.norm2` ## Main results - `polynomial.mirror_mul_of_domain`: `mirror` preserves multiplication. - `polynomial.irreducible_of_mirror`: an irreducibility criterion involving `mirror` - `polynomial.norm2_eq_mul_reverse_coeff`: `norm2` is a coefficient of `p * p.mirror` -/ namespace polynomial variables {R : Type*} [semiring R] (p : polynomial R) section mirror /-- mirror of a polynomial: reverses the coefficients while preserving `polynomial.nat_degree` -/ noncomputable def mirror := p.reverse * X ^ p.nat_trailing_degree @[simp] lemma mirror_zero : (0 : polynomial R).mirror = 0 := by simp [mirror] lemma mirror_monomial (n : ℕ) (a : R) : (monomial n a).mirror = (monomial n a) := begin classical, by_cases ha : a = 0, { rw [ha, monomial_zero_right, mirror_zero] }, { rw [mirror, reverse, nat_degree_monomial n a, if_neg ha, nat_trailing_degree_monomial ha, ←C_mul_X_pow_eq_monomial, reflect_C_mul_X_pow, rev_at_le (le_refl n), tsub_self, pow_zero, mul_one] }, end lemma mirror_C (a : R) : (C a).mirror = C a := mirror_monomial 0 a lemma mirror_X : X.mirror = (X : polynomial R) := mirror_monomial 1 (1 : R) lemma mirror_nat_degree : p.mirror.nat_degree = p.nat_degree := begin by_cases hp : p = 0, { rw [hp, mirror_zero] }, by_cases hR : nontrivial R, { haveI := hR, rw [mirror, nat_degree_mul', reverse_nat_degree, nat_degree_X_pow, tsub_add_cancel_of_le p.nat_trailing_degree_le_nat_degree], rwa [leading_coeff_X_pow, mul_one, reverse_leading_coeff, ne, trailing_coeff_eq_zero] }, { haveI := not_nontrivial_iff_subsingleton.mp hR, exact congr_arg nat_degree (subsingleton.elim p.mirror p) }, end lemma mirror_nat_trailing_degree : p.mirror.nat_trailing_degree = p.nat_trailing_degree := begin by_cases hp : p = 0, { rw [hp, mirror_zero] }, { rw [mirror, nat_trailing_degree_mul_X_pow ((mt reverse_eq_zero.mp) hp), reverse_nat_trailing_degree, zero_add] }, end lemma coeff_mirror (n : ℕ) : p.mirror.coeff n = p.coeff (rev_at (p.nat_degree + p.nat_trailing_degree) n) := begin by_cases h2 : p.nat_degree < n, { rw [coeff_eq_zero_of_nat_degree_lt (by rwa mirror_nat_degree)], by_cases h1 : n ≤ p.nat_degree + p.nat_trailing_degree, { rw [rev_at_le h1, coeff_eq_zero_of_lt_nat_trailing_degree], exact (tsub_lt_iff_left h1).mpr (nat.add_lt_add_right h2 _) }, { rw [←rev_at_fun_eq, rev_at_fun, if_neg h1, coeff_eq_zero_of_nat_degree_lt h2] } }, rw not_lt at h2, rw [rev_at_le (h2.trans (nat.le_add_right _ _))], by_cases h3 : p.nat_trailing_degree ≤ n, { rw [←tsub_add_eq_add_tsub h2, ←tsub_tsub_assoc h2 h3, mirror, coeff_mul_X_pow', if_pos h3, coeff_reverse, rev_at_le (tsub_le_self.trans h2)] }, rw not_le at h3, rw coeff_eq_zero_of_nat_degree_lt (lt_tsub_iff_right.mpr (nat.add_lt_add_left h3 _)), exact coeff_eq_zero_of_lt_nat_trailing_degree (by rwa mirror_nat_trailing_degree), end --TODO: Extract `finset.sum_range_rev_at` lemma. lemma mirror_eval_one : p.mirror.eval 1 = p.eval 1 := begin simp_rw [eval_eq_finset_sum, one_pow, mul_one, mirror_nat_degree], refine finset.sum_bij_ne_zero _ _ _ _ _, { exact λ n hn hp, rev_at (p.nat_degree + p.nat_trailing_degree) n }, { intros n hn hp, rw finset.mem_range_succ_iff at *, rw rev_at_le (hn.trans (nat.le_add_right _ _)), rw [tsub_le_iff_tsub_le, add_comm, add_tsub_cancel_right, ←mirror_nat_trailing_degree], exact nat_trailing_degree_le_of_ne_zero hp }, { exact λ n₁ n₂ hn₁ hp₁ hn₂ hp₂ h, by rw [←@rev_at_invol _ n₁, h, rev_at_invol] }, { intros n hn hp, use rev_at (p.nat_degree + p.nat_trailing_degree) n, refine ⟨_, _, rev_at_invol.symm⟩, { rw finset.mem_range_succ_iff at *, rw rev_at_le (hn.trans (nat.le_add_right _ _)), rw [tsub_le_iff_tsub_le, add_comm, add_tsub_cancel_right], exact nat_trailing_degree_le_of_ne_zero hp }, { change p.mirror.coeff _ ≠ 0, rwa [coeff_mirror, rev_at_invol] } }, { exact λ n hn hp, p.coeff_mirror n }, end lemma mirror_mirror : p.mirror.mirror = p := polynomial.ext (λ n, by rw [coeff_mirror, coeff_mirror, mirror_nat_degree, mirror_nat_trailing_degree, rev_at_invol]) lemma mirror_eq_zero : p.mirror = 0 ↔ p = 0 := ⟨λ h, by rw [←p.mirror_mirror, h, mirror_zero], λ h, by rw [h, mirror_zero]⟩ lemma mirror_trailing_coeff : p.mirror.trailing_coeff = p.leading_coeff := by rw [leading_coeff, trailing_coeff, mirror_nat_trailing_degree, coeff_mirror, rev_at_le (nat.le_add_left _ _), add_tsub_cancel_right] lemma mirror_leading_coeff : p.mirror.leading_coeff = p.trailing_coeff := by rw [←p.mirror_mirror, mirror_trailing_coeff, p.mirror_mirror] lemma mirror_mul_of_domain {R : Type*} [ring R] [is_domain R] (p q : polynomial R) : (p * q).mirror = p.mirror * q.mirror := begin by_cases hp : p = 0, { rw [hp, zero_mul, mirror_zero, zero_mul] }, by_cases hq : q = 0, { rw [hq, mul_zero, mirror_zero, mul_zero] }, rw [mirror, mirror, mirror, reverse_mul_of_domain, nat_trailing_degree_mul hp hq, pow_add], rw [mul_assoc, ←mul_assoc q.reverse], conv_lhs { congr, skip, congr, rw [←X_pow_mul] }, repeat { rw [mul_assoc], }, end lemma mirror_smul {R : Type*} [ring R] [is_domain R] (p : polynomial R) (a : R) : (a • p).mirror = a • p.mirror := by rw [←C_mul', ←C_mul', mirror_mul_of_domain, mirror_C] lemma mirror_neg {R : Type*} [ring R] (p : polynomial R) : (-p).mirror = -(p.mirror) := by rw [mirror, mirror, reverse_neg, nat_trailing_degree_neg, neg_mul_eq_neg_mul] lemma irreducible_of_mirror {R : Type*} [comm_ring R] [is_domain R] {f : polynomial R} (h1 : ¬ is_unit f) (h2 : ∀ k, f * f.mirror = k * k.mirror → k = f ∨ k = -f ∨ k = f.mirror ∨ k = -f.mirror) (h3 : ∀ g, g ∣ f → g ∣ f.mirror → is_unit g) : irreducible f := begin split, { exact h1 }, { intros g h fgh, let k := g * h.mirror, have key : f * f.mirror = k * k.mirror, { rw [fgh, mirror_mul_of_domain, mirror_mul_of_domain, mirror_mirror, mul_assoc, mul_comm h, mul_comm g.mirror, mul_assoc, ←mul_assoc] }, have g_dvd_f : g ∣ f, { rw fgh, exact dvd_mul_right g h }, have h_dvd_f : h ∣ f, { rw fgh, exact dvd_mul_left h g }, have g_dvd_k : g ∣ k, { exact dvd_mul_right g h.mirror }, have h_dvd_k_rev : h ∣ k.mirror, { rw [mirror_mul_of_domain, mirror_mirror], exact dvd_mul_left h g.mirror }, have hk := h2 k key, rcases hk with hk | hk | hk | hk, { exact or.inr (h3 h h_dvd_f (by rwa ← hk)) }, { exact or.inr (h3 h h_dvd_f (by rwa [eq_neg_iff_eq_neg.mp hk, mirror_neg, dvd_neg])) }, { exact or.inl (h3 g g_dvd_f (by rwa ← hk)) }, { exact or.inl (h3 g g_dvd_f (by rwa [eq_neg_iff_eq_neg.mp hk, dvd_neg])) } }, end end mirror end polynomial
5dc3b9eb035e5c96b9bf2cd0c8a3548905ed426e
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/unfold.lean
b152749677ab60a2afc37c87cba9c6526a599114
[ "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
712
lean
import data.nat open nat algebra definition f (a b : nat) := a + b example (a b : nat) : f a b = 0 → f b a = 0 := begin intro h, unfold f at h, state, unfold f, state, rewrite [add.comm], exact h end example (a b : nat) : f a b = 0 → f b a = 0 := begin intro h, unfold f at *, state, rewrite [add.comm], exact h end example (a b c : nat) : f c c = 0 → f a b = 0 → f b a = f c c := begin intros [h₁, h₂], unfold f at (h₁, h₂), state, unfold f, rewrite [add.comm, h₁, h₂], end example (a b c : nat) : f c c = 0 → f a b = 0 → f b a = f c c := begin intros [h₁, h₂], unfold f at * ⊢, state, unfold f, rewrite [add.comm, h₁, h₂], end
97f0e4f6cd3d272b520978966f8cbc185919d5b6
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/nat/even_odd_rec.lean
4eb5627bf7d339b4e599183c22313655c698d387
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
1,996
lean
/- Copyright (c) 2022 Stuart Presnell. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Stuart Presnell -/ import data.nat.basic /-! # A recursion principle based on even and odd numbers. -/ namespace nat /-- Recursion principle on even and odd numbers: if we have `P 0`, and for all `i : ℕ` we can extend from `P i` to both `P (2 * i)` and `P (2 * i + 1)`, then we have `P n` for all `n : ℕ`. This is nothing more than a wrapper around `nat.binary_rec`, to avoid having to switch to dealing with `bit0` and `bit1`. -/ @[elab_as_eliminator] def even_odd_rec {P : ℕ → Sort*} (h0 : P 0) (h_even : ∀ n (ih : P n), P (2 * n)) (h_odd : ∀ n (ih : P n), P (2 * n + 1)) (n : ℕ) : P n := begin refine @binary_rec P h0 (λ b i hi, _) n, cases b, { simpa [bit, bit0_val i] using h_even i hi }, { simpa [bit, bit1_val i] using h_odd i hi }, end @[simp] lemma even_odd_rec_zero (P : ℕ → Sort*) (h0 : P 0) (h_even : ∀ i, P i → P (2 * i)) (h_odd : ∀ i, P i → P (2 * i + 1)) : @even_odd_rec _ h0 h_even h_odd 0 = h0 := binary_rec_zero _ _ @[simp] lemma even_odd_rec_even (n : ℕ) (P : ℕ → Sort*) (h0 : P 0) (h_even : ∀ i, P i → P (2 * i)) (h_odd : ∀ i, P i → P (2 * i + 1)) (H : h_even 0 h0 = h0) : @even_odd_rec _ h0 h_even h_odd (2 * n) = h_even n (even_odd_rec h0 h_even h_odd n) := begin convert binary_rec_eq _ ff n, { exact (bit0_eq_two_mul _).symm }, { exact (bit0_eq_two_mul _).symm }, { apply heq_of_cast_eq, refl }, { exact H } end @[simp] lemma even_odd_rec_odd (n : ℕ) (P : ℕ → Sort*) (h0 : P 0) (h_even : ∀ i, P i → P (2 * i)) (h_odd : ∀ i, P i → P (2 * i + 1)) (H : h_even 0 h0 = h0) : @even_odd_rec _ h0 h_even h_odd (2 * n + 1) = h_odd n (even_odd_rec h0 h_even h_odd n) := begin convert binary_rec_eq _ tt n, { exact (bit0_eq_two_mul _).symm }, { exact (bit0_eq_two_mul _).symm }, { apply heq_of_cast_eq, refl }, { exact H } end end nat
dcfec1161081329232e00f18ca2199fef7de7fbf
e151e9053bfd6d71740066474fc500a087837323
/src/hott/hit/colimit.lean
60e37c7b671d6848d5feb7d23d12244b7130a914
[ "Apache-2.0" ]
permissive
daniel-carranza/hott3
15bac2d90589dbb952ef15e74b2837722491963d
913811e8a1371d3a5751d7d32ff9dec8aa6815d9
refs/heads/master
1,610,091,349,670
1,596,222,336,000
1,596,222,336,000
241,957,822
0
0
Apache-2.0
1,582,222,839,000
1,582,222,838,000
null
UTF-8
Lean
false
false
8,364
lean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn Definition of general colimits and sequential colimits. -/ import ..init universes u v w hott_theory namespace hott /- definition of a general colimit -/ open hott.eq nat hott.quotient sigma equiv is_trunc namespace colimit section parameters {I : Type u} {J : Type v} (A : I → Type w) (dom cod : J → I) (f : Π(j : J), A (dom j) → A (cod j)) variables {i : I} (a : A i) (j : J) (b : A (dom j)) local notation `B` := Σ(i : I), A i inductive colim_rel : B → B → Type (max u v w) | Rmk : Π{j : J} (a : A (dom j)), colim_rel ⟨cod j, f j a⟩ ⟨dom j, a⟩ open colim_rel local notation `R` := colim_rel -- TODO: define this in root namespace @[hott] def colimit : Type _ := quotient colim_rel @[hott] def incl : colimit := class_of R ⟨i, a⟩ @[hott, reducible] def ι := @incl @[hott] def cglue : eq.{max u v w} (ι (f j b)) (ι b) := eq_of_rel colim_rel (Rmk _ : colim_rel ⟨_, f j b⟩ ⟨_, b⟩) @[hott, elab_as_eliminator] protected def rec {P : colimit → Type _} (Pincl : Π⦃i : I⦄ (x : A i), P (ι x)) (Pglue : Π(j : J) (x : A (dom j)), Pincl (f j x) =[cglue j x] Pincl x) (y : colimit) : P y := begin fapply (quotient.rec_on y), { intro a, induction a, apply Pincl}, { intros a a' H, induction H, apply Pglue} end @[hott, elab_as_eliminator] protected def rec_on {P : colimit → Type _} (y : colimit) (Pincl : Π⦃i : I⦄ (x : A i), P (ι x)) (Pglue : Π(j : J) (x : A (dom j)), Pincl (f j x) =[cglue j x] Pincl x) : P y := rec Pincl Pglue y @[hott] theorem rec_cglue {P : colimit → Type _} (Pincl : Π⦃i : I⦄ (x : A i), P (ι x)) (Pglue : Π(j : J) (x : A (dom j)), Pincl (f j x) =[cglue j x] Pincl x) {j : J} (x : A (dom j)) : apd (rec Pincl Pglue) (cglue j x) = Pglue j x := by delta cglue hott.colimit.rec; dsimp [quotient.rec_on]; apply rec_eq_of_rel @[hott] protected def elim {P : Type _} (Pincl : Π⦃i : I⦄ (x : A i), P) (Pglue : Π(j : J) (x : A (dom j)), Pincl (f j x) = Pincl x) (y : colimit) : P := @rec (λ _, P) Pincl (λj a, pathover_of_eq _ (Pglue j a)) y @[hott] protected def elim_on {P : Type _} (y : colimit) (Pincl : Π⦃i : I⦄ (x : A i), P) (Pglue : Π(j : J) (x : A (dom j)), Pincl (f j x) = Pincl x) : P := elim Pincl Pglue y @[hott, hsimp] def elim_incl {P : Type _} (Pincl : Π⦃i : I⦄ (x : A i), P) (Pglue : Π(j : J) (x : A (dom j)), Pincl (f j x) = Pincl x) : hott.colimit.elim Pincl Pglue (ι a) = Pincl a := idp @[hott] theorem elim_cglue {P : Type _} (Pincl : Π⦃i : I⦄ (x : A i), P) (Pglue : Π(j : J) (x : A (dom j)), Pincl (f j x) = Pincl x) {j : J} (x : A (dom j)) : ap (elim Pincl Pglue) (cglue j x) = Pglue j x := begin apply eq_of_fn_eq_fn_inv ((pathover_constant (cglue _ _ _ _ j x)) _ _), refine (apd_eq_pathover_of_eq_ap _ _)⁻¹ ⬝ rec_eq_of_rel _ _ _ end @[hott] protected def elim_type (Pincl : Π⦃i : I⦄ (x : A i), Type _) (Pglue : Π(j : J) (x : A (dom j)), Pincl (f j x) ≃ Pincl x) (y : colimit) : Type _ := elim Pincl (λj a, ua (Pglue j a)) y @[hott] protected def elim_type_on (y : colimit) (Pincl : Π⦃i : I⦄ (x : A i), Type _) (Pglue : Π(j : J) (x : A (dom j)), Pincl (f j x) ≃ Pincl x) : Type _ := elim_type Pincl Pglue y @[hott] theorem elim_type_cglue (Pincl : Π⦃i : I⦄ (x : A i), Type _) (Pglue : Π(j : J) (x : A (dom j)), Pincl (f j x) ≃ Pincl x) {j : J} (x : A (dom j)) : transport (elim_type Pincl Pglue) (cglue j x) = Pglue j x := by rwr tr_eq_cast_ap_fn; delta elim_type; rwr elim_cglue; apply cast_ua_fn @[hott] protected def rec_prop {P : colimit → Type _} [H : Πx, is_prop (P x)] (Pincl : Π⦃i : I⦄ (x : A i), P (ι x)) (y : colimit) : P y := rec Pincl (λa b, is_prop.elimo _ _ _) y @[hott] protected def elim_prop {P : Type _} [H : is_prop P] (Pincl : Π⦃i : I⦄ (x : A i), P) (y : colimit) : P := elim Pincl (λa b, is_prop.elim _ _) y end end colimit /- definition of a sequential colimit -/ namespace seq_colim section /- we define it directly in terms of quotients. An alternative definition could be @[hott] def seq_colim := colimit.colimit A id succ f -/ parameters {A : ℕ → Type u} (f : Π⦃n⦄, A n → A (succ n)) variables {n : ℕ} (a : A n) local notation `B` := Σ(n : ℕ), A n inductive seq_rel : B → B → Type u | Rmk : Π{n : ℕ} (a : A n), seq_rel ⟨succ n, f a⟩ ⟨n, a⟩ open seq_rel local notation `R` := seq_rel -- TODO: define this in root namespace @[hott] def seq_colim : Type _ := quotient seq_rel @[hott] def inclusion : seq_colim := class_of R ⟨n, a⟩ @[reducible,hott] def sι := @inclusion @[hott] def glue : sι (f a) = sι a := eq_of_rel seq_rel (Rmk a) @[hott] protected def rec {P : seq_colim → Type _} (Pincl : Π⦃n : ℕ⦄ (a : A n), P (sι a)) (Pglue : Π(n : ℕ) (a : A n), Pincl (f a) =[glue a] Pincl a) (aa : seq_colim) : P aa := begin fapply (quotient.rec_on aa), { intro a, induction a, apply Pincl}, { intros a a' H, induction H, apply Pglue} end @[hott] protected def rec_on {P : seq_colim → Type _} (aa : seq_colim) (Pincl : Π⦃n : ℕ⦄ (a : A n), P (sι a)) (Pglue : Π⦃n : ℕ⦄ (a : A n), Pincl (f a) =[glue a] Pincl a) : P aa := rec Pincl Pglue aa @[hott] theorem rec_glue {P : seq_colim → Type _} (Pincl : Π⦃n : ℕ⦄ (a : A n), P (sι a)) (Pglue : Π⦃n : ℕ⦄ (a : A n), Pincl (f a) =[glue a] Pincl a) {n : ℕ} (a : A n) : apd (rec Pincl Pglue) (glue a) = Pglue a := by delta glue seq_colim.rec; dsimp [quotient.rec_on]; apply rec_eq_of_rel @[hott] protected def elim {P : Type _} (Pincl : Π⦃n : ℕ⦄ (a : A n), P) (Pglue : Π⦃n : ℕ⦄ (a : A n), Pincl (f a) = Pincl a) : seq_colim → P := rec Pincl (λn a, pathover_of_eq _ (Pglue a)) @[hott, hsimp] def elim_incl {P : Type _} (Pincl : Π⦃n : ℕ⦄ (a : A n), P) (Pglue : Π⦃n : ℕ⦄ (a : A n), Pincl (f a) = Pincl a) : hott.seq_colim.elim Pincl Pglue (sι a) = Pincl a := idp @[hott] protected def elim_on {P : Type _} (aa : seq_colim) (Pincl : Π⦃n : ℕ⦄ (a : A n), P) (Pglue : Π⦃n : ℕ⦄ (a : A n), Pincl (f a) = Pincl a) : P := elim Pincl Pglue aa @[hott] theorem elim_glue {P : Type _} (Pincl : Π⦃n : ℕ⦄ (a : A n), P) (Pglue : Π⦃n : ℕ⦄ (a : A n), Pincl (f a) = Pincl a) {n : ℕ} (a : A n) : ap (elim Pincl Pglue) (glue a) = Pglue a := begin apply eq_of_fn_eq_fn_inv ((pathover_constant (glue _ a)) _ _), refine (apd_eq_pathover_of_eq_ap _ _)⁻¹ ⬝ rec_eq_of_rel _ _ _ end @[hott] protected def elim_type (Pincl : Π⦃n : ℕ⦄ (a : A n), Type _) (Pglue : Π⦃n : ℕ⦄ (a : A n), Pincl (f a) ≃ Pincl a) : seq_colim → Type _ := elim Pincl (λn a, ua (Pglue a)) @[hott] protected def elim_type_on (aa : seq_colim) (Pincl : Π⦃n : ℕ⦄ (a : A n), Type _) (Pglue : Π⦃n : ℕ⦄ (a : A n), Pincl (f a) ≃ Pincl a) : Type _ := elim_type Pincl Pglue aa @[hott] theorem elim_type_glue (Pincl : Π⦃n : ℕ⦄ (a : A n), Type _) (Pglue : Π⦃n : ℕ⦄ (a : A n), Pincl (f a) ≃ Pincl a) {n : ℕ} (a : A n) : transport (elim_type Pincl Pglue) (glue a) = Pglue a := by rwr tr_eq_cast_ap_fn; dunfold elim_type; rwr elim_glue; apply cast_ua_fn @[hott] theorem elim_type_glue_inv (Pincl : Π⦃n : ℕ⦄ (a : A n), Type _) (Pglue : Π⦃n : ℕ⦄ (a : A n), Pincl (f a) ≃ Pincl a) {n : ℕ} (a : A n) : transport (hott.seq_colim.elim_type Pincl Pglue) (glue a)⁻¹ = (Pglue a)⁻¹ᶠ := by rwr tr_eq_cast_ap_fn; dunfold elim_type; rwr [ap_inv, elim_glue]; dsimp; apply cast_ua_inv_fn @[hott] protected def rec_prop {P : seq_colim → Type _} [H : Πx, is_prop (P x)] (Pincl : Π⦃n : ℕ⦄ (a : A n), P (sι a)) (aa : seq_colim) : P aa := rec Pincl (by intros; apply is_prop.elimo) aa @[hott] protected def elim_prop {P : Type _} [H : is_prop P] (Pincl : Π⦃n : ℕ⦄ (a : A n), P) : seq_colim → P := elim Pincl (λa b, is_prop.elim _ _) end end seq_colim end hott
71ef36e0ead48cf495acf7277b07089980f192d7
853df553b1d6ca524e3f0a79aedd32dde5d27ec3
/src/category_theory/limits/shapes/pullbacks.lean
250b56e05fef7b00a4fa533d709ce0808432b03c
[ "Apache-2.0" ]
permissive
DanielFabian/mathlib
efc3a50b5dde303c59eeb6353ef4c35a345d7112
f520d07eba0c852e96fe26da71d85bf6d40fcc2a
refs/heads/master
1,668,739,922,971
1,595,201,756,000
1,595,201,756,000
279,469,476
0
0
null
1,594,696,604,000
1,594,696,604,000
null
UTF-8
Lean
false
false
25,061
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, Bhavik Mehta -/ import category_theory.limits.shapes.wide_pullbacks import category_theory.limits.shapes.binary_products /-! # Pullbacks We define a category `walking_cospan` (resp. `walking_span`), which is the index category for the given data for a pullback (resp. pushout) diagram. Convenience methods `cospan f g` and `span f g` construct functors from the walking (co)span, hitting the given morphisms. We define `pullback f g` and `pushout f g` as limits and colimits of such functors. Typeclasses `has_pullbacks` and `has_pushouts` assert the existence of (co)limits shaped as walking (co)spans. -/ open category_theory namespace category_theory.limits universes v u local attribute [tidy] tactic.case_bash /-- The type of objects for the diagram indexing a pullback, defined as a special case of `wide_pullback_shape`. -/ abbreviation walking_cospan : Type v := wide_pullback_shape walking_pair /-- The left point of the walking cospan. -/ abbreviation walking_cospan.left : walking_cospan := some walking_pair.left /-- The right point of the walking cospan. -/ abbreviation walking_cospan.right : walking_cospan := some walking_pair.right /-- The central point of the walking cospan. -/ abbreviation walking_cospan.one : walking_cospan := none /-- The type of objects for the diagram indexing a pushout, defined as a special case of `wide_pushout_shape`. -/ abbreviation walking_span : Type v := wide_pushout_shape walking_pair /-- The left point of the walking span. -/ abbreviation walking_span.left : walking_span := some walking_pair.left /-- The right point of the walking span. -/ abbreviation walking_span.right : walking_span := some walking_pair.right /-- The central point of the walking span. -/ abbreviation walking_span.zero : walking_span := none namespace walking_cospan /-- The type of arrows for the diagram indexing a pullback. -/ abbreviation hom : walking_cospan → walking_cospan → Type v := wide_pullback_shape.hom /-- The left arrow of the walking cospan. -/ abbreviation hom.inl : left ⟶ one := wide_pullback_shape.hom.term _ /-- The right arrow of the walking cospan. -/ abbreviation hom.inr : right ⟶ one := wide_pullback_shape.hom.term _ /-- The identity arrows of the walking cospan. -/ abbreviation hom.id (X : walking_cospan) : X ⟶ X := wide_pullback_shape.hom.id X instance (X Y : walking_cospan) : subsingleton (X ⟶ Y) := by tidy end walking_cospan namespace walking_span /-- The type of arrows for the diagram indexing a pushout. -/ abbreviation hom : walking_span → walking_span → Type v := wide_pushout_shape.hom /-- The left arrow of the walking span. -/ abbreviation hom.fst : zero ⟶ left := wide_pushout_shape.hom.init _ /-- The right arrow of the walking span. -/ abbreviation hom.snd : zero ⟶ right := wide_pushout_shape.hom.init _ /-- The identity arrows of the walking span. -/ abbreviation hom.id (X : walking_span) : X ⟶ X := wide_pushout_shape.hom.id X instance (X Y : walking_span) : subsingleton (X ⟶ Y) := by tidy end walking_span open walking_span.hom walking_cospan.hom wide_pullback_shape.hom wide_pushout_shape.hom variables {C : Type u} [category.{v} C] /-- `cospan f g` is the functor from the walking cospan hitting `f` and `g`. -/ def cospan {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : walking_cospan ⥤ C := wide_pullback_shape.wide_cospan Z (λ j, walking_pair.cases_on j X Y) (λ j, walking_pair.cases_on j f g) /-- `span f g` is the functor from the walking span hitting `f` and `g`. -/ def span {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : walking_span ⥤ C := wide_pushout_shape.wide_span X (λ j, walking_pair.cases_on j Y Z) (λ j, walking_pair.cases_on j f g) @[simp] lemma cospan_left {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).obj walking_cospan.left = X := rfl @[simp] lemma span_left {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).obj walking_span.left = Y := rfl @[simp] lemma cospan_right {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).obj walking_cospan.right = Y := rfl @[simp] lemma span_right {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).obj walking_span.right = Z := rfl @[simp] lemma cospan_one {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).obj walking_cospan.one = Z := rfl @[simp] lemma span_zero {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).obj walking_span.zero = X := rfl @[simp] lemma cospan_map_inl {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).map walking_cospan.hom.inl = f := rfl @[simp] lemma span_map_fst {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).map walking_span.hom.fst = f := rfl @[simp] lemma cospan_map_inr {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).map walking_cospan.hom.inr = g := rfl @[simp] lemma span_map_snd {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).map walking_span.hom.snd = g := rfl lemma cospan_map_id {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) (w : walking_cospan) : (cospan f g).map (walking_cospan.hom.id w) = 𝟙 _ := rfl lemma span_map_id {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) (w : walking_span) : (span f g).map (walking_span.hom.id w) = 𝟙 _ := rfl /-- Every diagram indexing an pullback is naturally isomorphic (actually, equal) to a `cospan` -/ def diagram_iso_cospan (F : walking_cospan ⥤ C) : F ≅ cospan (F.map inl) (F.map inr) := nat_iso.of_components (λ j, eq_to_iso (by tidy)) (by tidy) /-- Every diagram indexing a pushout is naturally isomorphic (actually, equal) to a `span` -/ def diagram_iso_span (F : walking_span ⥤ C) : F ≅ span (F.map fst) (F.map snd) := nat_iso.of_components (λ j, eq_to_iso (by tidy)) (by tidy) variables {X Y Z : C} /-- A pullback cone is just a cone on the cospan formed by two morphisms `f : X ⟶ Z` and `g : Y ⟶ Z`.-/ abbreviation pullback_cone (f : X ⟶ Z) (g : Y ⟶ Z) := cone (cospan f g) namespace pullback_cone variables {f : X ⟶ Z} {g : Y ⟶ Z} /-- The first projection of a pullback cone. -/ abbreviation fst (t : pullback_cone f g) : t.X ⟶ X := t.π.app walking_cospan.left /-- The second projection of a pullback cone. -/ abbreviation snd (t : pullback_cone f g) : t.X ⟶ Y := t.π.app walking_cospan.right /-- A pullback cone on `f` and `g` is determined by morphisms `fst : W ⟶ X` and `snd : W ⟶ Y` such that `fst ≫ f = snd ≫ g`. -/ @[simps] def mk {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : pullback_cone f g := { X := W, π := { app := λ j, option.cases_on j (fst ≫ f) (λ j', walking_pair.cases_on j' fst snd) } } @[simp] lemma mk_π_app_left {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : (mk fst snd eq).π.app walking_cospan.left = fst := rfl @[simp] lemma mk_π_app_right {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : (mk fst snd eq).π.app walking_cospan.right = snd := rfl @[simp] lemma mk_π_app_one {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : (mk fst snd eq).π.app walking_cospan.one = fst ≫ f := rfl @[simp] lemma mk_fst {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : (mk fst snd eq).fst = fst := rfl @[simp] lemma mk_snd {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : (mk fst snd eq).snd = snd := rfl @[reassoc] lemma condition (t : pullback_cone f g) : fst t ≫ f = snd t ≫ g := (t.w inl).trans (t.w inr).symm /-- To check whether a morphism is equalized by the maps of a pullback cone, it suffices to check it for `fst t` and `snd t` -/ lemma equalizer_ext (t : pullback_cone f g) {W : C} {k l : W ⟶ t.X} (h₀ : k ≫ fst t = l ≫ fst t) (h₁ : k ≫ snd t = l ≫ snd t) : ∀ (j : walking_cospan), k ≫ t.π.app j = l ≫ t.π.app j | (some walking_pair.left) := h₀ | (some walking_pair.right) := h₁ | none := by rw [← t.w inl, reassoc_of h₀] lemma is_limit.hom_ext {t : pullback_cone f g} (ht : is_limit t) {W : C} {k l : W ⟶ t.X} (h₀ : k ≫ fst t = l ≫ fst t) (h₁ : k ≫ snd t = l ≫ snd t) : k = l := ht.hom_ext $ equalizer_ext _ h₀ h₁ /-- If `t` is a limit pullback cone over `f` and `g` and `h : W ⟶ X` and `k : W ⟶ Y` are such that `h ≫ f = k ≫ g`, then we have `l : W ⟶ t.X` satisfying `l ≫ fst t = h` and `l ≫ snd t = k`. -/ def is_limit.lift' {t : pullback_cone f g} (ht : is_limit t) {W : C} (h : W ⟶ X) (k : W ⟶ Y) (w : h ≫ f = k ≫ g) : {l : W ⟶ t.X // l ≫ fst t = h ∧ l ≫ snd t = k} := ⟨ht.lift $ pullback_cone.mk _ _ w, ht.fac _ _, ht.fac _ _⟩ /-- This is a slightly more convenient method to verify that a pullback cone is a limit cone. It only asks for a proof of facts that carry any mathematical content -/ def is_limit.mk (t : pullback_cone f g) (lift : Π (s : cone (cospan f g)), s.X ⟶ t.X) (fac_left : ∀ (s : cone (cospan f g)), lift s ≫ t.π.app walking_cospan.left = s.π.app walking_cospan.left) (fac_right : ∀ (s : cone (cospan f g)), lift s ≫ t.π.app walking_cospan.right = s.π.app walking_cospan.right) (uniq : ∀ (s : cone (cospan f g)) (m : s.X ⟶ t.X) (w : ∀ j : walking_cospan, m ≫ t.π.app j = s.π.app j), m = lift s) : is_limit t := { lift := lift, fac' := λ s j, option.cases_on j (by { simp [← s.w inl, ← t.w inl, ← fac_left s] } ) (λ j', walking_pair.cases_on j' (fac_left s) (fac_right s)), uniq' := uniq } /-- This is another convenient method to verify that a pullback cone 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 is_limit.mk' (t : pullback_cone f g) (create : Π (s : pullback_cone f g), {l // l ≫ t.fst = s.fst ∧ l ≫ t.snd = s.snd ∧ ∀ {m}, m ≫ t.fst = s.fst → m ≫ t.snd = s.snd → m = l}) : is_limit t := pullback_cone.is_limit.mk t (λ s, (create s).1) (λ s, (create s).2.1) (λ s, (create s).2.2.1) (λ s m w, (create s).2.2.2 (w walking_cospan.left) (w walking_cospan.right)) /-- The flip of a pullback square is a pullback square. -/ def flip_is_limit {W : C} {h : W ⟶ X} {k : W ⟶ Y} {comm : h ≫ f = k ≫ g} (t : is_limit (mk _ _ comm.symm)) : is_limit (mk _ _ comm) := is_limit.mk' _ $ λ s, begin refine ⟨(is_limit.lift' t _ _ s.condition.symm).1, (is_limit.lift' t _ _ _).2.2, (is_limit.lift' t _ _ _).2.1, λ m m₁ m₂, t.hom_ext _⟩, apply (mk k h _).equalizer_ext, { rwa (is_limit.lift' t _ _ _).2.1 }, { rwa (is_limit.lift' t _ _ _).2.2 }, end end pullback_cone /-- A pushout cocone is just a cocone on the span formed by two morphisms `f : X ⟶ Y` and `g : X ⟶ Z`.-/ abbreviation pushout_cocone (f : X ⟶ Y) (g : X ⟶ Z) := cocone (span f g) namespace pushout_cocone variables {f : X ⟶ Y} {g : X ⟶ Z} /-- The first inclusion of a pushout cocone. -/ abbreviation inl (t : pushout_cocone f g) : Y ⟶ t.X := t.ι.app walking_span.left /-- The second inclusion of a pushout cocone. -/ abbreviation inr (t : pushout_cocone f g) : Z ⟶ t.X := t.ι.app walking_span.right /-- A pushout cocone on `f` and `g` is determined by morphisms `inl : Y ⟶ W` and `inr : Z ⟶ W` such that `f ≫ inl = g ↠ inr`. -/ @[simps] def mk {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : pushout_cocone f g := { X := W, ι := { app := λ j, option.cases_on j (f ≫ inl) (λ j', walking_pair.cases_on j' inl inr) } } @[simp] lemma mk_ι_app_left {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : (mk inl inr eq).ι.app walking_span.left = inl := rfl @[simp] lemma mk_ι_app_right {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : (mk inl inr eq).ι.app walking_span.right = inr := rfl @[simp] lemma mk_ι_app_zero {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : (mk inl inr eq).ι.app walking_span.zero = f ≫ inl := rfl @[simp] lemma mk_inl {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : (mk inl inr eq).inl = inl := rfl @[simp] lemma mk_inr {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : (mk inl inr eq).inr = inr := rfl @[reassoc] lemma condition (t : pushout_cocone f g) : f ≫ (inl t) = g ≫ (inr t) := (t.w fst).trans (t.w snd).symm /-- To check whether a morphism is coequalized by the maps of a pushout cocone, it suffices to check it for `inl t` and `inr t` -/ lemma coequalizer_ext (t : pushout_cocone f g) {W : C} {k l : t.X ⟶ W} (h₀ : inl t ≫ k = inl t ≫ l) (h₁ : inr t ≫ k = inr t ≫ l) : ∀ (j : walking_span), t.ι.app j ≫ k = t.ι.app j ≫ l | (some walking_pair.left) := h₀ | (some walking_pair.right) := h₁ | none := by rw [← t.w fst, category.assoc, category.assoc, h₀] lemma is_colimit.hom_ext {t : pushout_cocone f g} (ht : is_colimit t) {W : C} {k l : t.X ⟶ W} (h₀ : inl t ≫ k = inl t ≫ l) (h₁ : inr t ≫ k = inr t ≫ l) : k = l := ht.hom_ext $ coequalizer_ext _ h₀ h₁ /-- If `t` is a colimit pushout cocone over `f` and `g` and `h : Y ⟶ W` and `k : Z ⟶ W` are morphisms satisfying `f ≫ h = g ≫ k`, then we have a factorization `l : t.X ⟶ W` such that `inl t ≫ l = h` and `inr t ≫ l = k`. -/ def is_colimit.desc' {t : pushout_cocone f g} (ht : is_colimit t) {W : C} (h : Y ⟶ W) (k : Z ⟶ W) (w : f ≫ h = g ≫ k) : {l : t.X ⟶ W // inl t ≫ l = h ∧ inr t ≫ l = k } := ⟨ht.desc $ pushout_cocone.mk _ _ w, ht.fac _ _, ht.fac _ _⟩ /-- This is a slightly more convenient method to verify that a pushout cocone is a colimit cocone. It only asks for a proof of facts that carry any mathematical content -/ def is_colimit.mk (t : pushout_cocone f g) (desc : Π (s : cocone (span f g)), t.X ⟶ s.X) (fac_left : ∀ (s : cocone (span f g)), t.ι.app walking_span.left ≫ desc s = s.ι.app walking_span.left) (fac_right : ∀ (s : cocone (span f g)), t.ι.app walking_span.right ≫ desc s = s.ι.app walking_span.right) (uniq : ∀ (s : cocone (span f g)) (m : t.X ⟶ s.X) (w : ∀ j : walking_span, t.ι.app j ≫ m = s.ι.app j), m = desc s) : is_colimit t := { desc := desc, fac' := λ s j, option.cases_on j (by { simp [← s.w fst, ← t.w fst, fac_left s] } ) (λ j', walking_pair.cases_on j' (fac_left s) (fac_right s)), uniq' := uniq } /-- This is another convenient method to verify that a pushout cocone is a colimit cocone. It only asks for a proof of facts that carry any mathematical content, and allows access to the same `s` for all parts. -/ def is_colimit.mk' (t : pushout_cocone f g) (create : Π (s : pushout_cocone f g), {l // t.inl ≫ l = s.inl ∧ t.inr ≫ l = s.inr ∧ ∀ {m}, t.inl ≫ m = s.inl → t.inr ≫ m = s.inr → m = l}) : is_colimit t := is_colimit.mk t (λ s, (create s).1) (λ s, (create s).2.1) (λ s, (create s).2.2.1) (λ s m w, (create s).2.2.2 (w walking_cospan.left) (w walking_cospan.right)) /-- The flip of a pushout square is a pushout square. -/ def flip_is_colimit {W : C} {h : Y ⟶ W} {k : Z ⟶ W} {comm : f ≫ h = g ≫ k} (t : is_colimit (mk _ _ comm.symm)) : is_colimit (mk _ _ comm) := is_colimit.mk' _ $ λ s, begin refine ⟨(is_colimit.desc' t _ _ s.condition.symm).1, (is_colimit.desc' t _ _ _).2.2, (is_colimit.desc' t _ _ _).2.1, λ m m₁ m₂, t.hom_ext _⟩, apply (mk k h _).coequalizer_ext, { rwa (is_colimit.desc' t _ _ _).2.1 }, { rwa (is_colimit.desc' t _ _ _).2.2 }, end end pushout_cocone /-- This is a helper construction that can be useful when verifying that a category has all pullbacks. Given `F : walking_cospan ⥤ C`, which is really the same as `cospan (F.map inl) (F.map inr)`, and a pullback cone on `F.map inl` and `F.map inr`, we get a cone on `F`. If you're thinking about using this, have a look at `has_pullbacks_of_has_limit_cospan`, which you may find to be an easier way of achieving your goal. -/ @[simps] def cone.of_pullback_cone {F : walking_cospan ⥤ C} (t : pullback_cone (F.map inl) (F.map inr)) : cone F := { X := t.X, π := t.π ≫ (diagram_iso_cospan F).inv } /-- This is a helper construction that can be useful when verifying that a category has all pushout. Given `F : walking_span ⥤ C`, which is really the same as `span (F.map fst) (F.mal snd)`, and a pushout cocone on `F.map fst` and `F.map snd`, we get a cocone on `F`. If you're thinking about using this, have a look at `has_pushouts_of_has_colimit_span`, which you may find to be an easiery way of achieving your goal. -/ @[simps] def cocone.of_pushout_cocone {F : walking_span ⥤ C} (t : pushout_cocone (F.map fst) (F.map snd)) : cocone F := { X := t.X, ι := (diagram_iso_span F).hom ≫ t.ι } /-- Given `F : walking_cospan ⥤ C`, which is really the same as `cospan (F.map inl) (F.map inr)`, and a cone on `F`, we get a pullback cone on `F.map inl` and `F.map inr`. -/ @[simps] def pullback_cone.of_cone {F : walking_cospan ⥤ C} (t : cone F) : pullback_cone (F.map inl) (F.map inr) := { X := t.X, π := t.π ≫ (diagram_iso_cospan F).hom } /-- Given `F : walking_span ⥤ C`, which is really the same as `span (F.map fst) (F.map snd)`, and a cocone on `F`, we get a pushout cocone on `F.map fst` and `F.map snd`. -/ @[simps] def pushout_cocone.of_cocone {F : walking_span ⥤ C} (t : cocone F) : pushout_cocone (F.map fst) (F.map snd) := { X := t.X, ι := (diagram_iso_span F).inv ≫ t.ι } /-- `pullback f g` computes the pullback of a pair of morphisms with the same target. -/ abbreviation pullback {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) [has_limit (cospan f g)] := limit (cospan f g) /-- `pushout f g` computes the pushout of a pair of morphisms with the same source. -/ abbreviation pushout {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) [has_colimit (span f g)] := colimit (span f g) /-- The first projection of the pullback of `f` and `g`. -/ abbreviation pullback.fst {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] : pullback f g ⟶ X := limit.π (cospan f g) walking_cospan.left /-- The second projection of the pullback of `f` and `g`. -/ abbreviation pullback.snd {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] : pullback f g ⟶ Y := limit.π (cospan f g) walking_cospan.right /-- The first inclusion into the pushout of `f` and `g`. -/ abbreviation pushout.inl {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] : Y ⟶ pushout f g := colimit.ι (span f g) walking_span.left /-- The second inclusion into the pushout of `f` and `g`. -/ abbreviation pushout.inr {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] : Z ⟶ pushout f g := colimit.ι (span f g) walking_span.right /-- A pair of morphisms `h : W ⟶ X` and `k : W ⟶ Y` satisfying `h ≫ f = k ≫ g` induces a morphism `pullback.lift : W ⟶ pullback f g`. -/ abbreviation pullback.lift {W X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] (h : W ⟶ X) (k : W ⟶ Y) (w : h ≫ f = k ≫ g) : W ⟶ pullback f g := limit.lift _ (pullback_cone.mk h k w) /-- A pair of morphisms `h : Y ⟶ W` and `k : Z ⟶ W` satisfying `f ≫ h = g ≫ k` induces a morphism `pushout.desc : pushout f g ⟶ W`. -/ abbreviation pushout.desc {W X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] (h : Y ⟶ W) (k : Z ⟶ W) (w : f ≫ h = g ≫ k) : pushout f g ⟶ W := colimit.desc _ (pushout_cocone.mk h k w) @[simp, reassoc] lemma pullback.lift_fst {W X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] (h : W ⟶ X) (k : W ⟶ Y) (w : h ≫ f = k ≫ g) : pullback.lift h k w ≫ pullback.fst = h := limit.lift_π _ _ @[simp, reassoc] lemma pullback.lift_snd {W X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] (h : W ⟶ X) (k : W ⟶ Y) (w : h ≫ f = k ≫ g) : pullback.lift h k w ≫ pullback.snd = k := limit.lift_π _ _ @[simp, reassoc] lemma pushout.inl_desc {W X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] (h : Y ⟶ W) (k : Z ⟶ W) (w : f ≫ h = g ≫ k) : pushout.inl ≫ pushout.desc h k w = h := colimit.ι_desc _ _ @[simp, reassoc] lemma pushout.inr_desc {W X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] (h : Y ⟶ W) (k : Z ⟶ W) (w : f ≫ h = g ≫ k) : pushout.inr ≫ pushout.desc h k w = k := colimit.ι_desc _ _ /-- A pair of morphisms `h : W ⟶ X` and `k : W ⟶ Y` satisfying `h ≫ f = k ≫ g` induces a morphism `l : W ⟶ pullback f g` such that `l ≫ pullback.fst = h` and `l ≫ pullback.snd = k`. -/ def pullback.lift' {W X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] (h : W ⟶ X) (k : W ⟶ Y) (w : h ≫ f = k ≫ g) : {l : W ⟶ pullback f g // l ≫ pullback.fst = h ∧ l ≫ pullback.snd = k} := ⟨pullback.lift h k w, pullback.lift_fst _ _ _, pullback.lift_snd _ _ _⟩ /-- A pair of morphisms `h : Y ⟶ W` and `k : Z ⟶ W` satisfying `f ≫ h = g ≫ k` induces a morphism `l : pushout f g ⟶ W` such that `pushout.inl ≫ l = h` and `pushout.inr ≫ l = k`. -/ def pullback.desc' {W X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] (h : Y ⟶ W) (k : Z ⟶ W) (w : f ≫ h = g ≫ k) : {l : pushout f g ⟶ W // pushout.inl ≫ l = h ∧ pushout.inr ≫ l = k} := ⟨pushout.desc h k w, pushout.inl_desc _ _ _, pushout.inr_desc _ _ _⟩ @[reassoc] lemma pullback.condition {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] : (pullback.fst : pullback f g ⟶ X) ≫ f = pullback.snd ≫ g := pullback_cone.condition _ @[reassoc] lemma pushout.condition {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] : f ≫ (pushout.inl : Y ⟶ pushout f g) = g ≫ pushout.inr := pushout_cocone.condition _ /-- Two morphisms into a pullback are equal if their compositions with the pullback morphisms are equal -/ @[ext] lemma pullback.hom_ext {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] {W : C} {k l : W ⟶ pullback f g} (h₀ : k ≫ pullback.fst = l ≫ pullback.fst) (h₁ : k ≫ pullback.snd = l ≫ pullback.snd) : k = l := limit.hom_ext $ pullback_cone.equalizer_ext _ h₀ h₁ /-- The pullback of a monomorphism is a monomorphism -/ instance pullback.fst_of_mono {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] [mono g] : mono (pullback.fst : pullback f g ⟶ X) := ⟨λ W u v h, pullback.hom_ext h $ (cancel_mono g).1 $ by simp [← pullback.condition, reassoc_of h]⟩ /-- The pullback of a monomorphism is a monomorphism -/ instance pullback.snd_of_mono {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] [mono f] : mono (pullback.snd : pullback f g ⟶ Y) := ⟨λ W u v h, pullback.hom_ext ((cancel_mono f).1 $ by simp [pullback.condition, reassoc_of h]) h⟩ /-- Two morphisms out of a pushout are equal if their compositions with the pushout morphisms are equal -/ @[ext] lemma pushout.hom_ext {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] {W : C} {k l : pushout f g ⟶ W} (h₀ : pushout.inl ≫ k = pushout.inl ≫ l) (h₁ : pushout.inr ≫ k = pushout.inr ≫ l) : k = l := colimit.hom_ext $ pushout_cocone.coequalizer_ext _ h₀ h₁ /-- The pushout of an epimorphism is an epimorphism -/ instance pushout.inl_of_epi {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] [epi g] : epi (pushout.inl : Y ⟶ pushout f g) := ⟨λ W u v h, pushout.hom_ext h $ (cancel_epi g).1 $ by simp [← pushout.condition_assoc, h] ⟩ /-- The pushout of an epimorphism is an epimorphism -/ instance pushout.inr_of_epi {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] [epi f] : epi (pushout.inr : Z ⟶ pushout f g) := ⟨λ W u v h, pushout.hom_ext ((cancel_epi f).1 $ by simp [pushout.condition_assoc, h]) h⟩ variables (C) /-- `has_pullbacks` represents a choice of pullback for every pair of morphisms -/ class has_pullbacks := (has_limits_of_shape : has_limits_of_shape walking_cospan C) /-- `has_pushouts` represents a choice of pushout for every pair of morphisms -/ class has_pushouts := (has_colimits_of_shape : has_colimits_of_shape walking_span C) attribute [instance] has_pullbacks.has_limits_of_shape has_pushouts.has_colimits_of_shape /-- If `C` has all limits of diagrams `cospan f g`, then it has all pullbacks -/ def has_pullbacks_of_has_limit_cospan [Π {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z}, has_limit (cospan f g)] : has_pullbacks C := { has_limits_of_shape := { has_limit := λ F, has_limit_of_iso (diagram_iso_cospan F).symm } } /-- If `C` has all colimits of diagrams `span f g`, then it has all pushouts -/ def has_pushouts_of_has_colimit_span [Π {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z}, has_colimit (span f g)] : has_pushouts C := { has_colimits_of_shape := { has_colimit := λ F, has_colimit_of_iso (diagram_iso_span F) } } end category_theory.limits
4370bd822d7e69ecf28f4be1b828885052a2b847
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/stage0/src/Init/Notation.lean
6d6be5fe53ab1086ed5ac4334b60984e5f06e237
[ "Apache-2.0" ]
permissive
collares/lean4
861a9269c4592bce49b71059e232ff0bfe4594cc
52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee
refs/heads/master
1,691,419,031,324
1,618,678,138,000
1,618,678,138,000
358,989,750
0
0
Apache-2.0
1,618,696,333,000
1,618,696,333,000
null
UTF-8
Lean
false
false
13,684
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 Notation for operators defined at Prelude.lean -/ prelude import Init.Prelude -- DSL for specifying parser precedences and priorities namespace Lean.Parser.Syntax syntax:65 (name := addPrec) prec " + " prec:66 : prec syntax:65 (name := subPrec) prec " - " prec:66 : prec syntax:65 (name := addPrio) prio " + " prio:66 : prio syntax:65 (name := subPrio) prio " - " prio:66 : prio end Lean.Parser.Syntax macro "max" : prec => `(1024) -- maximum precedence used in term parsers, in particular for terms in function position (`ident`, `paren`, ...) macro "arg" : prec => `(1023) -- precedence used for application arguments (`do`, `by`, ...) macro "lead" : prec => `(1022) -- precedence used for terms not supposed to be used as arguments (`let`, `have`, ...) macro "(" p:prec ")" : prec => p macro "min" : prec => `(10) -- minimum precedence used in term parsers macro "min1" : prec => `(11) -- `(min+1) we can only `min+1` after `Meta.lean` /- `max:prec` as a term. It is equivalent to `eval_prec max` for `eval_prec` defined at `Meta.lean`. We use `max_prec` to workaround bootstrapping issues. -/ macro "max_prec" : term => `(1024) macro "default" : prio => `(1000) macro "low" : prio => `(100) macro "mid" : prio => `(1000) macro "high" : prio => `(10000) macro "(" p:prio ")" : prio => p -- Basic notation for defining parsers syntax stx "+" : stx syntax stx "*" : stx syntax stx "?" : stx syntax:2 stx " <|> " stx:1 : stx macro_rules | `(stx| $p +) => `(stx| many1($p)) | `(stx| $p *) => `(stx| many($p)) | `(stx| $p ?) => `(stx| optional($p)) | `(stx| $p₁ <|> $p₂) => `(stx| orelse($p₁, $p₂)) /- Comma-separated sequence. -/ macro:max x:stx ",*" : stx => `(stx| sepBy($x, ",", ", ")) macro:max x:stx ",+" : stx => `(stx| sepBy1($x, ",", ", ")) /- Comma-separated sequence with optional trailing comma. -/ macro:max x:stx ",*,?" : stx => `(stx| sepBy($x, ",", ", ", allowTrailingSep)) macro:max x:stx ",+,?" : stx => `(stx| sepBy1($x, ",", ", ", allowTrailingSep)) macro "!" x:stx : stx => `(stx| notFollowedBy($x)) syntax (name := rawNatLit) "nat_lit " num : term infixr:90 " ∘ " => Function.comp infixr:35 " × " => Prod infixl:55 " ||| " => HOr.hOr infixl:58 " ^^^ " => HXor.hXor infixl:60 " &&& " => HAnd.hAnd infixl:65 " + " => HAdd.hAdd infixl:65 " - " => HSub.hSub infixl:70 " * " => HMul.hMul infixl:70 " / " => HDiv.hDiv infixl:70 " % " => HMod.hMod infixl:75 " <<< " => HShiftLeft.hShiftLeft infixl:75 " >>> " => HShiftRight.hShiftRight infixr:80 " ^ " => HPow.hPow prefix:100 "-" => Neg.neg prefix:100 "~~~" => Complement.complement -- declare ASCII alternatives first so that the latter Unicode unexpander wins infix:50 " <= " => HasLessEq.LessEq infix:50 " ≤ " => HasLessEq.LessEq infix:50 " < " => HasLess.Less infix:50 " >= " => GreaterEq infix:50 " ≥ " => GreaterEq infix:50 " > " => Greater infix:50 " = " => Eq infix:50 " == " => BEq.beq infix:50 " ~= " => HEq infix:50 " ≅ " => HEq /- Remark: the infix commands above ensure a delaborator is generated for each relations. We redefine the macros below to be able to use the auxiliary `binrel%` elaboration helper for binary relations. It has better support for applying coercions. For example, suppose we have `binrel% Eq n i` where `n : Nat` and `i : Int`. The default elaborator fails because we don't have a coercion from `Int` to `Nat`, but `binrel%` succeeds because it also tries a coercion from `Nat` to `Int` even when the nat occurs before the int. -/ macro_rules | `($x <= $y) => `(binrel% HasLessEq.LessEq $x $y) macro_rules | `($x ≤ $y) => `(binrel% HasLessEq.LessEq $x $y) macro_rules | `($x < $y) => `(binrel% HasLess.Less $x $y) macro_rules | `($x > $y) => `(binrel% Greater $x $y) macro_rules | `($x >= $y) => `(binrel% GreaterEq $x $y) macro_rules | `($x ≥ $y) => `(binrel% GreaterEq $x $y) macro_rules | `($x = $y) => `(binrel% Eq $x $y) macro_rules | `($x == $y) => `(binrel% BEq.beq $x $y) infixr:35 " /\\ " => And infixr:35 " ∧ " => And infixr:30 " \\/ " => Or infixr:30 " ∨ " => Or notation:max "¬" p:40 => Not p infixl:35 " && " => and infixl:30 " || " => or notation:max "!" b:40 => not b infixl:65 " ++ " => HAppend.hAppend infixr:67 " :: " => List.cons infixr:20 " <|> " => HOrElse.hOrElse infixr:60 " >> " => HAndThen.hAndThen infixl:55 " >>= " => Bind.bind infixl:60 " <*> " => Seq.seq infixl:60 " <* " => SeqLeft.seqLeft infixr:60 " *> " => SeqRight.seqRight infixr:100 " <$> " => Functor.map syntax (name := termDepIfThenElse) ppGroup(ppDedent("if " ident " : " term " then" ppSpace term ppDedent(ppSpace "else") ppSpace term)) : term macro_rules | `(if $h:ident : $c then $t:term else $e:term) => `(dite $c (fun $h:ident => $t) (fun $h:ident => $e)) syntax (name := termIfThenElse) ppGroup(ppDedent("if " term " then" ppSpace term ppDedent(ppSpace "else") ppSpace term)) : term macro_rules | `(if $c then $t:term else $e:term) => `(ite $c $t $e) macro "if " "let " pat:term " := " d:term " then " t:term " else " e:term : term => `(match $d:term with | $pat:term => $t | _ => $e) syntax:min term "<|" term:min : term macro_rules | `($f $args* <| $a) => let args := args.push a; `($f $args*) | `($f <| $a) => `($f $a) syntax:min term "|>" term:min1 : term macro_rules | `($a |> $f $args*) => let args := args.push a; `($f $args*) | `($a |> $f) => `($f $a) -- Haskell-like pipe <| -- Note that we have a whitespace after `$` to avoid an ambiguity with the antiquotations. syntax:min term atomic("$" ws) term:min : term macro_rules | `($f $args* $ $a) => let args := args.push a; `($f $args*) | `($f $ $a) => `($f $a) syntax "{ " ident (" : " term)? " // " term " }" : term macro_rules | `({ $x : $type // $p }) => `(Subtype (fun ($x:ident : $type) => $p)) | `({ $x // $p }) => `(Subtype (fun ($x:ident : _) => $p)) /- `without_expected_type t` instructs Lean to elaborate `t` without an expected type. Recall that terms such as `match ... with ...` and `⟨...⟩` will postpone elaboration until expected type is known. So, `without_expected_type` is not effective in this case. -/ macro "without_expected_type " x:term : term => `(let aux := $x; aux) syntax "[" term,* "]" : term syntax "%[" term,* "|" term "]" : term -- auxiliary notation for creating big list literals namespace Lean macro_rules | `([ $elems,* ]) => do let rec expandListLit (i : Nat) (skip : Bool) (result : Syntax) : MacroM Syntax := do match i, skip with | 0, _ => pure result | i+1, true => expandListLit i false result | i+1, false => expandListLit i true (← `(List.cons $(elems.elemsAndSeps[i]) $result)) if elems.elemsAndSeps.size < 64 then expandListLit elems.elemsAndSeps.size false (← `(List.nil)) else `(%[ $elems,* | List.nil ]) namespace Parser.Tactic syntax (name := intro) "intro " notFollowedBy("|") (colGt term:max)* : tactic syntax (name := intros) "intros " (colGt (ident <|> "_"))* : tactic syntax (name := rename) "rename " term " => " ident : tactic syntax (name := revert) "revert " (colGt ident)+ : tactic syntax (name := clear) "clear " (colGt ident)+ : tactic syntax (name := subst) "subst " (colGt ident)+ : tactic syntax (name := assumption) "assumption" : tactic syntax (name := contradiction) "contradiction" : tactic syntax (name := apply) "apply " term : tactic syntax (name := exact) "exact " term : tactic syntax (name := refine) "refine " term : tactic syntax (name := refine') "refine' " term : tactic syntax (name := case) "case " ident " => " tacticSeq : tactic syntax (name := allGoals) "allGoals " tacticSeq : tactic syntax (name := focus) "focus " tacticSeq : tactic syntax (name := skip) "skip" : tactic syntax (name := done) "done" : tactic syntax (name := traceState) "traceState" : tactic syntax (name := failIfSuccess) "failIfSuccess " tacticSeq : tactic syntax (name := generalize) "generalize " atomic(ident " : ")? term:51 " = " ident : tactic syntax (name := paren) "(" tacticSeq ")" : tactic syntax (name := withReducible) "withReducible " tacticSeq : tactic syntax (name := withReducibleAndInstances) "withReducibleAndInstances " tacticSeq : tactic syntax (name := first) "first " "|"? sepBy1(tacticSeq, "|") : tactic syntax (name := rotateLeft) "rotateLeft" (num)? : tactic syntax (name := rotateRight) "rotateRight" (num)? : tactic macro "try " t:tacticSeq : tactic => `(first $t | skip) macro:1 x:tactic " <;> " y:tactic:0 : tactic => `(tactic| focus ($x:tactic; allGoals $y:tactic)) macro "rfl" : tactic => `(exact rfl) macro "admit" : tactic => `(exact sorry) macro "inferInstance" : tactic => `(exact inferInstance) syntax locationWildcard := "*" syntax locationHyp := (colGt ident)+ ("⊢" <|> "|-")? -- TODO: delete syntax locationTargets := (colGt ident)+ ("⊢" <|> "|-")? syntax location := withPosition("at " locationWildcard <|> locationHyp) syntax (name := change) "change " term (location)? : tactic syntax (name := changeWith) "change " term " with " term (location)? : tactic syntax rwRule := ("←" <|> "<-")? term syntax rwRuleSeq := "[" rwRule,+,? "]" syntax (name := rewrite) "rewrite " rwRule (location)? : tactic syntax (name := rewriteSeq) (priority := high) "rewrite " rwRuleSeq (location)? : tactic syntax (name := erewrite) "erewrite " rwRule (location)? : tactic syntax (name := erewriteSeq) (priority := high) "erewrite " rwRuleSeq (location)? : tactic syntax (name := rw) "rw " rwRule (location)? : tactic syntax (name := rwSeq) (priority := high) "rw " rwRuleSeq (location)? : tactic syntax (name := erw) "erw " rwRule (location)? : tactic syntax (name := erwSeq) (priority := high) "erw " rwRuleSeq (location)? : tactic private def withCheapRefl (tac : Syntax) : MacroM Syntax := `(tactic| $tac; try (withReducible rfl)) @[macro rw] def expandRw : Macro := fun stx => withCheapRefl (stx.setKind `Lean.Parser.Tactic.rewrite |>.setArg 0 (mkAtomFrom stx "rewrite")) @[macro rwSeq] def expandRwSeq : Macro := fun stx => withCheapRefl (stx.setKind `Lean.Parser.Tactic.rewriteSeq |>.setArg 0 (mkAtomFrom stx "rewrite")) @[macro erw] def expandERw : Macro := fun stx => withCheapRefl (stx.setKind `Lean.Parser.Tactic.erewrite |>.setArg 0 (mkAtomFrom stx "erewrite")) @[macro erwSeq] def expandERwSeq : Macro := fun stx => withCheapRefl (stx.setKind `Lean.Parser.Tactic.erewriteSeq |>.setArg 0 (mkAtomFrom stx "erewrite")) syntax (name := injection) "injection " term (" with " (colGt (ident <|> "_"))+)? : tactic syntax simpPre := "↓" syntax simpPost := "↑" syntax simpLemma := (simpPre <|> simpPost)? term syntax simpErase := "-" ident syntax (name := simp) "simp " ("(" &"config" " := " term ")")? (&"only ")? ("[" (simpErase <|> simpLemma),* "]")? (location)? : tactic syntax (name := simpAll) "simp_all " ("(" &"config" " := " term ")")? (&"only ")? ("[" (simpErase <|> simpLemma),* "]")? : tactic -- Auxiliary macro for lifting have/suffices/let/... -- It makes sure the "continuation" `?_` is the main goal after refining macro "refineLift " e:term : tactic => `(focus (refine noImplicitLambda% $e; rotateRight)) macro "have " d:haveDecl : tactic => `(refineLift have $d:haveDecl; ?_) /- We use a priority > default, to avoid ambiguity with previous `have` notation -/ macro (priority := high) "have" x:ident " := " p:term : tactic => `(have $x:ident : _ := $p) macro "suffices " d:sufficesDecl : tactic => `(refineLift suffices $d:sufficesDecl; ?_) macro "let " d:letDecl : tactic => `(refineLift let $d:letDecl; ?_) macro "show " e:term : tactic => `(refineLift show $e:term from ?_) syntax (name := letrec) withPosition(atomic(group("let " &"rec ")) letRecDecls) : tactic macro_rules | `(tactic| let rec $d:letRecDecls) => `(tactic| refineLift let rec $d:letRecDecls; ?_) -- Similar to `refineLift`, but using `refine'` macro "refineLift' " e:term : tactic => `(focus (refine' noImplicitLambda% $e; rotateRight)) macro "have' " d:haveDecl : tactic => `(refineLift' have $d:haveDecl; ?_) macro (priority := high) "have'" x:ident " := " p:term : tactic => `(have' $x:ident : _ := $p) macro "let' " d:letDecl : tactic => `(refineLift' let $d:letDecl; ?_) syntax inductionAlt := "| " (group("@"? ident) <|> "_") (ident <|> "_")* " => " (hole <|> syntheticHole <|> tacticSeq) syntax inductionAlts := "with " (tactic)? withPosition( (colGe inductionAlt)+) syntax (name := induction) "induction " term,+ (" using " ident)? ("generalizing " ident+)? (inductionAlts)? : tactic syntax casesTarget := atomic(ident " : ")? term syntax (name := cases) "cases " casesTarget,+ (" using " ident)? (inductionAlts)? : tactic syntax (name := existsIntro) "exists " term : tactic syntax "repeat " tacticSeq : tactic macro_rules | `(tactic| repeat $seq) => `(tactic| first ($seq); repeat $seq | skip) syntax "trivial" : tactic macro_rules | `(tactic| trivial) => `(tactic| assumption) macro_rules | `(tactic| trivial) => `(tactic| rfl) macro_rules | `(tactic| trivial) => `(tactic| contradiction) macro_rules | `(tactic| trivial) => `(tactic| apply True.intro) macro_rules | `(tactic| trivial) => `(tactic| apply And.intro <;> trivial) macro "unhygienic " t:tacticSeq : tactic => `(set_option tactic.hygienic false in $t:tacticSeq) end Tactic namespace Attr -- simp attribute syntax syntax (name := simp) "simp" (Tactic.simpPre <|> Tactic.simpPost)? (prio)? : attr end Attr end Parser end Lean macro "‹" type:term "›" : term => `((by assumption : $type))
23b2e7f34e65548562328c045215cc4add150387
7b02c598aa57070b4cf4fbfe2416d0479220187f
/algebra/direct_sum.hlean
e5eaf82b3ecc9e906285ac158e1ad686cbc47df4
[ "Apache-2.0" ]
permissive
jdchristensen/Spectral
50d4f0ddaea1484d215ef74be951da6549de221d
6ded2b94d7ae07c4098d96a68f80a9cd3d433eb8
refs/heads/master
1,611,555,010,649
1,496,724,191,000
1,496,724,191,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,823
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Egbert Rijke Constructions with groups -/ import .quotient_group .free_commutative_group open eq algebra is_trunc set_quotient relation sigma prod sum list trunc function equiv sigma.ops namespace group variables {G G' : AddGroup} (H : subgroup_rel G) (N : normal_subgroup_rel G) {g g' h h' k : G} {A B : AddAbGroup} variables (X : Set) {l l' : list (X ⊎ X)} section parameters {I : Set} (Y : I → AddAbGroup) variables {A' : AddAbGroup} {Y' : I → AddAbGroup} definition dirsum_carrier : AddAbGroup := free_ab_group (trunctype.mk (Σi, Y i) _) local abbreviation ι [constructor] := @free_ab_group_inclusion inductive dirsum_rel : dirsum_carrier → Type := | rmk : Πi y₁ y₂, dirsum_rel (ι ⟨i, y₁⟩ + ι ⟨i, y₂⟩ + -(ι ⟨i, y₁ + y₂⟩)) definition dirsum : AddAbGroup := quotient_ab_group_gen dirsum_carrier (λg, ∥dirsum_rel g∥) -- definition dirsum_carrier_incl [constructor] (i : I) : Y i →a dirsum_carrier := definition dirsum_incl [constructor] (i : I) : Y i →a dirsum := add_homomorphism.mk (λy, class_of (ι ⟨i, y⟩)) begin intro g h, symmetry, apply gqg_eq_of_rel, apply tr, apply dirsum_rel.rmk end parameter {Y} definition dirsum.rec {P : dirsum → Type} [H : Πg, is_prop (P g)] (h₁ : Πi (y : Y i), P (dirsum_incl i y)) (h₂ : P 0) (h₃ : Πg h, P g → P h → P (g + h)) : Πg, P g := begin refine @set_quotient.rec_prop _ _ _ H _, refine @set_quotient.rec_prop _ _ _ (λx, !H) _, esimp, intro l, induction l with s l ih, exact h₂, induction s with v v, induction v with i y, exact h₃ _ _ (h₁ i y) ih, induction v with i y, refine h₃ (gqg_map _ _ (class_of [inr ⟨i, y⟩])) _ _ ih, refine transport P _ (h₁ i (-y)), refine _ ⬝ !one_mul, refine _ ⬝ ap (λx, mul x _) (to_respect_zero (dirsum_incl i)), apply gqg_eq_of_rel', apply tr, esimp, refine transport dirsum_rel _ (dirsum_rel.rmk i (-y) y), rewrite [add.left_inv, add.assoc], end definition dirsum_homotopy {φ ψ : dirsum →a A'} (h : Πi (y : Y i), φ (dirsum_incl i y) = ψ (dirsum_incl i y)) : φ ~ ψ := begin refine dirsum.rec _ _ _, exact h, refine !to_respect_zero ⬝ !to_respect_zero⁻¹, intro g₁ g₂ h₁ h₂, rewrite [+ to_respect_add', h₁, h₂] end definition dirsum_elim_resp_quotient (f : Πi, Y i →a A') (g : dirsum_carrier) (r : ∥dirsum_rel g∥) : free_ab_group_elim (λv, f v.1 v.2) g = 1 := begin induction r with r, induction r, rewrite [to_respect_add, to_respect_neg, to_respect_add, ▸*, ↑foldl, +one_mul, to_respect_add'], apply mul.right_inv end definition dirsum_elim [constructor] (f : Πi, Y i →a A') : dirsum →a A' := gqg_elim _ (free_ab_group_elim (λv, f v.1 v.2)) (dirsum_elim_resp_quotient f) definition dirsum_elim_compute (f : Πi, Y i →a A') (i : I) : dirsum_elim f ∘g dirsum_incl i ~ f i := begin intro g, apply zero_add end definition dirsum_elim_unique (f : Πi, Y i →a A') (k : dirsum →a A') (H : Πi, k ∘g dirsum_incl i ~ f i) : k ~ dirsum_elim f := begin apply gqg_elim_unique, apply free_ab_group_elim_unique, intro x, induction x with i y, exact H i y end end variables {I J : Set} {Y Y' Y'' : I → AddAbGroup} definition dirsum_functor [constructor] (f : Πi, Y i →a Y' i) : dirsum Y →a dirsum Y' := dirsum_elim (λi, dirsum_incl Y' i ∘g f i) theorem dirsum_functor_compose (f' : Πi, Y' i →a Y'' i) (f : Πi, Y i →a Y' i) : dirsum_functor f' ∘a dirsum_functor f ~ dirsum_functor (λi, f' i ∘a f i) := begin apply dirsum_homotopy, intro i y, reflexivity, end variable (Y) definition dirsum_functor_gid : dirsum_functor (λi, aid (Y i)) ~ aid (dirsum Y) := begin apply dirsum_homotopy, intro i y, reflexivity, end variable {Y} definition dirsum_functor_add (f f' : Πi, Y i →a Y' i) : homomorphism_add (dirsum_functor f) (dirsum_functor f') ~ dirsum_functor (λi, homomorphism_add (f i) (f' i)) := begin apply dirsum_homotopy, intro i y, esimp, exact sorry end definition dirsum_functor_homotopy {f f' : Πi, Y i →a Y' i} (p : f ~2 f') : dirsum_functor f ~ dirsum_functor f' := begin apply dirsum_homotopy, intro i y, exact sorry end definition dirsum_functor_left [constructor] (f : J → I) : dirsum (Y ∘ f) →a dirsum Y := dirsum_elim (λj, dirsum_incl Y (f j)) end group
49e7f9d936062bdc9b09d6c5699e6d460a41d506
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/archive/imo/imo1998_q2.lean
65c26a8300a959a9e335df42aec0605588c07a62
[ "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
9,571
lean
/- Copyright (c) 2020 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import data.fintype.basic import data.int.parity import algebra.big_operators.order import tactic.ring import tactic.noncomm_ring /-! # IMO 1998 Q2 In a competition, there are `a` contestants and `b` judges, where `b ≥ 3` is an odd integer. Each judge rates each contestant as either "pass" or "fail". Suppose `k` is a number such that, for any two judges, their ratings coincide for at most `k` contestants. Prove that `k / a ≥ (b - 1) / (2b)`. ## Solution The problem asks us to think about triples consisting of a contestant and two judges whose ratings agree for that contestant. We thus consider the subset `A ⊆ C × JJ` of all such incidences of agreement, where `C` and `J` are the sets of contestants and judges, and `JJ = J × J − {(j, j)}`. We have natural maps: `left : A → C` and `right: A → JJ`. We count the elements of `A` in two ways: as the sum of the cardinalities of the fibres of `left` and as the sum of the cardinalities of the fibres of `right`. We obtain an upper bound on the cardinality of `A` from the count for `right`, and a lower bound from the count for `left`. These two bounds combine to the required result. First consider the map `right : A → JJ`. Since the size of any fibre over a point in JJ is bounded by `k` and since `|JJ| = b^2 - b`, we obtain the upper bound: `|A| ≤ k(b^2−b)`. Now consider the map `left : A → C`. The fibre over a given contestant `c ∈ C` is the set of ordered pairs of (distinct) judges who agree about `c`. We seek to bound the cardinality of this fibre from below. Minimum agreement for a contestant occurs when the judges' ratings are split as evenly as possible. Since `b` is odd, this occurs when they are divided into groups of size `(b−1)/2` and `(b+1)/2`. This corresponds to a fibre of cardinality `(b-1)^2/2` and so we obtain the lower bound: `a(b-1)^2/2 ≤ |A|`. Rearranging gives the result. -/ open_locale classical noncomputable theory /-- An ordered pair of judges. -/ abbreviation judge_pair (J : Type*) := J × J /-- A triple consisting of contestant together with an ordered pair of judges. -/ abbreviation agreed_triple (C J : Type*) := C × (judge_pair J) variables {C J : Type*} (r : C → J → Prop) /-- The first judge from an ordered pair of judges. -/ abbreviation judge_pair.judge₁ : judge_pair J → J := prod.fst /-- The second judge from an ordered pair of judges. -/ abbreviation judge_pair.judge₂ : judge_pair J → J := prod.snd /-- The proposition that the judges in an ordered pair are distinct. -/ abbreviation judge_pair.distinct (p : judge_pair J) := p.judge₁ ≠ p.judge₂ /-- The proposition that the judges in an ordered pair agree about a contestant's rating. -/ abbreviation judge_pair.agree (p : judge_pair J) (c : C) := r c p.judge₁ ↔ r c p.judge₂ /-- The contestant from the triple consisting of a contestant and an ordered pair of judges. -/ abbreviation agreed_triple.contestant : agreed_triple C J → C := prod.fst /-- The ordered pair of judges from the triple consisting of a contestant and an ordered pair of judges. -/ abbreviation agreed_triple.judge_pair : agreed_triple C J → judge_pair J := prod.snd @[simp] lemma judge_pair.agree_iff_same_rating (p : judge_pair J) (c : C) : p.agree r c ↔ (r c p.judge₁ ↔ r c p.judge₂) := iff.rfl /-- The set of contestants on which two judges agree. -/ def agreed_contestants [fintype C] (p : judge_pair J) : finset C := finset.univ.filter (λ c, p.agree r c) section variables [fintype J] [fintype C] /-- All incidences of agreement. -/ def A : finset (agreed_triple C J) := finset.univ.filter (λ (a : agreed_triple C J), a.judge_pair.agree r a.contestant ∧ a.judge_pair.distinct) lemma A_maps_to_off_diag_judge_pair (a : agreed_triple C J) : a ∈ A r → a.judge_pair ∈ finset.off_diag (@finset.univ J _) := by simp [A, finset.mem_off_diag] lemma A_fibre_over_contestant (c : C) : finset.univ.filter (λ (p : judge_pair J), p.agree r c ∧ p.distinct) = ((A r).filter (λ (a : agreed_triple C J), a.contestant = c)).image prod.snd := begin ext p, simp only [A, finset.mem_univ, finset.mem_filter, finset.mem_image, true_and, exists_prop], split, { rintros ⟨h₁, h₂⟩, refine ⟨(c, p), _⟩, finish, }, { intros h, finish, }, end lemma A_fibre_over_contestant_card (c : C) : (finset.univ.filter (λ (p : judge_pair J), p.agree r c ∧ p.distinct)).card = ((A r).filter (λ (a : agreed_triple C J), a.contestant = c)).card := by { rw A_fibre_over_contestant r, apply finset.card_image_of_inj_on, tidy, } lemma A_fibre_over_judge_pair {p : judge_pair J} (h : p.distinct) : agreed_contestants r p = ((A r).filter(λ (a : agreed_triple C J), a.judge_pair = p)).image agreed_triple.contestant := begin dunfold A agreed_contestants, ext c, split; intros h, { rw finset.mem_image, refine ⟨⟨c, p⟩, _⟩, finish, }, { finish, }, end lemma A_fibre_over_judge_pair_card {p : judge_pair J} (h : p.distinct) : (agreed_contestants r p).card = ((A r).filter(λ (a : agreed_triple C J), a.judge_pair = p)).card := by { rw A_fibre_over_judge_pair r h, apply finset.card_image_of_inj_on, tidy, } lemma A_card_upper_bound {k : ℕ} (hk : ∀ (p : judge_pair J), p.distinct → (agreed_contestants r p).card ≤ k) : (A r).card ≤ k * ((fintype.card J) * (fintype.card J) - (fintype.card J)) := begin change _ ≤ k * ((finset.card _ ) * (finset.card _ ) - (finset.card _ )), rw ← finset.off_diag_card, apply finset.card_le_mul_card_image_of_maps_to (A_maps_to_off_diag_judge_pair r), intros p hp, have hp' : p.distinct, { simp [finset.mem_off_diag] at hp, exact hp, }, rw ← A_fibre_over_judge_pair_card r hp', apply hk, exact hp', end end lemma add_sq_add_sq_sub {α : Type*} [ring α] (x y : α) : (x + y) * (x + y) + (x - y) * (x - y) = 2*x*x + 2*y*y := by noncomm_ring lemma norm_bound_of_odd_sum {x y z : ℤ} (h : x + y = 2*z + 1) : 2*z*z + 2*z + 1 ≤ x*x + y*y := begin suffices : 4*z*z + 4*z + 1 + 1 ≤ 2*x*x + 2*y*y, { rw ← mul_le_mul_left (@zero_lt_two _ _ int.nontrivial), convert this; ring, }, have h' : (x + y) * (x + y) = 4*z*z + 4*z + 1, { rw h, ring, }, rw [← add_sq_add_sq_sub, h', add_le_add_iff_left], suffices : 0 < (x - y) * (x - y), { apply int.add_one_le_of_lt this, }, apply mul_self_pos, rw sub_ne_zero, apply int.ne_of_odd_add ⟨z, h⟩, end section variables [fintype J] lemma judge_pairs_card_lower_bound {z : ℕ} (hJ : fintype.card J = 2*z + 1) (c : C) : 2*z*z + 2*z + 1 ≤ (finset.univ.filter (λ (p : judge_pair J), p.agree r c)).card := begin let x := (finset.univ.filter (λ j, r c j)).card, let y := (finset.univ.filter (λ j, ¬ r c j)).card, have h : (finset.univ.filter (λ (p : judge_pair J), p.agree r c)).card = x*x + y*y, { simp [← finset.filter_product_card], }, rw h, apply int.le_of_coe_nat_le_coe_nat, simp only [int.coe_nat_add, int.coe_nat_mul], apply norm_bound_of_odd_sum, suffices : x + y = 2*z + 1, { simp [← int.coe_nat_add, this], }, rw [finset.filter_card_add_filter_neg_card_eq_card, ← hJ], refl, end lemma distinct_judge_pairs_card_lower_bound {z : ℕ} (hJ : fintype.card J = 2*z + 1) (c : C) : 2*z*z ≤ (finset.univ.filter (λ (p : judge_pair J), p.agree r c ∧ p.distinct)).card := begin let s := finset.univ.filter (λ (p : judge_pair J), p.agree r c), let t := finset.univ.filter (λ (p : judge_pair J), p.distinct), have hs : 2*z*z + 2*z + 1 ≤ s.card, { exact judge_pairs_card_lower_bound r hJ c, }, have hst : s \ t = finset.univ.diag, { ext p, split; intros, { finish, }, { suffices : p.judge₁ = p.judge₂, { simp [this], }, finish, }, }, have hst' : (s \ t).card = 2*z + 1, { rw [hst, finset.diag_card, ← hJ], refl, }, rw [finset.filter_and, ← finset.sdiff_sdiff_self_left s t, finset.card_sdiff], { rw hst', rw add_assoc at hs, apply le_tsub_of_add_le_right hs, }, { apply finset.sdiff_subset, }, end lemma A_card_lower_bound [fintype C] {z : ℕ} (hJ : fintype.card J = 2*z + 1) : 2*z*z * (fintype.card C) ≤ (A r).card := begin have h : ∀ a, a ∈ A r → prod.fst a ∈ @finset.univ C _, { intros, apply finset.mem_univ, }, apply finset.mul_card_image_le_card_of_maps_to h, intros c hc, rw ← A_fibre_over_contestant_card, apply distinct_judge_pairs_card_lower_bound r hJ, end end local notation x `/` y := (x : ℚ) / y lemma clear_denominators {a b k : ℕ} (ha : 0 < a) (hb : 0 < b) : (b - 1) / (2 * b) ≤ k / a ↔ (b - 1) * a ≤ k * (2 * b) := by rw div_le_div_iff; norm_cast; simp [ha, hb] theorem imo1998_q2 [fintype J] [fintype C] (a b k : ℕ) (hC : fintype.card C = a) (hJ : fintype.card J = b) (ha : 0 < a) (hb : odd b) (hk : ∀ (p : judge_pair J), p.distinct → (agreed_contestants r p).card ≤ k) : (b - 1) / (2 * b) ≤ k / a := begin rw clear_denominators ha (nat.odd_gt_zero hb), obtain ⟨z, hz⟩ := hb, rw hz at hJ, rw hz, have h := le_trans (A_card_lower_bound r hJ) (A_card_upper_bound r hk), rw [hC, hJ] at h, -- We are now essentially done; we just need to bash `h` into exactly the right shape. have hl : k * ((2 * z + 1) * (2 * z + 1) - (2 * z + 1)) = (k * (2 * (2 * z + 1))) * z, { simp only [add_mul, two_mul, mul_comm, mul_assoc], finish, }, have hr : 2 * z * z * a = 2 * z * a * z, { ring, }, rw [hl, hr] at h, cases z, { simp, }, { exact le_of_mul_le_mul_right h z.succ_pos, }, end
54dea10cec210e8d7d22d5d69a9fdddf19c648bf
4b264bd060cfaad29c2dca34fa94c34f88a4d619
/colimit/move_to_lib.hlean
f7db1065be53f4f934105450c3c32c0918281c5f
[ "Apache-2.0" ]
permissive
UlrikBuchholtz/leansnippets
a0d2675f5173867a1b90c3b0e559af5152f2e96c
ee547e8b301c9364022937cdc4a1dbf2cb4b1162
refs/heads/master
1,611,460,071,315
1,441,903,237,000
1,441,903,237,000
41,886,729
0
0
null
1,441,319,113,000
1,441,319,113,000
null
UTF-8
Lean
false
false
4,048
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Egbert Rijke -/ -- these definitions and theorems should be moved to the HoTT library import types.nat open eq open nat open is_trunc open function namespace my definition add.assoc (n m : ℕ) : Πk, (n + m) + k = n + (m + k) := nat.rec (by reflexivity) (λk, ap succ) definition zero_add' : Πn : ℕ, n = 0 + n := nat.rec idp (λn, ap succ) definition is_hset_elim_triv (D : Type) [H : is_hset D] (x : D) : is_hset.elim (refl x) (refl x) = idp := begin apply is_hset.elim end definition pathover_ap_compose {A A₁ A₂ : Type} (B₂ : A₂ → Type) (g : A₁ → A₂) (f : A → A₁) {a a₂ : A} (p : a = a₂) {b : B₂ (g (f a))} {b₂ : B₂ (g (f a₂))} (q : b =[p] b₂) : pathover_ap B₂ (g ∘ f) q =[ap_compose g f p] pathover_ap B₂ g (pathover_ap (B₂ ∘ g) f q) := by induction q; constructor variables {A A' : Type} {B B' : A → Type} {C : Π⦃a⦄, B a → Type} {a a₂ a₃ a₄ : A} {p p' : a = a₂} {p₂ : a₂ = a₃} {p₃ : a₃ = a₄} {b b' : B a} {b₂ b₂' : B a₂} {b₃ : B a₃} {b₄ : B a₄} {c : C b} {c₂ : C b₂} definition change_path_pathover (q : p = p') (r : b =[p] b₂) : r =[q] change_path q r := begin induction q, apply pathover_idp_of_eq, reflexivity end definition tro_functor (s : p = p') {q : b =[p] b₂} {q' : b =[p'] b₂} (t : q =[s] q') (c : C b) : q ▸o c = q' ▸o c := by induction t; reflexivity definition pathover_idp_of_eq_tro (q : b = b') (c : C b) : pathover_idp_of_eq q ▸o c = transport (λy, C y) q c := by induction q; reflexivity definition apo011_invo {C : Type} (f : Πx, B x → C) (q : b =[p] b₂) : apo011 f p⁻¹ q⁻¹ᵒ = (apo011 f p q)⁻¹ := by induction q; reflexivity definition apdo_ap {D : Type} (g : D → A) (f : Πa, B a) {d d₂ : D} (p : d = d₂) : apdo f (ap g p) = pathover_ap B g (apdo (λx, f (g x)) p) := by induction p; reflexivity definition cast_apo011 {P : Πa, B a → Type} {Ha : a = a₂} (Hb : b =[Ha] b₂) (p : P a b) : cast (apo011 P Ha Hb) p = Hb ▸o p := by induction Hb; reflexivity definition fn_tro_eq_tro_fn {C' : Π ⦃a : A⦄, B a → Type} (q : b =[p] b₂) (f : Π⦃a : A⦄ (b : B a), C b → C' b) (c : C b) : f b₂ (q ▸o c) = (q ▸o (f b c)) := by induction q;reflexivity -- TODO: prove for generalized apo definition apo_tro (C : Π⦃a⦄, B' a → Type) (f : Π⦃a⦄, B a → B' a) (q : b =[p] b₂) (c : C (f b)) : apo f q ▸o c = q ▸o c := by induction q; reflexivity definition pathover_ap_tro {B' : A' → Type} (C : Π⦃a'⦄, B' a' → Type) (f : A → A') {b : B' (f a)} {b₂ : B' (f a₂)} (q : b =[p] b₂) (c : C b) : pathover_ap B' f q ▸o c = q ▸o c := by induction q; reflexivity definition pathover_ap_invo_tro {B' : A' → Type} (C : Π⦃a'⦄, B' a' → Type) (f : A → A') {b : B' (f a)} {b₂ : B' (f a₂)} (q : b =[p] b₂) (c : C b₂) : (pathover_ap B' f q)⁻¹ᵒ ▸o c = q⁻¹ᵒ ▸o c := by induction q; reflexivity -- TODO: prove for generalized apo definition apo_invo (f : Πa, B a → B' a) {Ha : a = a₂} (Hb : b =[Ha] b₂) : (apo f Hb)⁻¹ᵒ = apo f Hb⁻¹ᵒ := by induction Hb; reflexivity --not used definition pathover_ap_invo {B' : A' → Type} (f : A → A') {p : a = a₂} {b : B' (f a)} {b₂ : B' (f a₂)} (q : b =[p] b₂) : pathover_ap B' f q⁻¹ᵒ =[ap_inv f p] (pathover_ap B' f q)⁻¹ᵒ := by induction q; exact idpo definition apo_np {B' : A' → Type} (f : A → A') (g : Πx, B' (f x)) (Ha : a = a₂) : g a =[Ha] g a₂ := by induction Ha; exact idpo definition apo_np_tro {B' : A' → Type} (f : A → A') (g : Πx, B' (f x)) (Ha : a = a₂) (D : Π⦃x'⦄, B' x' → Type) (d : D (g a)) : apo_np f g Ha ▸o d = Ha ▸ d := by induction Ha; reflexivity end my
5dfc894c2c036e2823490ad502445c5171190310
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/monoidal/rigid/functor_category.lean
ef3315f137b3d7cb36b59a9bde3e90c77f9f6db6
[ "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
2,859
lean
/- Copyright (c) 2022 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.monoidal.rigid.basic import category_theory.monoidal.functor_category /-! # Functors from a groupoid into a right/left rigid category form a right/left rigid category. (Using the pointwise monoidal structure on the functor category.) -/ noncomputable theory open category_theory open category_theory.monoidal_category namespace category_theory.monoidal variables {C D : Type*} [groupoid C] [category D] [monoidal_category D] instance functor_has_right_dual [right_rigid_category D] (F : C ⥤ D) : has_right_dual F := { right_dual := { obj := λ X, (F.obj X)ᘁ, map := λ X Y f, (F.map (inv f))ᘁ, map_comp' := λ X Y Z f g, by { simp [comp_right_adjoint_mate], }, }, exact := { evaluation := { app := λ X, ε_ _ _, naturality' := λ X Y f, begin dsimp, rw [category.comp_id, functor.map_inv, ←id_tensor_comp_tensor_id, category.assoc, right_adjoint_mate_comp_evaluation, ←category.assoc, ←id_tensor_comp, is_iso.hom_inv_id, tensor_id, category.id_comp], end }, coevaluation := { app := λ X, η_ _ _, naturality' := λ X Y f, begin dsimp, rw [functor.map_inv, category.id_comp, ←id_tensor_comp_tensor_id, ←category.assoc, coevaluation_comp_right_adjoint_mate, category.assoc, ←comp_tensor_id, is_iso.inv_hom_id, tensor_id, category.comp_id], end, }, }, } instance right_rigid_functor_category [right_rigid_category D] : right_rigid_category (C ⥤ D) := {} instance functor_has_left_dual [left_rigid_category D] (F : C ⥤ D) : has_left_dual F := { left_dual := { obj := λ X, ᘁ(F.obj X), map := λ X Y f, ᘁ(F.map (inv f)), map_comp' := λ X Y Z f g, by { simp [comp_left_adjoint_mate], }, }, exact := { evaluation := { app := λ X, ε_ _ _, naturality' := λ X Y f, begin dsimp, rw [category.comp_id, functor.map_inv, ←tensor_id_comp_id_tensor, category.assoc, left_adjoint_mate_comp_evaluation, ←category.assoc, ←comp_tensor_id, is_iso.hom_inv_id, tensor_id, category.id_comp], end }, coevaluation := { app := λ X, η_ _ _, naturality' := λ X Y f, begin dsimp, rw [functor.map_inv, category.id_comp, ←tensor_id_comp_id_tensor, ←category.assoc, coevaluation_comp_left_adjoint_mate, category.assoc, ←id_tensor_comp, is_iso.inv_hom_id, tensor_id, category.comp_id], end, }, }, } instance left_rigid_functor_category [left_rigid_category D] : left_rigid_category (C ⥤ D) := {} instance rigid_functor_category [rigid_category D] : rigid_category (C ⥤ D) := {} end category_theory.monoidal
94834eb77703d29023a33e5192579fa25a54c4f3
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/system/io_interface.lean
834382a6f29b8619c8a13befabd50b03da4fe77a
[]
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
4,980
lean
/- Copyright (c) 2018 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.default import Mathlib.Lean3Lib.data.buffer import Mathlib.Lean3Lib.system.random universes l namespace Mathlib inductive io.error where | other : string → io.error | sys : ℕ → io.error inductive io.mode where | read : io.mode | write : io.mode | read_write : io.mode | append : io.mode inductive io.process.stdio where | piped : io.process.stdio | inherit : io.process.stdio | null : io.process.stdio /- Command name. -/ structure io.process.spawn_args where cmd : string args : List string stdin : io.process.stdio stdout : io.process.stdio stderr : io.process.stdio cwd : Option string env : List (string × Option string) /- Arguments for the process -/ /- Configuration for the process' stdin handle. -/ /- Configuration for the process' stdout handle. -/ /- Configuration for the process' stderr handle. -/ /- Working directory for the process. -/ /- Environment variables for the process. -/ class monad_io (m : Type → Type → Type) where monad : (e : Type) → Monad (m e) catch : (e₁ e₂ α : Type) → m e₁ α → (e₁ → m e₂ α) → m e₂ α fail : (e α : Type) → e → m e α iterate : (e α : Type) → α → (α → m e (Option α)) → m e α handle : Type -- TODO(Leo): use monad_except after it is merged -- Primitive Types class monad_io_terminal (m : Type → Type → Type) where put_str : string → m io.error Unit get_line : m io.error string cmdline_args : List string class monad_io_net_system (m : Type → Type → Type) [monad_io m] where socket : Type listen : string → ℕ → m io.error socket accept : socket → m io.error socket connect : string → m io.error socket recv : socket → ℕ → m io.error char_buffer send : socket → char_buffer → m io.error Unit close : socket → m io.error Unit /- Remark: in Haskell, they also provide (Maybe TextEncoding) and NewlineMode -/ class monad_io_file_system (m : Type → Type → Type) [monad_io m] where mk_file_handle : string → io.mode → Bool → m io.error (monad_io.handle m) is_eof : monad_io.handle m → m io.error Bool flush : monad_io.handle m → m io.error Unit close : monad_io.handle m → m io.error Unit read : monad_io.handle m → ℕ → m io.error char_buffer write : monad_io.handle m → char_buffer → m io.error Unit get_line : monad_io.handle m → m io.error char_buffer stdin : m io.error (monad_io.handle m) stdout : m io.error (monad_io.handle m) stderr : m io.error (monad_io.handle m) file_exists : string → m io.error Bool dir_exists : string → m io.error Bool remove : string → m io.error Unit rename : string → string → m io.error Unit mkdir : string → Bool → m io.error Bool rmdir : string → m io.error Bool class monad_io_environment (m : Type → Type → Type) where get_env : string → m io.error (Option string) get_cwd : m io.error string set_cwd : string → m io.error Unit -- we don't provide set_env as it is (thread-)unsafe (at least with glibc) class monad_io_process (m : Type → Type → Type) [monad_io m] where child : Type stdin : child → monad_io.handle m stdout : child → monad_io.handle m stderr : child → monad_io.handle m spawn : io.process.spawn_args → m io.error child wait : child → m io.error ℕ sleep : ℕ → m io.error Unit class monad_io_random (m : Type → Type → Type) where set_rand_gen : std_gen → m io.error Unit rand : ℕ → ℕ → m io.error ℕ protected instance monad_io_is_monad (m : Type → Type → Type) (e : Type) [monad_io m] : Monad (m e) := monad_io.monad e protected instance monad_io_is_monad_fail (m : Type → Type → Type) [monad_io m] : monad_fail (m io.error) := monad_fail.mk fun (α : Type) (s : string) => monad_io.fail io.error α (io.error.other s) protected instance monad_io_is_alternative (m : Type → Type → Type) [monad_io m] : alternative (m io.error) := alternative.mk fun (α : Type) => monad_io.fail io.error α (io.error.other (string.str (string.str (string.str (string.str (string.str (string.str (string.str string.empty (char.of_nat (bit0 (bit1 (bit1 (bit0 (bit0 (bit1 1)))))))) (char.of_nat (bit1 (bit0 (bit0 (bit0 (bit0 (bit1 1)))))))) (char.of_nat (bit1 (bit0 (bit0 (bit1 (bit0 (bit1 1)))))))) (char.of_nat (bit0 (bit0 (bit1 (bit1 (bit0 (bit1 1)))))))) (char.of_nat (bit1 (bit0 (bit1 (bit0 (bit1 (bit1 1)))))))) (char.of_nat (bit0 (bit1 (bit0 (bit0 (bit1 (bit1 1)))))))) (char.of_nat (bit1 (bit0 (bit1 (bit0 (bit0 (bit1 1)))))))))
38eb2b7dcabdec662b093970dfff0af88af8f788
aa5a655c05e5359a70646b7154e7cac59f0b4132
/stage0/src/Lean/Meta/Match/MatcherInfo.lean
013ba30c2053ff82d813914563f42ebd4f6c13b6
[ "Apache-2.0" ]
permissive
lambdaxymox/lean4
ae943c960a42247e06eff25c35338268d07454cb
278d47c77270664ef29715faab467feac8a0f446
refs/heads/master
1,677,891,867,340
1,612,500,005,000
1,612,500,005,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,930
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.Basic namespace Lean.Meta namespace Match /-- A "matcher" auxiliary declaration has the following structure: - `numParams` parameters - motive - `numDiscrs` discriminators (aka major premises) - `altNumParams.size` alternatives (aka minor premises) where alternative `i` has `altNumParams[i]` parameters - `uElimPos?` is `some pos` when the matcher can eliminate in different universe levels, and `pos` is the position of the universe level parameter that specifies the elimination universe. It is `none` if the matcher only eliminates into `Prop`. -/ structure MatcherInfo where numParams : Nat numDiscrs : Nat altNumParams : Array Nat uElimPos? : Option Nat def MatcherInfo.numAlts (matcherInfo : MatcherInfo) : Nat := matcherInfo.altNumParams.size namespace Extension structure Entry where name : Name info : MatcherInfo structure State where map : SMap Name MatcherInfo := {} instance : Inhabited State := ⟨{}⟩ def State.addEntry (s : State) (e : Entry) : State := { s with map := s.map.insert e.name e.info } def State.switch (s : State) : State := { s with map := s.map.switch } builtin_initialize extension : SimplePersistentEnvExtension Entry State ← registerSimplePersistentEnvExtension { name := `matcher, addEntryFn := State.addEntry, addImportedFn := fun es => (mkStateFromImportedEntries State.addEntry {} es).switch } def addMatcherInfo (env : Environment) (matcherName : Name) (info : MatcherInfo) : Environment := extension.addEntry env { name := matcherName, info := info } def getMatcherInfo? (env : Environment) (declName : Name) : Option MatcherInfo := (extension.getState env).map.find? declName end Extension def addMatcherInfo (matcherName : Name) (info : MatcherInfo) : MetaM Unit := modifyEnv fun env => Extension.addMatcherInfo env matcherName info end Match export Match (MatcherInfo) def getMatcherInfo? (declName : Name) : MetaM (Option MatcherInfo) := do let env ← getEnv pure $ Match.Extension.getMatcherInfo? env declName def isMatcher (declName : Name) : MetaM Bool := do let info? ← getMatcherInfo? declName pure info?.isSome structure MatcherApp where matcherName : Name matcherLevels : Array Level uElimPos? : Option Nat params : Array Expr motive : Expr discrs : Array Expr altNumParams : Array Nat alts : Array Expr remaining : Array Expr def matchMatcherApp? (e : Expr) : MetaM (Option MatcherApp) := match e.getAppFn with | Expr.const declName declLevels _ => do let some info ← getMatcherInfo? declName | pure none let args := e.getAppArgs if args.size < info.numParams + 1 + info.numDiscrs + info.numAlts then pure none else pure $ some { matcherName := declName, matcherLevels := declLevels.toArray, uElimPos? := info.uElimPos?, params := args.extract 0 info.numParams, motive := args.get! info.numParams, discrs := args.extract (info.numParams + 1) (info.numParams + 1 + info.numDiscrs), altNumParams := info.altNumParams, alts := args.extract (info.numParams + 1 + info.numDiscrs) (info.numParams + 1 + info.numDiscrs + info.numAlts), remaining := args.extract (info.numParams + 1 + info.numDiscrs + info.numAlts) args.size } | _ => pure none def MatcherApp.toExpr (matcherApp : MatcherApp) : Expr := let result := mkAppN (mkConst matcherApp.matcherName matcherApp.matcherLevels.toList) matcherApp.params let result := mkApp result matcherApp.motive let result := mkAppN result matcherApp.discrs let result := mkAppN result matcherApp.alts mkAppN result matcherApp.remaining end Lean.Meta
b6c15eba99cb923342dfe54850b59b8d5c686915
4fa161becb8ce7378a709f5992a594764699e268
/src/data/equiv/encodable.lean
a5bc290d05c451f16fe26edf876bddb46652d186
[ "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
14,722
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, Mario Carneiro Type class for encodable Types. Note that every encodable Type is countable. -/ import data.equiv.nat import order.order_iso open option list nat function /-- An encodable type is a "constructively countable" type. This is where we have an explicit injection `encode : α → nat` and a partial inverse `decode : nat → option α`. This makes the range of `encode` decidable, although it is not decidable if `α` is finite or not. -/ class encodable (α : Type*) := (encode : α → nat) (decode [] : nat → option α) (encodek : ∀ a, decode (encode a) = some a) attribute [simp] encodable.encodek namespace encodable variables {α : Type*} {β : Type*} universe u open encodable theorem encode_injective [encodable α] : function.injective (@encode α _) | x y e := option.some.inj $ by rw [← encodek, e, encodek] /- This is not set as an instance because this is usually not the best way to infer decidability. -/ def decidable_eq_of_encodable (α) [encodable α] : decidable_eq α | a b := decidable_of_iff _ encode_injective.eq_iff def of_left_injection [encodable α] (f : β → α) (finv : α → option β) (linv : ∀ b, finv (f b) = some b) : encodable β := ⟨λ b, encode (f b), λ n, (decode α n).bind finv, λ b, by simp [encodable.encodek, linv]⟩ def of_left_inverse [encodable α] (f : β → α) (finv : α → β) (linv : ∀ b, finv (f b) = b) : encodable β := of_left_injection f (some ∘ finv) (λ b, congr_arg some (linv b)) /-- If `α` is encodable and `β ≃ α`, then so is `β` -/ def of_equiv (α) [encodable α] (e : β ≃ α) : encodable β := of_left_inverse e e.symm e.left_inv @[simp] theorem encode_of_equiv {α β} [encodable α] (e : β ≃ α) (b : β) : @encode _ (of_equiv _ e) b = encode (e b) := rfl @[simp] theorem decode_of_equiv {α β} [encodable α] (e : β ≃ α) (n : ℕ) : @decode _ (of_equiv _ e) n = (decode α n).map e.symm := rfl instance nat : encodable nat := ⟨id, some, λ a, rfl⟩ @[simp] theorem encode_nat (n : ℕ) : encode n = n := rfl @[simp] theorem decode_nat (n : ℕ) : decode ℕ n = some n := rfl instance empty : encodable empty := ⟨λ a, a.rec _, λ n, none, λ a, a.rec _⟩ instance unit : encodable punit := ⟨λ_, zero, λn, nat.cases_on n (some punit.star) (λ _, none), λ⟨⟩, by simp⟩ @[simp] theorem encode_star : encode punit.star = 0 := rfl @[simp] theorem decode_unit_zero : decode punit 0 = some punit.star := rfl @[simp] theorem decode_unit_succ (n) : decode punit (succ n) = none := rfl instance option {α : Type*} [h : encodable α] : encodable (option α) := ⟨λ o, option.cases_on o nat.zero (λ a, succ (encode a)), λ n, nat.cases_on n (some none) (λ m, (decode α m).map some), λ o, by cases o; dsimp; simp [encodek, nat.succ_ne_zero]⟩ @[simp] theorem encode_none [encodable α] : encode (@none α) = 0 := rfl @[simp] theorem encode_some [encodable α] (a : α) : encode (some a) = succ (encode a) := rfl @[simp] theorem decode_option_zero [encodable α] : decode (option α) 0 = some none := rfl @[simp] theorem decode_option_succ [encodable α] (n) : decode (option α) (succ n) = (decode α n).map some := rfl def decode2 (α) [encodable α] (n : ℕ) : option α := (decode α n).bind (option.guard (λ a, encode a = n)) theorem mem_decode2' [encodable α] {n : ℕ} {a : α} : a ∈ decode2 α n ↔ a ∈ decode α n ∧ encode a = n := by simp [decode2]; exact ⟨λ ⟨_, h₁, rfl, h₂⟩, ⟨h₁, h₂⟩, λ ⟨h₁, h₂⟩, ⟨_, h₁, rfl, h₂⟩⟩ theorem mem_decode2 [encodable α] {n : ℕ} {a : α} : a ∈ decode2 α n ↔ encode a = n := mem_decode2'.trans (and_iff_right_of_imp $ λ e, e ▸ encodek _) theorem decode2_is_partial_inv [encodable α] : is_partial_inv encode (decode2 α) := λ a n, mem_decode2 theorem decode2_inj [encodable α] {n : ℕ} {a₁ a₂ : α} (h₁ : a₁ ∈ decode2 α n) (h₂ : a₂ ∈ decode2 α n) : a₁ = a₂ := encode_injective $ (mem_decode2.1 h₁).trans (mem_decode2.1 h₂).symm theorem encodek2 [encodable α] (a : α) : decode2 α (encode a) = some a := mem_decode2.2 rfl def decidable_range_encode (α : Type*) [encodable α] : decidable_pred (set.range (@encode α _)) := λ x, decidable_of_iff (option.is_some (decode2 α x)) ⟨λ h, ⟨option.get h, by rw [← decode2_is_partial_inv (option.get h), option.some_get]⟩, λ ⟨n, hn⟩, by rw [← hn, encodek2]; exact rfl⟩ def equiv_range_encode (α : Type*) [encodable α] : α ≃ set.range (@encode α _) := { to_fun := λ a : α, ⟨encode a, set.mem_range_self _⟩, inv_fun := λ n, option.get (show is_some (decode2 α n.1), by cases n.2 with x hx; rw [← hx, encodek2]; exact rfl), left_inv := λ a, by dsimp; rw [← option.some_inj, option.some_get, encodek2], right_inv := λ ⟨n, x, hx⟩, begin apply subtype.eq, dsimp, conv {to_rhs, rw ← hx}, rw [encode_injective.eq_iff, ← option.some_inj, option.some_get, ← hx, encodek2], end } section sum variables [encodable α] [encodable β] def encode_sum : α ⊕ β → nat | (sum.inl a) := bit0 $ encode a | (sum.inr b) := bit1 $ encode b def decode_sum (n : nat) : option (α ⊕ β) := match bodd_div2 n with | (ff, m) := (decode α m).map sum.inl | (tt, m) := (decode β m).map sum.inr end instance sum : encodable (α ⊕ β) := ⟨encode_sum, decode_sum, λ s, by cases s; simp [encode_sum, decode_sum, encodek]; refl⟩ @[simp] theorem encode_inl (a : α) : @encode (α ⊕ β) _ (sum.inl a) = bit0 (encode a) := rfl @[simp] theorem encode_inr (b : β) : @encode (α ⊕ β) _ (sum.inr b) = bit1 (encode b) := rfl @[simp] theorem decode_sum_val (n : ℕ) : decode (α ⊕ β) n = decode_sum n := rfl end sum instance bool : encodable bool := of_equiv (unit ⊕ unit) equiv.bool_equiv_punit_sum_punit @[simp] theorem encode_tt : encode tt = 1 := rfl @[simp] theorem encode_ff : encode ff = 0 := rfl @[simp] theorem decode_zero : decode bool 0 = some ff := rfl @[simp] theorem decode_one : decode bool 1 = some tt := rfl theorem decode_ge_two (n) (h : 2 ≤ n) : decode bool n = none := begin suffices : decode_sum n = none, { change (decode_sum n).map _ = none, rw this, refl }, have : 1 ≤ div2 n, { rw [div2_val, nat.le_div_iff_mul_le], exacts [h, dec_trivial] }, cases exists_eq_succ_of_ne_zero (ne_of_gt this) with m e, simp [decode_sum]; cases bodd n; simp [decode_sum]; rw e; refl end section sigma variables {γ : α → Type*} [encodable α] [∀ a, encodable (γ a)] def encode_sigma : sigma γ → ℕ | ⟨a, b⟩ := mkpair (encode a) (encode b) def decode_sigma (n : ℕ) : option (sigma γ) := let (n₁, n₂) := unpair n in (decode α n₁).bind $ λ a, (decode (γ a) n₂).map $ sigma.mk a instance sigma : encodable (sigma γ) := ⟨encode_sigma, decode_sigma, λ ⟨a, b⟩, by simp [encode_sigma, decode_sigma, unpair_mkpair, encodek]⟩ @[simp] theorem decode_sigma_val (n : ℕ) : decode (sigma γ) n = (decode α n.unpair.1).bind (λ a, (decode (γ a) n.unpair.2).map $ sigma.mk a) := show decode_sigma._match_1 _ = _, by cases n.unpair; refl @[simp] theorem encode_sigma_val (a b) : @encode (sigma γ) _ ⟨a, b⟩ = mkpair (encode a) (encode b) := rfl end sigma section prod variables [encodable α] [encodable β] instance prod : encodable (α × β) := of_equiv _ (equiv.sigma_equiv_prod α β).symm @[simp] theorem decode_prod_val (n : ℕ) : decode (α × β) n = (decode α n.unpair.1).bind (λ a, (decode β n.unpair.2).map $ prod.mk a) := show (decode (sigma (λ _, β)) n).map (equiv.sigma_equiv_prod α β) = _, by simp; cases decode α n.unpair.1; simp; cases decode β n.unpair.2; refl @[simp] theorem encode_prod_val (a b) : @encode (α × β) _ (a, b) = mkpair (encode a) (encode b) := rfl end prod section subtype open subtype decidable variable {P : α → Prop} variable [encA : encodable α] variable [decP : decidable_pred P] include encA def encode_subtype : {a : α // P a} → nat | ⟨v, h⟩ := encode v include decP def decode_subtype (v : nat) : option {a : α // P a} := (decode α v).bind $ λ a, if h : P a then some ⟨a, h⟩ else none instance subtype : encodable {a : α // P a} := ⟨encode_subtype, decode_subtype, λ ⟨v, h⟩, by simp [encode_subtype, decode_subtype, encodek, h]⟩ lemma subtype.encode_eq (a : subtype P) : encode a = encode a.val := by cases a; refl end subtype instance fin (n) : encodable (fin n) := of_equiv _ (equiv.fin_equiv_subtype _) instance int : encodable ℤ := of_equiv _ equiv.int_equiv_nat instance ulift [encodable α] : encodable (ulift α) := of_equiv _ equiv.ulift instance plift [encodable α] : encodable (plift α) := of_equiv _ equiv.plift noncomputable def of_inj [encodable β] (f : α → β) (hf : injective f) : encodable α := of_left_injection f (partial_inv f) (λ x, (partial_inv_of_injective hf _ _).2 rfl) end encodable section ulower local attribute [instance, priority 100] encodable.decidable_range_encode /-- `ulower α : Type 0` is an equivalent type in the lowest universe, given `encodable α`. -/ @[derive decidable_eq, derive encodable] def ulower (α : Type*) [encodable α] : Type := set.range (encodable.encode : α → ℕ) end ulower namespace ulower variables (α : Type*) [encodable α] /-- The equivalence between the encodable type `α` and `ulower α : Type 0`. -/ def equiv : α ≃ ulower α := encodable.equiv_range_encode α variables {α} /-- Lowers an `a : α` into `ulower α`. -/ def down (a : α) : ulower α := equiv α a instance [inhabited α] : inhabited (ulower α) := ⟨down (default _)⟩ /-- Lifts an `a : ulower α` into `α`. -/ def up (a : ulower α) : α := (equiv α).symm a @[simp] lemma down_up {a : ulower α} : down a.up = a := equiv.right_inv _ _ @[simp] lemma up_down {a : α} : (down a).up = a := equiv.left_inv _ _ @[simp] lemma up_eq_up {a b : ulower α} : a.up = b.up ↔ a = b := equiv.apply_eq_iff_eq _ _ _ @[simp] lemma down_eq_down {a b : α} : down a = down b ↔ a = b := equiv.apply_eq_iff_eq _ _ _ @[ext] protected lemma ext {a b : ulower α} : a.up = b.up → a = b := up_eq_up.1 end ulower /- Choice function for encodable types and decidable predicates. We provide the following API choose {α : Type*} {p : α → Prop} [c : encodable α] [d : decidable_pred p] : (∃ x, p x) → α := choose_spec {α : Type*} {p : α → Prop} [c : encodable α] [d : decidable_pred p] (ex : ∃ x, p x) : p (choose ex) := -/ namespace encodable section find_a variables {α : Type*} (p : α → Prop) [encodable α] [decidable_pred p] private def good : option α → Prop | (some a) := p a | none := false private def decidable_good : decidable_pred (good p) | n := by cases n; unfold good; apply_instance local attribute [instance] decidable_good open encodable variable {p} def choose_x (h : ∃ x, p x) : {a:α // p a} := have ∃ n, good p (decode α n), from let ⟨w, pw⟩ := h in ⟨encode w, by simp [good, encodek, pw]⟩, match _, nat.find_spec this : ∀ o, good p o → {a // p a} with | some a, h := ⟨a, h⟩ end def choose (h : ∃ x, p x) : α := (choose_x h).1 lemma choose_spec (h : ∃ x, p x) : p (choose h) := (choose_x h).2 end find_a theorem axiom_of_choice {α : Type*} {β : α → Type*} {R : Π x, β x → Prop} [Π a, encodable (β a)] [∀ x y, decidable (R x y)] (H : ∀x, ∃y, R x y) : ∃f:Πa, β a, ∀x, R x (f x) := ⟨λ x, choose (H x), λ x, choose_spec (H x)⟩ theorem skolem {α : Type*} {β : α → Type*} {P : Π x, β x → Prop} [c : Π a, encodable (β a)] [d : ∀ x y, decidable (P x y)] : (∀x, ∃y, P x y) ↔ ∃f : Π a, β a, (∀x, P x (f x)) := ⟨axiom_of_choice, λ ⟨f, H⟩ x, ⟨_, H x⟩⟩ /- There is a total ordering on the elements of an encodable type, induced by the map to ℕ. -/ /-- The `encode` function, viewed as an embedding. -/ def encode' (α) [encodable α] : α ↪ nat := ⟨encodable.encode, encodable.encode_injective⟩ instance {α} [encodable α] : is_trans _ (encode' α ⁻¹'o (≤)) := (order_embedding.preimage _ _).is_trans instance {α} [encodable α] : is_antisymm _ (encodable.encode' α ⁻¹'o (≤)) := (order_embedding.preimage _ _).is_antisymm instance {α} [encodable α] : is_total _ (encodable.encode' α ⁻¹'o (≤)) := (order_embedding.preimage _ _).is_total end encodable namespace directed open encodable variables {α : Type*} {β : Type*} [encodable α] [inhabited α] /-- Given a `directed r` function `f : α → β` defined on an encodable inhabited type, construct a noncomputable sequence such that `r (f (x n)) (f (x (n + 1)))` and `r (f a) (f (x (encode a + 1))`. -/ protected noncomputable def sequence {r : β → β → Prop} (f : α → β) (hf : directed r f) : ℕ → α | 0 := default α | (n + 1) := let p := sequence n in match decode α n with | none := classical.some (hf p p) | (some a) := classical.some (hf p a) end lemma sequence_mono_nat {r : β → β → Prop} {f : α → β} (hf : directed r f) (n : ℕ) : r (f (hf.sequence f n)) (f (hf.sequence f (n+1))) := begin dsimp [directed.sequence], generalize eq : hf.sequence f n = p, cases h : decode α n with a, { exact (classical.some_spec (hf p p)).1 }, { exact (classical.some_spec (hf p a)).1 } end lemma rel_sequence {r : β → β → Prop} {f : α → β} (hf : directed r f) (a : α) : r (f a) (f (hf.sequence f (encode a + 1))) := begin simp only [directed.sequence, encodek], exact (classical.some_spec (hf _ a)).2 end variables [preorder β] {f : α → β} (hf : directed (≤) f) lemma sequence_mono : monotone (f ∘ (hf.sequence f)) := monotone_of_monotone_nat $ hf.sequence_mono_nat lemma le_sequence (a : α) : f a ≤ f (hf.sequence f (encode a + 1)) := hf.rel_sequence a end directed section quotient open encodable quotient variables {α : Type*} {s : setoid α} [@decidable_rel α (≈)] [encodable α] /-- Representative of an equivalence class. This is a computable version of `quot.out` for a setoid on an encodable type. -/ def quotient.rep (q : quotient s) : α := choose (exists_rep q) theorem quotient.rep_spec (q : quotient s) : ⟦q.rep⟧ = q := choose_spec (exists_rep q) /-- The quotient of an encodable space by a decidable equivalence relation is encodable. -/ def encodable_quotient : encodable (quotient s) := ⟨λ q, encode q.rep, λ n, quotient.mk <$> decode α n, by rintros ⟨l⟩; rw encodek; exact congr_arg some ⟦l⟧.rep_spec⟩ end quotient
2e811ef58dadc4dcd8f4b863d24e976150029029
798dd332c1ad790518589a09bc82459fb12e5156
/analysis/topology/topological_space.lean
dcdd0da52a7be82e615e28a4ff3e4778c8026364
[ "Apache-2.0" ]
permissive
tobiasgrosser/mathlib
b040b7eb42d5942206149371cf92c61404de3c31
120635628368ec261e031cefc6d30e0304088b03
refs/heads/master
1,644,803,442,937
1,536,663,752,000
1,536,663,907,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
58,054
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro Theory of topological spaces. Parts of the formalization is based on the books: N. Bourbaki: General Topology I. M. James: Topologies and Uniformities A major difference is that this formalization is heavily based on the filter library. -/ import order.filter data.set.countable tactic open set filter lattice classical local attribute [instance] prop_decidable universes u v w structure topological_space (α : Type u) := (is_open : set α → Prop) (is_open_univ : is_open univ) (is_open_inter : ∀s t, is_open s → is_open t → is_open (s ∩ t)) (is_open_sUnion : ∀s, (∀t∈s, is_open t) → is_open (⋃₀ s)) attribute [class] topological_space section topological_space variables {α : Type u} {β : Type v} {ι : Sort w} {a a₁ a₂ : α} {s s₁ s₂ : set α} {p p₁ p₂ : α → Prop} lemma topological_space_eq : ∀ {f g : topological_space α}, f.is_open = g.is_open → f = g | ⟨a, _, _, _⟩ ⟨b, _, _, _⟩ rfl := rfl section variables [t : topological_space α] include t /-- `is_open s` means that `s` is open in the ambient topological space on `α` -/ def is_open (s : set α) : Prop := topological_space.is_open t s @[simp] lemma is_open_univ : is_open (univ : set α) := topological_space.is_open_univ t lemma is_open_inter (h₁ : is_open s₁) (h₂ : is_open s₂) : is_open (s₁ ∩ s₂) := topological_space.is_open_inter t s₁ s₂ h₁ h₂ lemma is_open_sUnion {s : set (set α)} (h : ∀t ∈ s, is_open t) : is_open (⋃₀ s) := topological_space.is_open_sUnion t s h end lemma is_open_fold {s : set α} {t : topological_space α} : t.is_open s = @is_open α t s := rfl variables [topological_space α] lemma is_open_union (h₁ : is_open s₁) (h₂ : is_open s₂) : is_open (s₁ ∪ s₂) := have (⋃₀ {s₁, s₂}) = (s₁ ∪ s₂), by simp [union_comm], this ▸ is_open_sUnion $ show ∀(t : set α), t ∈ ({s₁, s₂} : set (set α)) → is_open t, by finish lemma is_open_Union {f : ι → set α} (h : ∀i, is_open (f i)) : is_open (⋃i, f i) := is_open_sUnion $ assume t ⟨i, (heq : t = f i)⟩, heq.symm ▸ h i lemma is_open_bUnion {s : set β} {f : β → set α} (h : ∀i∈s, is_open (f i)) : is_open (⋃i∈s, f i) := is_open_Union $ assume i, is_open_Union $ assume hi, h i hi @[simp] lemma is_open_empty : is_open (∅ : set α) := have is_open (⋃₀ ∅ : set α), from is_open_sUnion (assume a, false.elim), by simp at this; assumption lemma is_open_sInter {s : set (set α)} (hs : finite s) : (∀t ∈ s, is_open t) → is_open (⋂₀ s) := finite.induction_on hs (by simp) $ λ a s has hs ih h, begin suffices : is_open (a ∩ ⋂₀ s), { simpa }, exact is_open_inter (h _ $ mem_insert _ _) (ih $ assume t ht, h _ $ mem_insert_of_mem _ ht) end lemma is_open_bInter {s : set β} {f : β → set α} (hs : finite s) : (∀i∈s, is_open (f i)) → is_open (⋂i∈s, f i) := finite.induction_on hs (by simp) (by simp [or_imp_distrib, _root_.is_open_inter, forall_and_distrib] {contextual := tt}) lemma is_open_const {p : Prop} : is_open {a : α | p} := by_cases (assume : p, begin simp [*]; exact is_open_univ end) (assume : ¬ p, begin simp [*]; exact is_open_empty end) lemma is_open_and : is_open {a | p₁ a} → is_open {a | p₂ a} → is_open {a | p₁ a ∧ p₂ a} := is_open_inter /-- A set is closed if its complement is open -/ def is_closed (s : set α) : Prop := is_open (-s) @[simp] lemma is_closed_empty : is_closed (∅ : set α) := by simp [is_closed] @[simp] lemma is_closed_univ : is_closed (univ : set α) := by simp [is_closed] lemma is_closed_union : is_closed s₁ → is_closed s₂ → is_closed (s₁ ∪ s₂) := by simp [is_closed]; exact is_open_inter lemma is_closed_sInter {s : set (set α)} : (∀t ∈ s, is_closed t) → is_closed (⋂₀ s) := by simp [is_closed, compl_sInter]; exact assume h, is_open_Union $ assume t, is_open_Union $ assume ht, h t ht lemma is_closed_Inter {f : ι → set α} (h : ∀i, is_closed (f i)) : is_closed (⋂i, f i ) := is_closed_sInter $ assume t ⟨i, (heq : t = f i)⟩, heq.symm ▸ h i @[simp] lemma is_open_compl_iff {s : set α} : is_open (-s) ↔ is_closed s := iff.rfl @[simp] lemma is_closed_compl_iff {s : set α} : is_closed (-s) ↔ is_open s := by rw [←is_open_compl_iff, compl_compl] lemma is_open_diff {s t : set α} (h₁ : is_open s) (h₂ : is_closed t) : is_open (s \ t) := is_open_inter h₁ $ is_open_compl_iff.mpr h₂ lemma is_closed_inter (h₁ : is_closed s₁) (h₂ : is_closed s₂) : is_closed (s₁ ∩ s₂) := by rw [is_closed, compl_inter]; exact is_open_union h₁ h₂ lemma is_closed_Union {s : set β} {f : β → set α} (hs : finite s) : (∀i∈s, is_closed (f i)) → is_closed (⋃i∈s, f i) := finite.induction_on hs (by simp) (by simp [or_imp_distrib, is_closed_union, forall_and_distrib] {contextual := tt}) lemma is_closed_imp [topological_space α] {p q : α → Prop} (hp : is_open {x | p x}) (hq : is_closed {x | q x}) : is_closed {x | p x → q x} := have {x | p x → q x} = (- {x | p x}) ∪ {x | q x}, from set.ext $ by finish, by rw [this]; exact is_closed_union (is_closed_compl_iff.mpr hp) hq lemma is_open_neg : is_closed {a | p a} → is_open {a | ¬ p a} := is_open_compl_iff.mpr /-- The interior of a set `s` is the largest open subset of `s`. -/ def interior (s : set α) : set α := ⋃₀ {t | is_open t ∧ t ⊆ s} lemma mem_interior {s : set α} {x : α} : x ∈ interior s ↔ ∃ t ⊆ s, is_open t ∧ x ∈ t := by simp [interior, and_comm, and.left_comm] @[simp] lemma is_open_interior {s : set α} : is_open (interior s) := is_open_sUnion $ assume t ⟨h₁, h₂⟩, h₁ lemma interior_subset {s : set α} : interior s ⊆ s := sUnion_subset $ assume t ⟨h₁, h₂⟩, h₂ lemma interior_maximal {s t : set α} (h₁ : t ⊆ s) (h₂ : is_open t) : t ⊆ interior s := subset_sUnion_of_mem ⟨h₂, h₁⟩ lemma interior_eq_of_open {s : set α} (h : is_open s) : interior s = s := subset.antisymm interior_subset (interior_maximal (subset.refl s) h) lemma interior_eq_iff_open {s : set α} : interior s = s ↔ is_open s := ⟨assume h, h ▸ is_open_interior, interior_eq_of_open⟩ lemma subset_interior_iff_open {s : set α} : s ⊆ interior s ↔ is_open s := by simp [interior_eq_iff_open.symm, subset.antisymm_iff, interior_subset] lemma subset_interior_iff_subset_of_open {s t : set α} (h₁ : is_open s) : s ⊆ interior t ↔ s ⊆ t := ⟨assume h, subset.trans h interior_subset, assume h₂, interior_maximal h₂ h₁⟩ lemma interior_mono {s t : set α} (h : s ⊆ t) : interior s ⊆ interior t := interior_maximal (subset.trans interior_subset h) is_open_interior @[simp] lemma interior_empty : interior (∅ : set α) = ∅ := interior_eq_of_open is_open_empty @[simp] lemma interior_univ : interior (univ : set α) = univ := interior_eq_of_open is_open_univ @[simp] lemma interior_interior {s : set α} : interior (interior s) = interior s := interior_eq_of_open is_open_interior @[simp] lemma interior_inter {s t : set α} : interior (s ∩ t) = interior s ∩ interior t := subset.antisymm (subset_inter (interior_mono $ inter_subset_left s t) (interior_mono $ inter_subset_right s t)) (interior_maximal (inter_subset_inter interior_subset interior_subset) $ by simp [is_open_inter]) lemma interior_union_is_closed_of_interior_empty {s t : set α} (h₁ : is_closed s) (h₂ : interior t = ∅) : interior (s ∪ t) = interior s := have interior (s ∪ t) ⊆ s, from assume x ⟨u, ⟨(hu₁ : is_open u), (hu₂ : u ⊆ s ∪ t)⟩, (hx₁ : x ∈ u)⟩, classical.by_contradiction $ assume hx₂ : x ∉ s, have u \ s ⊆ t, from assume x ⟨h₁, h₂⟩, or.resolve_left (hu₂ h₁) h₂, have u \ s ⊆ interior t, by simp [subset_interior_iff_subset_of_open, this, is_open_diff hu₁ h₁], have u \ s ⊆ ∅, by rw [h₂] at this; assumption, this ⟨hx₁, hx₂⟩, subset.antisymm (interior_maximal this is_open_interior) (interior_mono $ subset_union_left _ _) lemma is_open_iff_forall_mem_open : is_open s ↔ ∀ x ∈ s, ∃ t ⊆ s, is_open t ∧ x ∈ t := by rw ← subset_interior_iff_open; simp [subset_def, mem_interior] /-- The closure of `s` is the smallest closed set containing `s`. -/ def closure (s : set α) : set α := ⋂₀ {t | is_closed t ∧ s ⊆ t} @[simp] lemma is_closed_closure {s : set α} : is_closed (closure s) := is_closed_sInter $ assume t ⟨h₁, h₂⟩, h₁ lemma subset_closure {s : set α} : s ⊆ closure s := subset_sInter $ assume t ⟨h₁, h₂⟩, h₂ lemma closure_minimal {s t : set α} (h₁ : s ⊆ t) (h₂ : is_closed t) : closure s ⊆ t := sInter_subset_of_mem ⟨h₂, h₁⟩ lemma closure_eq_of_is_closed {s : set α} (h : is_closed s) : closure s = s := subset.antisymm (closure_minimal (subset.refl s) h) subset_closure lemma closure_eq_iff_is_closed {s : set α} : closure s = s ↔ is_closed s := ⟨assume h, h ▸ is_closed_closure, closure_eq_of_is_closed⟩ lemma closure_subset_iff_subset_of_is_closed {s t : set α} (h₁ : is_closed t) : closure s ⊆ t ↔ s ⊆ t := ⟨subset.trans subset_closure, assume h, closure_minimal h h₁⟩ lemma closure_mono {s t : set α} (h : s ⊆ t) : closure s ⊆ closure t := closure_minimal (subset.trans h subset_closure) is_closed_closure @[simp] lemma closure_empty : closure (∅ : set α) = ∅ := closure_eq_of_is_closed is_closed_empty lemma closure_empty_iff (s : set α) : closure s = ∅ ↔ s = ∅ := begin split ; intro h, { rw set.eq_empty_iff_forall_not_mem, intros x H, simpa [h] using subset_closure H }, { exact (eq.symm h) ▸ closure_empty }, end @[simp] lemma closure_univ : closure (univ : set α) = univ := closure_eq_of_is_closed is_closed_univ @[simp] lemma closure_closure {s : set α} : closure (closure s) = closure s := closure_eq_of_is_closed is_closed_closure @[simp] lemma closure_union {s t : set α} : closure (s ∪ t) = closure s ∪ closure t := subset.antisymm (closure_minimal (union_subset_union subset_closure subset_closure) $ by simp [is_closed_union]) (union_subset (closure_mono $ subset_union_left _ _) (closure_mono $ subset_union_right _ _)) lemma interior_subset_closure {s : set α} : interior s ⊆ closure s := subset.trans interior_subset subset_closure lemma closure_eq_compl_interior_compl {s : set α} : closure s = - interior (- s) := begin simp [interior, closure], rw [compl_sUnion, compl_image_set_of], simp [compl_subset_compl] end @[simp] lemma interior_compl_eq {s : set α} : interior (- s) = - closure s := by simp [closure_eq_compl_interior_compl] @[simp] lemma closure_compl_eq {s : set α} : closure (- s) = - interior s := by simp [closure_eq_compl_interior_compl] lemma closure_compl {s : set α} : closure (-s) = - interior s := subset.antisymm (by simp [closure_subset_iff_subset_of_is_closed, compl_subset_compl, subset.refl]) begin rw [compl_subset_comm, subset_interior_iff_subset_of_open, compl_subset_comm], exact subset_closure, exact is_open_compl_iff.mpr is_closed_closure end lemma interior_compl {s : set α} : interior (-s) = - closure s := calc interior (- s) = - - interior (- s) : by simp ... = - closure (- (- s)) : by rw [closure_compl] ... = - closure s : by simp theorem mem_closure_iff {s : set α} {a : α} : a ∈ closure s ↔ ∀ o, is_open o → a ∈ o → o ∩ s ≠ ∅ := ⟨λ h o oo ao os, have s ⊆ -o, from λ x xs xo, @ne_empty_of_mem α (o∩s) x ⟨xo, xs⟩ os, closure_minimal this (is_closed_compl_iff.2 oo) h ao, λ H c ⟨h₁, h₂⟩, classical.by_contradiction $ λ nc, let ⟨x, hc, hs⟩ := exists_mem_of_ne_empty (H _ h₁ nc) in hc (h₂ hs)⟩ lemma dense_iff_inter_open {s : set α} : closure s = univ ↔ ∀ U, is_open U → U ≠ ∅ → U ∩ s ≠ ∅ := begin split ; intro h, { intros U U_op U_ne, cases exists_mem_of_ne_empty U_ne with x x_in, exact mem_closure_iff.1 (by simp[h]) U U_op x_in }, { ext x, suffices : x ∈ closure s, by simp [this], rw mem_closure_iff, intros U U_op x_in, exact h U U_op (ne_empty_of_mem x_in) }, end /-- The frontier of a set is the set of points between the closure and interior. -/ def frontier (s : set α) : set α := closure s \ interior s lemma frontier_eq_closure_inter_closure {s : set α} : frontier s = closure s ∩ closure (- s) := by rw [closure_compl, frontier, diff_eq] @[simp] lemma frontier_compl (s : set α) : frontier (-s) = frontier s := by simp [frontier_eq_closure_inter_closure, inter_comm] /-- neighbourhood filter -/ def nhds (a : α) : filter α := (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, principal s) lemma tendsto_nhds {m : β → α} {f : filter β} (h : ∀s, a ∈ s → is_open s → m ⁻¹' s ∈ f.sets) : tendsto m f (nhds a) := show map m f ≤ (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, principal s), from le_infi $ assume s, le_infi $ assume ⟨ha, hs⟩, le_principal_iff.mpr $ h s ha hs lemma tendsto_const_nhds {a : α} {f : filter β} : tendsto (λb:β, a) f (nhds a) := tendsto_nhds $ assume s ha hs, univ_mem_sets' $ assume _, ha lemma nhds_sets {a : α} : (nhds a).sets = {s | ∃t⊆s, is_open t ∧ a ∈ t} := calc (nhds a).sets = (⋃s∈{s : set α| a ∈ s ∧ is_open s}, (principal s).sets) : infi_sets_eq' (assume x ⟨hx₁, hx₂⟩ y ⟨hy₁, hy₂⟩, ⟨x ∩ y, ⟨⟨hx₁, hy₁⟩, is_open_inter hx₂ hy₂⟩, by simp⟩) ⟨univ, by simp⟩ ... = {s | ∃t⊆s, is_open t ∧ a ∈ t} : le_antisymm (supr_le $ assume i, supr_le $ assume ⟨hi₁, hi₂⟩ t ht, ⟨i, ht, hi₂, hi₁⟩) (assume t ⟨i, hi₁, hi₂, hi₃⟩, by simp; exact ⟨i, ⟨hi₃, hi₂⟩, hi₁⟩) lemma map_nhds {a : α} {f : α → β} : map f (nhds a) = (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, principal (image f s)) := calc map f (nhds a) = (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, map f (principal s)) : map_binfi_eq (assume x ⟨hx₁, hx₂⟩ y ⟨hy₁, hy₂⟩, ⟨x ∩ y, ⟨⟨hx₁, hy₁⟩, is_open_inter hx₂ hy₂⟩, by simp⟩) ⟨univ, by simp⟩ ... = _ : by simp lemma mem_nhds_sets_iff {a : α} {s : set α} : s ∈ (nhds a).sets ↔ ∃t⊆s, is_open t ∧ a ∈ t := by simp [nhds_sets] lemma mem_of_nhds {a : α} {s : set α} : s ∈ (nhds a).sets → a ∈ s := by simp [mem_nhds_sets_iff]; exact assume t ht _ hs, ht hs lemma mem_nhds_sets {a : α} {s : set α} (hs : is_open s) (ha : a ∈ s) : s ∈ (nhds a).sets := by simp [nhds_sets]; exact ⟨s, subset.refl _, hs, ha⟩ lemma pure_le_nhds : pure ≤ (nhds : α → filter α) := assume a, le_infi $ assume s, le_infi $ assume ⟨h₁, _⟩, principal_mono.mpr $ by simp [h₁] @[simp] lemma nhds_neq_bot {a : α} : nhds a ≠ ⊥ := assume : nhds a = ⊥, have return a = (⊥ : filter α), from lattice.bot_unique $ this ▸ pure_le_nhds a, pure_neq_bot this lemma interior_eq_nhds {s : set α} : interior s = {a | nhds a ≤ principal s} := set.ext $ by simp [mem_interior, nhds_sets] lemma mem_interior_iff_mem_nhds {s : set α} {a : α} : a ∈ interior s ↔ s ∈ (nhds a).sets := by simp [interior_eq_nhds] lemma is_open_iff_nhds {s : set α} : is_open s ↔ ∀a∈s, nhds a ≤ principal s := calc is_open s ↔ interior s = s : by rw [interior_eq_iff_open] ... ↔ s ⊆ interior s : ⟨assume h, by simp [*, subset.refl], subset.antisymm interior_subset⟩ ... ↔ (∀a∈s, nhds a ≤ principal s) : by rw [interior_eq_nhds]; refl lemma is_open_iff_mem_nhds {s : set α} : is_open s ↔ ∀a∈s, s ∈ (nhds a).sets := by simpa using @is_open_iff_nhds α _ _ lemma closure_eq_nhds {s : set α} : closure s = {a | nhds a ⊓ principal s ≠ ⊥} := calc closure s = - interior (- s) : closure_eq_compl_interior_compl ... = {a | ¬ nhds a ≤ principal (-s)} : by rw [interior_eq_nhds]; refl ... = {a | nhds a ⊓ principal s ≠ ⊥} : set.ext $ assume a, not_congr (inf_eq_bot_iff_le_compl (show principal s ⊔ principal (-s) = ⊤, by simp [principal_univ]) (by simp)).symm theorem mem_closure_iff_nhds {s : set α} {a : α} : a ∈ closure s ↔ ∀ t ∈ (nhds a).sets, t ∩ s ≠ ∅ := mem_closure_iff.trans ⟨λ H t ht, subset_ne_empty (inter_subset_inter_left _ interior_subset) (H _ is_open_interior (mem_interior_iff_mem_nhds.2 ht)), λ H o oo ao, H _ (mem_nhds_sets oo ao)⟩ lemma is_closed_iff_nhds {s : set α} : is_closed s ↔ ∀a, nhds a ⊓ principal s ≠ ⊥ → a ∈ s := calc is_closed s ↔ closure s = s : by rw [closure_eq_iff_is_closed] ... ↔ closure s ⊆ s : ⟨assume h, by simp [*, subset.refl], assume h, subset.antisymm h subset_closure⟩ ... ↔ (∀a, nhds a ⊓ principal s ≠ ⊥ → a ∈ s) : by rw [closure_eq_nhds]; refl lemma closure_inter_open {s t : set α} (h : is_open s) : s ∩ closure t ⊆ closure (s ∩ t) := assume a ⟨hs, ht⟩, have s ∈ (nhds a).sets, from mem_nhds_sets h hs, have nhds a ⊓ principal s = nhds a, from inf_of_le_left $ by simp [this], have nhds a ⊓ principal (s ∩ t) ≠ ⊥, from calc nhds a ⊓ principal (s ∩ t) = nhds a ⊓ (principal s ⊓ principal t) : by simp ... = nhds a ⊓ principal t : by rw [←inf_assoc, this] ... ≠ ⊥ : by rw [closure_eq_nhds] at ht; assumption, by rw [closure_eq_nhds]; assumption lemma closure_diff {s t : set α} : closure s - closure t ⊆ closure (s - t) := calc closure s \ closure t = (- closure t) ∩ closure s : by simp [diff_eq, inter_comm] ... ⊆ closure (- closure t ∩ s) : closure_inter_open $ is_open_compl_iff.mpr $ is_closed_closure ... = closure (s \ closure t) : by simp [diff_eq, inter_comm] ... ⊆ closure (s \ t) : closure_mono $ diff_subset_diff (subset.refl s) subset_closure lemma mem_of_closed_of_tendsto {f : β → α} {b : filter β} {a : α} {s : set α} (hb : b ≠ ⊥) (hf : tendsto f b (nhds a)) (hs : is_closed s) (h : f ⁻¹' s ∈ b.sets) : a ∈ s := have b.map f ≤ nhds a ⊓ principal s, from le_trans (le_inf (le_refl _) (le_principal_iff.mpr h)) (inf_le_inf hf (le_refl _)), is_closed_iff_nhds.mp hs a $ neq_bot_of_le_neq_bot (map_ne_bot hb) this lemma mem_closure_of_tendsto {f : β → α} {x : filter β} {a : α} {s : set α} (hf : tendsto f x (nhds a)) (hs : is_closed s) (h : x ⊓ principal (f ⁻¹' s) ≠ ⊥) : a ∈ s := is_closed_iff_nhds.mp hs _ $ neq_bot_of_le_neq_bot (@map_ne_bot _ _ _ f h) $ le_inf (le_trans (map_mono $ inf_le_left) hf) $ le_trans (map_mono $ inf_le_right_of_le $ by simp; exact subset.refl _) (@map_comap_le _ _ _ f) /- locally finite family [General Topology (Bourbaki, 1995)] -/ section locally_finite /-- A family of sets in `set α` is locally finite if at every point `x:α`, there is a neighborhood of `x` which meets only finitely many sets in the family -/ def locally_finite (f : β → set α) := ∀x:α, ∃t∈(nhds x).sets, finite {i | f i ∩ t ≠ ∅ } lemma locally_finite_of_finite {f : β → set α} (h : finite (univ : set β)) : locally_finite f := assume x, ⟨univ, univ_mem_sets, finite_subset h $ by simp⟩ lemma locally_finite_subset {f₁ f₂ : β → set α} (hf₂ : locally_finite f₂) (hf : ∀b, f₁ b ⊆ f₂ b) : locally_finite f₁ := assume a, let ⟨t, ht₁, ht₂⟩ := hf₂ a in ⟨t, ht₁, finite_subset ht₂ $ assume i hi, neq_bot_of_le_neq_bot hi $ inter_subset_inter (hf i) $ subset.refl _⟩ lemma is_closed_Union_of_locally_finite {f : β → set α} (h₁ : locally_finite f) (h₂ : ∀i, is_closed (f i)) : is_closed (⋃i, f i) := is_open_iff_nhds.mpr $ assume a, assume h : a ∉ (⋃i, f i), have ∀i, a ∈ -f i, from assume i hi, by simp at h; exact h i hi, have ∀i, - f i ∈ (nhds a).sets, by rw [nhds_sets]; exact assume i, ⟨- f i, subset.refl _, h₂ i, this i⟩, let ⟨t, h_sets, (h_fin : finite {i | f i ∩ t ≠ ∅ })⟩ := h₁ a in calc nhds a ≤ principal (t ∩ (⋂ i∈{i | f i ∩ t ≠ ∅ }, - f i)) : begin rw [le_principal_iff], apply @filter.inter_mem_sets _ (nhds a) _ _ h_sets, apply @filter.Inter_mem_sets _ (nhds a) _ _ _ h_fin, exact assume i h, this i end ... ≤ principal (- ⋃i, f i) : begin simp only [principal_mono, subset_def, mem_compl_eq, mem_inter_eq, mem_Inter, mem_set_of_eq, mem_Union, and_imp, not_exists, not_eq_empty_iff_exists, exists_imp_distrib, (≠)], exact assume x xt ht i xfi, ht i x xfi xt xfi end end locally_finite /- compact sets -/ section compact /-- A set `s` is compact if every filter that contains `s` also meets every neighborhood of some `a ∈ s`. -/ def compact (s : set α) := ∀f, f ≠ ⊥ → f ≤ principal s → ∃a∈s, f ⊓ nhds a ≠ ⊥ lemma compact_of_is_closed_subset {s t : set α} (hs : compact s) (ht : is_closed t) (h : t ⊆ s) : compact t := assume f hnf hsf, let ⟨a, hsa, (ha : f ⊓ nhds a ≠ ⊥)⟩ := hs f hnf (le_trans hsf $ by simp [h]) in have ∀a, principal t ⊓ nhds a ≠ ⊥ → a ∈ t, by intro a; rw [inf_comm]; rw [is_closed_iff_nhds] at ht; exact ht a, have a ∈ t, from this a $ neq_bot_of_le_neq_bot ha $ inf_le_inf hsf (le_refl _), ⟨a, this, ha⟩ lemma compact_adherence_nhdset {s t : set α} {f : filter α} (hs : compact s) (hf₂ : f ≤ principal s) (ht₁ : is_open t) (ht₂ : ∀a∈s, nhds a ⊓ f ≠ ⊥ → a ∈ t) : t ∈ f.sets := classical.by_cases mem_sets_of_neq_bot $ assume : f ⊓ principal (- t) ≠ ⊥, let ⟨a, ha, (hfa : f ⊓ principal (-t) ⊓ nhds a ≠ ⊥)⟩ := hs _ this $ inf_le_left_of_le hf₂ in have a ∈ t, from ht₂ a ha $ neq_bot_of_le_neq_bot hfa $ le_inf inf_le_right $ inf_le_left_of_le inf_le_left, have nhds a ⊓ principal (-t) ≠ ⊥, from neq_bot_of_le_neq_bot hfa $ le_inf inf_le_right $ inf_le_left_of_le inf_le_right, have ∀s∈(nhds a ⊓ principal (-t)).sets, s ≠ ∅, from forall_sets_neq_empty_iff_neq_bot.mpr this, have false, from this _ ⟨t, mem_nhds_sets ht₁ ‹a ∈ t›, -t, subset.refl _, subset.refl _⟩ (by simp), by contradiction lemma compact_iff_ultrafilter_le_nhds {s : set α} : compact s ↔ (∀f, ultrafilter f → f ≤ principal s → ∃a∈s, f ≤ nhds a) := ⟨assume hs : compact s, assume f hf hfs, let ⟨a, ha, h⟩ := hs _ hf.left hfs in ⟨a, ha, le_of_ultrafilter hf h⟩, assume hs : (∀f, ultrafilter f → f ≤ principal s → ∃a∈s, f ≤ nhds a), assume f hf hfs, let ⟨a, ha, (h : ultrafilter_of f ≤ nhds a)⟩ := hs (ultrafilter_of f) (ultrafilter_ultrafilter_of hf) (le_trans ultrafilter_of_le hfs) in have ultrafilter_of f ⊓ nhds a ≠ ⊥, by simp [inf_of_le_left, h]; exact (ultrafilter_ultrafilter_of hf).left, ⟨a, ha, neq_bot_of_le_neq_bot this (inf_le_inf ultrafilter_of_le (le_refl _))⟩⟩ lemma compact_elim_finite_subcover {s : set α} {c : set (set α)} (hs : compact s) (hc₁ : ∀t∈c, is_open t) (hc₂ : s ⊆ ⋃₀ c) : ∃c'⊆c, finite c' ∧ s ⊆ ⋃₀ c' := classical.by_contradiction $ assume h, have h : ∀{c'}, c' ⊆ c → finite c' → ¬ s ⊆ ⋃₀ c', from assume c' h₁ h₂ h₃, h ⟨c', h₁, h₂, h₃⟩, let f : filter α := (⨅c':{c' : set (set α) // c' ⊆ c ∧ finite c'}, principal (s - ⋃₀ c')), ⟨a, ha⟩ := @exists_mem_of_ne_empty α s (assume h', h (empty_subset _) finite_empty $ h'.symm ▸ empty_subset _) in have f ≠ ⊥, from infi_neq_bot_of_directed ⟨a⟩ (assume ⟨c₁, hc₁, hc'₁⟩ ⟨c₂, hc₂, hc'₂⟩, ⟨⟨c₁ ∪ c₂, union_subset hc₁ hc₂, finite_union hc'₁ hc'₂⟩, principal_mono.mpr $ diff_subset_diff_right $ sUnion_mono $ subset_union_left _ _, principal_mono.mpr $ diff_subset_diff_right $ sUnion_mono $ subset_union_right _ _⟩) (assume ⟨c', hc'₁, hc'₂⟩, show principal (s \ _) ≠ ⊥, by simp [diff_eq_empty]; exact h hc'₁ hc'₂), have f ≤ principal s, from infi_le_of_le ⟨∅, empty_subset _, finite_empty⟩ $ show principal (s \ ⋃₀∅) ≤ principal s, by simp; exact subset.refl s, let ⟨a, ha, (h : f ⊓ nhds a ≠ ⊥)⟩ := hs f ‹f ≠ ⊥› this, ⟨t, ht₁, (ht₂ : a ∈ t)⟩ := hc₂ ha in have f ≤ principal (-t), from infi_le_of_le ⟨{t}, by simp [ht₁], finite_insert _ finite_empty⟩ $ principal_mono.mpr $ show s - ⋃₀{t} ⊆ - t, begin simp; exact assume x ⟨_, hnt⟩, hnt end, have is_closed (- t), from is_open_compl_iff.mp $ by simp; exact hc₁ t ht₁, have a ∈ - t, from is_closed_iff_nhds.mp this _ $ neq_bot_of_le_neq_bot h $ le_inf inf_le_right (inf_le_left_of_le ‹f ≤ principal (- t)›), this ‹a ∈ t› lemma compact_elim_finite_subcover_image {s : set α} {b : set β} {c : β → set α} (hs : compact s) (hc₁ : ∀i∈b, is_open (c i)) (hc₂ : s ⊆ ⋃i∈b, c i) : ∃b'⊆b, finite b' ∧ s ⊆ ⋃i∈b', c i := if h : b = ∅ then ⟨∅, by simp, by simp, h ▸ hc₂⟩ else let ⟨i, hi⟩ := exists_mem_of_ne_empty h in have hc'₁ : ∀i∈c '' b, is_open i, from assume i ⟨j, hj, h⟩, h ▸ hc₁ _ hj, have hc'₂ : s ⊆ ⋃₀ (c '' b), by simpa, let ⟨d, hd₁, hd₂, hd₃⟩ := compact_elim_finite_subcover hs hc'₁ hc'₂ in have ∀x : d, ∃i, i ∈ b ∧ c i = x, from assume ⟨x, hx⟩, hd₁ hx, let ⟨f', hf⟩ := axiom_of_choice this, f := λx:set α, (if h : x ∈ d then f' ⟨x, h⟩ else i : β) in have ∀(x : α) (i : set α), i ∈ d → x ∈ i → (∃ (i : β), i ∈ f '' d ∧ x ∈ c i), from assume x i hid hxi, ⟨f i, mem_image_of_mem f hid, by simpa [f, hid, (hf ⟨_, hid⟩).2] using hxi⟩, ⟨f '' d, assume i ⟨j, hj, h⟩, h ▸ by simpa [f, hj] using (hf ⟨_, hj⟩).1, finite_image f hd₂, subset.trans hd₃ $ by simpa [subset_def]⟩ lemma compact_of_finite_subcover {s : set α} (h : ∀c, (∀t∈c, is_open t) → s ⊆ ⋃₀ c → ∃c'⊆c, finite c' ∧ s ⊆ ⋃₀ c') : compact s := assume f hfn hfs, classical.by_contradiction $ assume : ¬ (∃x∈s, f ⊓ nhds x ≠ ⊥), have hf : ∀x∈s, nhds x ⊓ f = ⊥, by simpa [not_and, inf_comm], have ¬ ∃x∈s, ∀t∈f.sets, x ∈ closure t, from assume ⟨x, hxs, hx⟩, have ∅ ∈ (nhds x ⊓ f).sets, by rw [empty_in_sets_eq_bot, hf x hxs], let ⟨t₁, ht₁, t₂, ht₂, ht⟩ := by rw [mem_inf_sets] at this; exact this in have ∅ ∈ (nhds x ⊓ principal t₂).sets, from (nhds x ⊓ principal t₂).sets_of_superset (inter_mem_inf_sets ht₁ (subset.refl t₂)) ht, have nhds x ⊓ principal t₂ = ⊥, by rwa [empty_in_sets_eq_bot] at this, by simp [closure_eq_nhds] at hx; exact hx t₂ ht₂ this, have ∀x∈s, ∃t∈f.sets, x ∉ closure t, by simpa [_root_.not_forall], let c := (λt, - closure t) '' f.sets, ⟨c', hcc', hcf, hsc'⟩ := h c (assume t ⟨s, hs, h⟩, h ▸ is_closed_closure) (by simpa [subset_def]) in let ⟨b, hb⟩ := axiom_of_choice $ show ∀s:c', ∃t, t ∈ f.sets ∧ - closure t = s, from assume ⟨x, hx⟩, hcc' hx in have (⋂s∈c', if h : s ∈ c' then b ⟨s, h⟩ else univ) ∈ f.sets, from Inter_mem_sets hcf $ assume t ht, by rw [dif_pos ht]; exact (hb ⟨t, ht⟩).left, have s ∩ (⋂s∈c', if h : s ∈ c' then b ⟨s, h⟩ else univ) ∈ f.sets, from inter_mem_sets (by simp at hfs; assumption) this, have ∅ ∈ f.sets, from mem_sets_of_superset this $ assume x ⟨hxs, hxi⟩, let ⟨t, htc', hxt⟩ := (show ∃t ∈ c', x ∈ t, by simpa using hsc' hxs) in have -closure (b ⟨t, htc'⟩) = t, from (hb _).right, have x ∈ - t, from this ▸ (calc x ∈ b ⟨t, htc'⟩ : by simp at hxi; have h := hxi t htc'; rwa [dif_pos htc'] at h ... ⊆ closure (b ⟨t, htc'⟩) : subset_closure ... ⊆ - - closure (b ⟨t, htc'⟩) : by simp; exact subset.refl _), show false, from this hxt, hfn $ by rwa [empty_in_sets_eq_bot] at this lemma compact_iff_finite_subcover {s : set α} : compact s ↔ (∀c, (∀t∈c, is_open t) → s ⊆ ⋃₀ c → ∃c'⊆c, finite c' ∧ s ⊆ ⋃₀ c') := ⟨assume hc c, compact_elim_finite_subcover hc, compact_of_finite_subcover⟩ lemma compact_empty : compact (∅ : set α) := assume f hnf hsf, not.elim hnf $ by simpa [empty_in_sets_eq_bot] using hsf lemma compact_singleton {a : α} : compact ({a} : set α) := compact_of_finite_subcover $ assume c hc₁ hc₂, let ⟨i, hic, hai⟩ := (show ∃i ∈ c, a ∈ i, by simpa using hc₂) in ⟨{i}, by simp [hic], finite_singleton _, by simp [hai]⟩ lemma compact_bUnion_of_compact {s : set β} {f : β → set α} (hs : finite s) : (∀i ∈ s, compact (f i)) → compact (⋃i ∈ s, f i) := assume hf, compact_of_finite_subcover $ assume c c_open c_cover, have ∀i : subtype s, ∃c' ⊆ c, finite c' ∧ f i ⊆ ⋃₀ c', from assume ⟨i, hi⟩, compact_elim_finite_subcover (hf i hi) c_open (calc f i ⊆ ⋃i ∈ s, f i : subset_bUnion_of_mem hi ... ⊆ ⋃₀ c : c_cover), let ⟨finite_subcovers, h⟩ := axiom_of_choice this in let c' := ⋃i, finite_subcovers i in have c' ⊆ c, from Union_subset (λi, (h i).fst), have finite c', from @finite_Union _ _ hs.fintype _ (λi, (h i).snd.1), have (⋃i ∈ s, f i) ⊆ ⋃₀ c', from bUnion_subset $ λi hi, calc f i ⊆ ⋃₀ finite_subcovers ⟨i,hi⟩ : (h ⟨i,hi⟩).snd.2 ... ⊆ ⋃₀ c' : sUnion_mono (subset_Union _ _), ⟨c', ‹c' ⊆ c›, ‹finite c'›, this⟩ lemma compact_of_finite {s : set α} (hs : finite s) : compact s := let s' : set α := ⋃i ∈ s, {i} in have e : s' = s, from ext $ λi, by simp, have compact s', from compact_bUnion_of_compact hs (λ_ _, compact_singleton), e ▸ this end compact /- separation axioms -/ section separation /-- A T₁ space, also known as a Fréchet space, is a topological space where for every pair `x ≠ y`, there is an open set containing `x` and not `y`. Equivalently, every singleton set is closed. -/ class t1_space (α : Type u) [topological_space α] := (t1 : ∀x, is_closed ({x} : set α)) lemma is_closed_singleton [t1_space α] {x : α} : is_closed ({x} : set α) := t1_space.t1 x lemma compl_singleton_mem_nhds [t1_space α] {x y : α} (h : y ≠ x) : - {x} ∈ (nhds y).sets := mem_nhds_sets is_closed_singleton $ by simp; exact h @[simp] lemma closure_singleton [topological_space α] [t1_space α] {a : α} : closure ({a} : set α) = {a} := closure_eq_of_is_closed is_closed_singleton /-- A T₂ space, also known as a Hausdorff space, is one in which for every `x ≠ y` there exists disjoint open sets around `x` and `y`. This is the most widely used of the separation axioms. -/ class t2_space (α : Type u) [topological_space α] := (t2 : ∀x y, x ≠ y → ∃u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ u ∩ v = ∅) lemma t2_separation [t2_space α] {x y : α} (h : x ≠ y) : ∃u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ u ∩ v = ∅ := t2_space.t2 x y h instance t2_space.t1_space [topological_space α] [t2_space α] : t1_space α := ⟨assume x, have ∀y, y ≠ x ↔ ∃ (i : set α), (x ∉ i ∧ is_open i) ∧ y ∈ i, from assume y, ⟨assume h', let ⟨u, v, hu, hv, hy, hx, h⟩ := t2_separation h' in have x ∉ u, from assume : x ∈ u, have x ∈ u ∩ v, from ⟨this, hx⟩, by rwa [h] at this, ⟨u, ⟨this, hu⟩, hy⟩, assume ⟨s, ⟨hx, hs⟩, hy⟩ h, hx $ h ▸ hy⟩, have (-{x} : set α) = (⋃s∈{s : set α | x ∉ s ∧ is_open s}, s), by apply set.ext; simpa, show is_open (- {x}), by rw [this]; exact (is_open_Union $ assume s, is_open_Union $ assume ⟨_, hs⟩, hs)⟩ lemma eq_of_nhds_neq_bot [ht : t2_space α] {x y : α} (h : nhds x ⊓ nhds y ≠ ⊥) : x = y := classical.by_contradiction $ assume : x ≠ y, let ⟨u, v, hu, hv, hx, hy, huv⟩ := t2_space.t2 x y this in have u ∩ v ∈ (nhds x ⊓ nhds y).sets, from inter_mem_inf_sets (mem_nhds_sets hu hx) (mem_nhds_sets hv hy), h $ empty_in_sets_eq_bot.mp $ huv ▸ this @[simp] lemma nhds_eq_nhds_iff {a b : α} [t2_space α] : nhds a = nhds b ↔ a = b := ⟨assume h, eq_of_nhds_neq_bot $ by simp [h], assume h, h ▸ rfl⟩ @[simp] lemma nhds_le_nhds_iff {a b : α} [t2_space α] : nhds a ≤ nhds b ↔ a = b := ⟨assume h, eq_of_nhds_neq_bot $ by simp [inf_of_le_left h], assume h, h ▸ le_refl _⟩ lemma tendsto_nhds_unique [t2_space α] {f : β → α} {l : filter β} {a b : α} (hl : l ≠ ⊥) (ha : tendsto f l (nhds a)) (hb : tendsto f l (nhds b)) : a = b := eq_of_nhds_neq_bot $ neq_bot_of_le_neq_bot (map_ne_bot hl) $ le_inf ha hb end separation section regularity /-- A T₃ space, also known as a regular space (although this condition sometimes omits T₂), is one in which for every closed `C` and `x ∉ C`, there exist disjoint open sets containing `x` and `C` respectively. -/ class regular_space (α : Type u) [topological_space α] extends t2_space α := (regular : ∀{s:set α} {a}, is_closed s → a ∉ s → ∃t, is_open t ∧ s ⊆ t ∧ nhds a ⊓ principal t = ⊥) lemma nhds_is_closed [regular_space α] {a : α} {s : set α} (h : s ∈ (nhds a).sets) : ∃t∈(nhds a).sets, t ⊆ s ∧ is_closed t := let ⟨s', h₁, h₂, h₃⟩ := mem_nhds_sets_iff.mp h in have ∃t, is_open t ∧ -s' ⊆ t ∧ nhds a ⊓ principal t = ⊥, from regular_space.regular (is_closed_compl_iff.mpr h₂) (not_not_intro h₃), let ⟨t, ht₁, ht₂, ht₃⟩ := this in ⟨-t, mem_sets_of_neq_bot $ by simp; exact ht₃, subset.trans (compl_subset_comm.1 ht₂) h₁, is_closed_compl_iff.mpr ht₁⟩ end regularity /- generating sets -/ end topological_space namespace topological_space variables {α : Type u} /-- The least topology containing a collection of basic sets. -/ inductive generate_open (g : set (set α)) : set α → Prop | basic : ∀s∈g, generate_open s | univ : generate_open univ | inter : ∀s t, generate_open s → generate_open t → generate_open (s ∩ t) | sUnion : ∀k, (∀s∈k, generate_open s) → generate_open (⋃₀ k) /-- The smallest topological space containing the collection `g` of basic sets -/ def generate_from (g : set (set α)) : topological_space α := { is_open := generate_open g, is_open_univ := generate_open.univ g, is_open_inter := generate_open.inter, is_open_sUnion := generate_open.sUnion } lemma nhds_generate_from {g : set (set α)} {a : α} : @nhds α (generate_from g) a = (⨅s∈{s | a ∈ s ∧ s ∈ g}, principal s) := le_antisymm (infi_le_infi $ assume s, infi_le_infi_const $ assume ⟨as, sg⟩, ⟨as, generate_open.basic _ sg⟩) (le_infi $ assume s, le_infi $ assume ⟨as, hs⟩, have ∀s, generate_open g s → a ∈ s → (⨅s∈{s | a ∈ s ∧ s ∈ g}, principal s) ≤ principal s, begin intros s hs, induction hs, case generate_open.basic : s hs { exact assume as, infi_le_of_le s $ infi_le _ ⟨as, hs⟩ }, case generate_open.univ { rw [principal_univ], exact assume _, le_top }, case generate_open.inter : s t hs' ht' hs ht { exact assume ⟨has, hat⟩, calc _ ≤ principal s ⊓ principal t : le_inf (hs has) (ht hat) ... = _ : by simp }, case generate_open.sUnion : k hk' hk { exact λ ⟨t, htk, hat⟩, calc _ ≤ principal t : hk t htk hat ... ≤ _ : begin simp; exact subset_sUnion_of_mem htk end } end, this s hs as) lemma tendsto_nhds_generate_from {β : Type*} {m : α → β} {f : filter α} {g : set (set β)} {b : β} (h : ∀s∈g, b ∈ s → m ⁻¹' s ∈ f.sets) : tendsto m f (@nhds β (generate_from g) b) := by rw [nhds_generate_from]; exact (tendsto_infi.2 $ assume s, tendsto_infi.2 $ assume ⟨hbs, hsg⟩, tendsto_principal.2 $ h s hsg hbs) end topological_space section lattice variables {α : Type u} {β : Type v} instance : partial_order (topological_space α) := { le := λt s, t.is_open ≤ s.is_open, le_antisymm := assume t s h₁ h₂, topological_space_eq $ le_antisymm h₁ h₂, le_refl := assume t, le_refl t.is_open, le_trans := assume a b c h₁ h₂, @le_trans _ _ a.is_open b.is_open c.is_open h₁ h₂ } lemma generate_from_le_iff_subset_is_open {g : set (set α)} {t : topological_space α} : topological_space.generate_from g ≤ t ↔ g ⊆ {s | t.is_open s} := iff.intro (assume ht s hs, ht _ $ topological_space.generate_open.basic s hs) (assume hg s hs, hs.rec_on (assume v hv, hg hv) t.is_open_univ (assume u v _ _, t.is_open_inter u v) (assume k _, t.is_open_sUnion k)) protected def mk_of_closure (s : set (set α)) (hs : {u | (topological_space.generate_from s).is_open u} = s) : topological_space α := { is_open := λu, u ∈ s, is_open_univ := hs ▸ topological_space.generate_open.univ _, is_open_inter := hs ▸ topological_space.generate_open.inter, is_open_sUnion := hs ▸ topological_space.generate_open.sUnion } lemma mk_of_closure_sets {s : set (set α)} {hs : {u | (topological_space.generate_from s).is_open u} = s} : mk_of_closure s hs = topological_space.generate_from s := topological_space_eq hs.symm def gi_generate_from (α : Type*) : galois_insertion topological_space.generate_from (λt:topological_space α, {s | t.is_open s}) := { gc := assume g t, generate_from_le_iff_subset_is_open, le_l_u := assume ts s hs, topological_space.generate_open.basic s hs, choice := λg hg, mk_of_closure g (subset.antisymm hg $ generate_from_le_iff_subset_is_open.1 $ le_refl _), choice_eq := assume s hs, mk_of_closure_sets } instance {α : Type u} : complete_lattice (topological_space α) := (gi_generate_from α).lift_complete_lattice @[simp] lemma is_open_top {s : set α} : @is_open α ⊤ s := trivial lemma le_of_nhds_le_nhds {t₁ t₂ : topological_space α} (h : ∀x, @nhds α t₂ x ≤ @nhds α t₁ x) : t₁ ≤ t₂ := assume s, show @is_open α t₁ s → @is_open α t₂ s, begin simp [is_open_iff_nhds]; exact assume hs a ha, h _ $ hs _ ha end lemma eq_of_nhds_eq_nhds {t₁ t₂ : topological_space α} (h : ∀x, @nhds α t₂ x = @nhds α t₁ x) : t₁ = t₂ := le_antisymm (le_of_nhds_le_nhds $ assume x, le_of_eq $ h x) (le_of_nhds_le_nhds $ assume x, le_of_eq $ (h x).symm) end lattice section galois_connection variables {α : Type*} {β : Type*} {γ : Type*} /-- Given `f : α → β` and a topology on `β`, the induced topology on `α` is the collection of sets that are preimages of some open set in `β`. This is the coarsest topology that makes `f` continuous. -/ def topological_space.induced {α : Type u} {β : Type v} (f : α → β) (t : topological_space β) : topological_space α := { is_open := λs, ∃s', t.is_open s' ∧ s = f ⁻¹' s', is_open_univ := ⟨univ, by simp; exact t.is_open_univ⟩, is_open_inter := assume s₁ s₂ ⟨s'₁, hs₁, eq₁⟩ ⟨s'₂, hs₂, eq₂⟩, ⟨s'₁ ∩ s'₂, by simp [eq₁, eq₂]; exact t.is_open_inter _ _ hs₁ hs₂⟩, is_open_sUnion := assume s h, begin simp [classical.skolem] at h, cases h with f hf, apply exists.intro (⋃(x : set α) (h : x ∈ s), f x h), simp [sUnion_eq_bUnion, (λx h, (hf x h).right.symm)], exact (@is_open_Union β _ t _ $ assume i, show is_open (⋃h, f i h), from @is_open_Union β _ t _ $ assume h, (hf i h).left) end } lemma is_closed_induced_iff [t : topological_space β] {s : set α} {f : α → β} : @is_closed α (t.induced f) s ↔ (∃t, is_closed t ∧ s = f ⁻¹' t) := ⟨assume ⟨t, ht, heq⟩, ⟨-t, by simp; assumption, by simp [preimage_compl, heq.symm]⟩, assume ⟨t, ht, heq⟩, ⟨-t, ht, by simp [preimage_compl, heq.symm]⟩⟩ /-- Given `f : α → β` and a topology on `α`, the coinduced topology on `β` is defined such that `s:set β` is open if the preimage of `s` is open. This is the finest topology that makes `f` continuous. -/ def topological_space.coinduced {α : Type u} {β : Type v} (f : α → β) (t : topological_space α) : topological_space β := { is_open := λs, t.is_open (f ⁻¹' s), is_open_univ := by simp; exact t.is_open_univ, is_open_inter := assume s₁ s₂ h₁ h₂, by simp; exact t.is_open_inter _ _ h₁ h₂, is_open_sUnion := assume s h, by rw [preimage_sUnion]; exact (@is_open_Union _ _ t _ $ assume i, show is_open (⋃ (H : i ∈ s), f ⁻¹' i), from @is_open_Union _ _ t _ $ assume hi, h i hi) } variables {t t₁ t₂ : topological_space α} {t' : topological_space β} {f : α → β} {g : β → α} lemma induced_le_iff_le_coinduced {f : α → β } {tα : topological_space α} {tβ : topological_space β} : tβ.induced f ≤ tα ↔ tβ ≤ tα.coinduced f := iff.intro (assume h s hs, show tα.is_open (f ⁻¹' s), from h _ ⟨s, hs, rfl⟩) (assume h s ⟨t, ht, hst⟩, hst.symm ▸ h _ ht) lemma gc_induced_coinduced (f : α → β) : galois_connection (topological_space.induced f) (topological_space.coinduced f) := assume f g, induced_le_iff_le_coinduced lemma induced_mono (h : t₁ ≤ t₂) : t₁.induced g ≤ t₂.induced g := (gc_induced_coinduced g).monotone_l h lemma coinduced_mono (h : t₁ ≤ t₂) : t₁.coinduced f ≤ t₂.coinduced f := (gc_induced_coinduced f).monotone_u h @[simp] lemma induced_bot : (⊥ : topological_space α).induced g = ⊥ := (gc_induced_coinduced g).l_bot @[simp] lemma induced_sup : (t₁ ⊔ t₂).induced g = t₁.induced g ⊔ t₂.induced g := (gc_induced_coinduced g).l_sup @[simp] lemma induced_supr {ι : Sort w} {t : ι → topological_space α} : (⨆i, t i).induced g = (⨆i, (t i).induced g) := (gc_induced_coinduced g).l_supr @[simp] lemma coinduced_top : (⊤ : topological_space α).coinduced f = ⊤ := (gc_induced_coinduced f).u_top @[simp] lemma coinduced_inf : (t₁ ⊓ t₂).coinduced f = t₁.coinduced f ⊓ t₂.coinduced f := (gc_induced_coinduced f).u_inf @[simp] lemma coinduced_infi {ι : Sort w} {t : ι → topological_space α} : (⨅i, t i).coinduced f = (⨅i, (t i).coinduced f) := (gc_induced_coinduced f).u_infi lemma induced_id [t : topological_space α] : t.induced id = t := topological_space_eq $ funext $ assume s, propext $ ⟨assume ⟨s', hs, h⟩, h.symm ▸ hs, assume hs, ⟨s, hs, rfl⟩⟩ lemma induced_compose [tβ : topological_space β] [tγ : topological_space γ] {f : α → β} {g : β → γ} : (tγ.induced g).induced f = tγ.induced (g ∘ f) := topological_space_eq $ funext $ assume s, propext $ ⟨assume ⟨s', ⟨s, hs, h₂⟩, h₁⟩, h₁.symm ▸ h₂.symm ▸ ⟨s, hs, rfl⟩, assume ⟨s, hs, h⟩, ⟨preimage g s, ⟨s, hs, rfl⟩, h ▸ rfl⟩⟩ lemma coinduced_id [t : topological_space α] : t.coinduced id = t := topological_space_eq rfl lemma coinduced_compose [tα : topological_space α] {f : α → β} {g : β → γ} : (tα.coinduced f).coinduced g = tα.coinduced (g ∘ f) := topological_space_eq rfl end galois_connection /- constructions using the complete lattice structure -/ section constructions open topological_space variables {α : Type u} {β : Type v} instance inhabited_topological_space {α : Type u} : inhabited (topological_space α) := ⟨⊤⟩ lemma t2_space_top : @t2_space α ⊤ := { t2 := assume x y hxy, ⟨{x}, {y}, trivial, trivial, mem_insert _ _, mem_insert _ _, eq_empty_iff_forall_not_mem.2 $ by intros z hz; simp at hz; cc⟩ } instance : topological_space empty := ⊤ instance : topological_space unit := ⊤ instance : topological_space bool := ⊤ instance : topological_space ℕ := ⊤ instance : topological_space ℤ := ⊤ instance sierpinski_space : topological_space Prop := generate_from {{true}} instance {p : α → Prop} [t : topological_space α] : topological_space (subtype p) := induced subtype.val t instance {r : α → α → Prop} [t : topological_space α] : topological_space (quot r) := coinduced (quot.mk r) t instance {s : setoid α} [t : topological_space α] : topological_space (quotient s) := coinduced quotient.mk t instance [t₁ : topological_space α] [t₂ : topological_space β] : topological_space (α × β) := induced prod.fst t₁ ⊔ induced prod.snd t₂ instance [t₁ : topological_space α] [t₂ : topological_space β] : topological_space (α ⊕ β) := coinduced sum.inl t₁ ⊓ coinduced sum.inr t₂ instance {β : α → Type v} [t₂ : Πa, topological_space (β a)] : topological_space (sigma β) := ⨅a, coinduced (sigma.mk a) (t₂ a) instance Pi.topological_space {β : α → Type v} [t₂ : Πa, topological_space (β a)] : topological_space (Πa, β a) := ⨆a, induced (λf, f a) (t₂ a) lemma quotient_dense_of_dense [setoid α] [topological_space α] {s : set α} (H : ∀ x, x ∈ closure s) : closure (quotient.mk '' s) = univ := begin ext x, suffices : x ∈ closure (quotient.mk '' s), by simp [this], rw mem_closure_iff, intros U U_op x_in_U, let V := quotient.mk ⁻¹' U, cases quotient.exists_rep x with y y_x, have y_in_V : y ∈ V, by simp [mem_preimage_eq, y_x, x_in_U], have V_op : is_open V := U_op, have : V ∩ s ≠ ∅ := mem_closure_iff.1 (H y) V V_op y_in_V, rcases exists_mem_of_ne_empty this with ⟨w, w_in_V, w_in_range⟩, exact ne_empty_of_mem ⟨by tauto, mem_image_of_mem quotient.mk w_in_range⟩ end lemma generate_from_le {t : topological_space α} { g : set (set α) } (h : ∀s∈g, is_open s) : generate_from g ≤ t := generate_from_le_iff_subset_is_open.2 h protected def topological_space.nhds_adjoint (a : α) (f : filter α) : topological_space α := { is_open := λs, a ∈ s → s ∈ f.sets, is_open_univ := assume s, univ_mem_sets, is_open_inter := assume s t hs ht ⟨has, hat⟩, inter_mem_sets (hs has) (ht hat), is_open_sUnion := assume k hk ⟨u, hu, hau⟩, mem_sets_of_superset (hk u hu hau) (subset_sUnion_of_mem hu) } lemma gc_nhds (a : α) : @galois_connection _ (order_dual (filter α)) _ _ (λt, @nhds α t a) (topological_space.nhds_adjoint a) := assume t (f : filter α), show f ≤ @nhds α t a ↔ _, from iff.intro (assume h s hs has, h $ @mem_nhds_sets α t a s hs has) (assume h, le_infi $ assume u, le_infi $ assume ⟨hau, hu⟩, le_principal_iff.2 $ h _ hu hau) lemma nhds_mono {t₁ t₂ : topological_space α} {a : α} (h : t₁ ≤ t₂) : @nhds α t₂ a ≤ @nhds α t₁ a := (gc_nhds a).monotone_l h lemma nhds_supr {ι : Sort*} {t : ι → topological_space α} {a : α} : @nhds α (supr t) a = (⨅i, @nhds α (t i) a) := (gc_nhds a).l_supr lemma nhds_Sup {s : set (topological_space α)} {a : α} : @nhds α (Sup s) a = (⨅t∈s, @nhds α t a) := (gc_nhds a).l_Sup lemma nhds_sup {t₁ t₂ : topological_space α} {a : α} : @nhds α (t₁ ⊔ t₂) a = @nhds α t₁ a ⊓ @nhds α t₂ a := (gc_nhds a).l_sup lemma nhds_bot {a : α} : @nhds α ⊥ a = ⊤ := (gc_nhds a).l_bot private lemma separated_by_f [tα : topological_space α] [tβ : topological_space β] [t2_space β] (f : α → β) (hf : induced f tβ ≤ tα) {x y : α} (h : f x ≠ f y) : ∃u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ u ∩ v = ∅ := let ⟨u, v, uo, vo, xu, yv, uv⟩ := t2_separation h in ⟨f ⁻¹' u, f ⁻¹' v, hf _ ⟨u, uo, rfl⟩, hf _ ⟨v, vo, rfl⟩, xu, yv, by rw [←preimage_inter, uv, preimage_empty]⟩ instance {p : α → Prop} [t : topological_space α] [t2_space α] : t2_space (subtype p) := ⟨assume x y h, separated_by_f subtype.val (le_refl _) (mt subtype.eq h)⟩ instance [t₁ : topological_space α] [t2_space α] [t₂ : topological_space β] [t2_space β] : t2_space (α × β) := ⟨assume ⟨x₁,x₂⟩ ⟨y₁,y₂⟩ h, or.elim (not_and_distrib.mp (mt prod.ext_iff.mpr h)) (λ h₁, separated_by_f prod.fst le_sup_left h₁) (λ h₂, separated_by_f prod.snd le_sup_right h₂)⟩ instance Pi.t2_space {β : α → Type v} [t₂ : Πa, topological_space (β a)] [Πa, t2_space (β a)] : t2_space (Πa, β a) := ⟨assume x y h, let ⟨i, hi⟩ := not_forall.mp (mt funext h) in separated_by_f (λz, z i) (le_supr _ i) hi⟩ end constructions namespace topological_space /- countability axioms For our applications we are interested that there exists a countable basis, but we do not need the concrete basis itself. This allows us to declare these type classes as `Prop` to use them as mixins. -/ variables {α : Type u} [t : topological_space α] include t /-- A topological basis is one that satisfies the necessary conditions so that it suffices to take unions of the basis sets to get a topology (without taking finite intersections as well). -/ def is_topological_basis (s : set (set α)) : Prop := (∀t₁∈s, ∀t₂∈s, ∀ x ∈ t₁ ∩ t₂, ∃ t₃∈s, x ∈ t₃ ∧ t₃ ⊆ t₁ ∩ t₂) ∧ (⋃₀ s) = univ ∧ t = generate_from s lemma is_topological_basis_of_subbasis {s : set (set α)} (hs : t = generate_from s) : is_topological_basis ((λf, ⋂₀ f) '' {f:set (set α) | finite f ∧ f ⊆ s ∧ ⋂₀ f ≠ ∅}) := let b' := (λf, ⋂₀ f) '' {f:set (set α) | finite f ∧ f ⊆ s ∧ ⋂₀ f ≠ ∅} in ⟨assume s₁ ⟨t₁, ⟨hft₁, ht₁b, ht₁⟩, eq₁⟩ s₂ ⟨t₂, ⟨hft₂, ht₂b, ht₂⟩, eq₂⟩, have ie : ⋂₀(t₁ ∪ t₂) = ⋂₀ t₁ ∩ ⋂₀ t₂, from Inf_union, eq₁ ▸ eq₂ ▸ assume x h, ⟨_, ⟨t₁ ∪ t₂, ⟨finite_union hft₁ hft₂, union_subset ht₁b ht₂b, by simpa [ie] using ne_empty_of_mem h⟩, ie⟩, h, subset.refl _⟩, eq_univ_iff_forall.2 $ assume a, ⟨univ, ⟨∅, by simp; exact (@empty_ne_univ _ ⟨a⟩).symm⟩, mem_univ _⟩, have generate_from s = generate_from b', from le_antisymm (generate_from_le $ assume s hs, by_cases (assume : s = ∅, by rw [this]; apply @is_open_empty _ _) (assume : s ≠ ∅, generate_open.basic _ ⟨{s}, by simp [this, hs]⟩)) (generate_from_le $ assume u ⟨t, ⟨hft, htb, ne⟩, eq⟩, eq ▸ @is_open_sInter _ (generate_from s) _ hft (assume s hs, generate_open.basic _ $ htb hs)), this ▸ hs⟩ lemma is_topological_basis_of_open_of_nhds {s : set (set α)} (h_open : ∀ u ∈ s, _root_.is_open u) (h_nhds : ∀(a:α) (u : set α), a ∈ u → _root_.is_open u → ∃v ∈ s, a ∈ v ∧ v ⊆ u) : is_topological_basis s := ⟨assume t₁ ht₁ t₂ ht₂ x ⟨xt₁, xt₂⟩, h_nhds x (t₁ ∩ t₂) ⟨xt₁, xt₂⟩ (is_open_inter _ _ _ (h_open _ ht₁) (h_open _ ht₂)), eq_univ_iff_forall.2 $ assume a, let ⟨u, h₁, h₂, _⟩ := h_nhds a univ trivial (is_open_univ _) in ⟨u, h₁, h₂⟩, le_antisymm (assume u hu, (@is_open_iff_nhds α (generate_from _) _).mpr $ assume a hau, let ⟨v, hvs, hav, hvu⟩ := h_nhds a u hau hu in by rw nhds_generate_from; exact infi_le_of_le v (infi_le_of_le ⟨hav, hvs⟩ $ by simp [hvu])) (generate_from_le h_open)⟩ lemma mem_nhds_of_is_topological_basis {a : α} {s : set α} {b : set (set α)} (hb : is_topological_basis b) : s ∈ (nhds a).sets ↔ ∃t∈b, a ∈ t ∧ t ⊆ s := begin rw [hb.2.2, nhds_generate_from, infi_sets_eq'], { simp [and_comm, and.left_comm] }, { exact assume s ⟨hs₁, hs₂⟩ t ⟨ht₁, ht₂⟩, have a ∈ s ∩ t, from ⟨hs₁, ht₁⟩, let ⟨u, hu₁, hu₂, hu₃⟩ := hb.1 _ hs₂ _ ht₂ _ this in ⟨u, ⟨hu₂, hu₁⟩, by simpa using hu₃⟩ }, { suffices : a ∈ (⋃₀ b), { simpa [and_comm] }, { rw [hb.2.1], trivial } } end lemma is_open_of_is_topological_basis {s : set α} {b : set (set α)} (hb : is_topological_basis b) (hs : s ∈ b) : _root_.is_open s := is_open_iff_mem_nhds.2 $ λ a as, (mem_nhds_of_is_topological_basis hb).2 ⟨s, hs, as, subset.refl _⟩ lemma mem_basis_subset_of_mem_open {b : set (set α)} (hb : is_topological_basis b) {a:α} {u : set α} (au : a ∈ u) (ou : _root_.is_open u) : ∃v ∈ b, a ∈ v ∧ v ⊆ u := (mem_nhds_of_is_topological_basis hb).1 $ mem_nhds_sets ou au lemma sUnion_basis_of_is_open {B : set (set α)} (hB : is_topological_basis B) {u : set α} (ou : _root_.is_open u) : ∃ S ⊆ B, u = ⋃₀ S := ⟨{s ∈ B | s ⊆ u}, λ s h, h.1, set.ext $ λ a, ⟨λ ha, let ⟨b, hb, ab, bu⟩ := mem_basis_subset_of_mem_open hB ha ou in ⟨b, ⟨hb, bu⟩, ab⟩, λ ⟨b, ⟨hb, bu⟩, ab⟩, bu ab⟩⟩ lemma Union_basis_of_is_open {B : set (set α)} (hB : is_topological_basis B) {u : set α} (ou : _root_.is_open u) : ∃ (β : Type u) (f : β → set α), u = (⋃ i, f i) ∧ ∀ i, f i ∈ B := let ⟨S, sb, su⟩ := sUnion_basis_of_is_open hB ou in ⟨S, subtype.val, su.trans set.sUnion_eq_Union, λ ⟨b, h⟩, sb h⟩ variables (α) /-- A separable space is one with a countable dense subset. -/ class separable_space : Prop := (exists_countable_closure_eq_univ : ∃s:set α, countable s ∧ closure s = univ) /-- A first-countable space is one in which every point has a countable neighborhood basis. -/ class first_countable_topology : Prop := (nhds_generated_countable : ∀a:α, ∃s:set (set α), countable s ∧ nhds a = (⨅t∈s, principal t)) /-- A second-countable space is one with a countable basis. -/ class second_countable_topology : Prop := (is_open_generated_countable : ∃b:set (set α), countable b ∧ t = topological_space.generate_from b) instance second_countable_topology.to_first_countable_topology [second_countable_topology α] : first_countable_topology α := let ⟨b, hb, eq⟩ := second_countable_topology.is_open_generated_countable α in ⟨assume a, ⟨{s | a ∈ s ∧ s ∈ b}, countable_subset (assume x ⟨_, hx⟩, hx) hb, by rw [eq, nhds_generate_from]⟩⟩ lemma is_open_generated_countable_inter [second_countable_topology α] : ∃b:set (set α), countable b ∧ ∅ ∉ b ∧ is_topological_basis b := let ⟨b, hb₁, hb₂⟩ := second_countable_topology.is_open_generated_countable α in let b' := (λs, ⋂₀ s) '' {s:set (set α) | finite s ∧ s ⊆ b ∧ ⋂₀ s ≠ ∅} in ⟨b', countable_image _ $ countable_subset (by simp {contextual:=tt}) (countable_set_of_finite_subset hb₁), assume ⟨s, ⟨_, _, hn⟩, hp⟩, hn hp, is_topological_basis_of_subbasis hb₂⟩ instance second_countable_topology.to_separable_space [second_countable_topology α] : separable_space α := let ⟨b, hb₁, hb₂, hb₃, hb₄, eq⟩ := is_open_generated_countable_inter α in have nhds_eq : ∀a, nhds a = (⨅ s : {s : set α // a ∈ s ∧ s ∈ b}, principal s.val), by intro a; rw [eq, nhds_generate_from]; simp [infi_subtype], have ∀s∈b, ∃a, a ∈ s, from assume s hs, exists_mem_of_ne_empty $ assume eq, hb₂ $ eq ▸ hs, have ∃f:∀s∈b, α, ∀s h, f s h ∈ s, by simp only [skolem] at this; exact this, let ⟨f, hf⟩ := this in ⟨⟨(⋃s∈b, ⋃h:s∈b, {f s h}), countable_bUnion hb₁ (by simp [countable_Union_Prop]), set.ext $ assume a, have a ∈ (⋃₀ b), by rw [hb₄]; exact trivial, let ⟨t, ht₁, ht₂⟩ := this in have w : {s : set α // a ∈ s ∧ s ∈ b}, from ⟨t, ht₂, ht₁⟩, suffices (⨅ (x : {s // a ∈ s ∧ s ∈ b}), principal (x.val ∩ ⋃s (h₁ h₂ : s ∈ b), {f s h₂})) ≠ ⊥, by simpa [closure_eq_nhds, nhds_eq, infi_inf w], infi_neq_bot_of_directed ⟨a⟩ (assume ⟨s₁, has₁, hs₁⟩ ⟨s₂, has₂, hs₂⟩, have a ∈ s₁ ∩ s₂, from ⟨has₁, has₂⟩, let ⟨s₃, hs₃, has₃, hs⟩ := hb₃ _ hs₁ _ hs₂ _ this in ⟨⟨s₃, has₃, hs₃⟩, begin simp only [le_principal_iff, mem_principal_sets], simp at hs, split; apply inter_subset_inter_left; simp [hs] end⟩) (assume ⟨s, has, hs⟩, have s ∩ (⋃ (s : set α) (H h : s ∈ b), {f s h}) ≠ ∅, from ne_empty_of_mem ⟨hf _ hs, mem_bUnion hs $ mem_Union.mpr ⟨hs, by simp⟩⟩, by simp [this]) ⟩⟩ lemma is_open_sUnion_countable [second_countable_topology α] (S : set (set α)) (H : ∀ s ∈ S, _root_.is_open s) : ∃ T : set (set α), countable T ∧ T ⊆ S ∧ ⋃₀ T = ⋃₀ S := let ⟨B, cB, _, bB⟩ := is_open_generated_countable_inter α in begin let B' := {b ∈ B | ∃ s ∈ S, b ⊆ s}, rcases axiom_of_choice (λ b:B', b.2.2) with ⟨f, hf⟩, change B' → set α at f, haveI : encodable B' := (countable_subset (sep_subset _ _) cB).to_encodable, have : range f ⊆ S := range_subset_iff.2 (λ x, (hf x).fst), exact ⟨_, countable_range f, this, subset.antisymm (sUnion_subset_sUnion this) $ sUnion_subset $ λ s hs x xs, let ⟨b, hb, xb, bs⟩ := mem_basis_subset_of_mem_open bB xs (H _ hs) in ⟨_, ⟨⟨_, hb, _, hs, bs⟩, rfl⟩, (hf _).snd xb⟩⟩ end end topological_space section limit variables {α : Type u} [inhabited α] [topological_space α] open classical /-- If `f` is a filter, then `lim f` is a limit of the filter, if it exists. -/ noncomputable def lim (f : filter α) : α := epsilon $ λa, f ≤ nhds a lemma lim_spec {f : filter α} (h : ∃a, f ≤ nhds a) : f ≤ nhds (lim f) := epsilon_spec h variables [t2_space α] {f : filter α} lemma lim_eq {a : α} (hf : f ≠ ⊥) (h : f ≤ nhds a) : lim f = a := eq_of_nhds_neq_bot $ neq_bot_of_le_neq_bot hf $ le_inf (lim_spec ⟨_, h⟩) h @[simp] lemma lim_nhds_eq {a : α} : lim (nhds a) = a := lim_eq nhds_neq_bot (le_refl _) @[simp] lemma lim_nhds_eq_of_closure {a : α} {s : set α} (h : a ∈ closure s) : lim (nhds a ⊓ principal s) = a := lim_eq begin rw [closure_eq_nhds] at h, exact h end inf_le_left end limit
942f293cc6b73c1b242c51ecb40aa43ca0c5fd09
30b012bb72d640ec30c8fdd4c45fdfa67beb012c
/data/padics/hensel.lean
17f58da8ba3b78d6c467d790b07a5e5fc70b000f
[ "Apache-2.0" ]
permissive
kckennylau/mathlib
21fb810b701b10d6606d9002a4004f7672262e83
47b3477e20ffb5a06588dd3abb01fe0fe3205646
refs/heads/master
1,634,976,409,281
1,542,042,832,000
1,542,319,733,000
109,560,458
0
0
Apache-2.0
1,542,369,208,000
1,509,867,494,000
Lean
UTF-8
Lean
false
false
20,814
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis A proof of Hensel's lemma on ℤ_p, roughly following Keith Conrad's writeup: http://www.math.uconn.edu/~kconrad/blurbs/gradnumthy/hensel.pdf -/ import data.padics.padic_integers data.polynomial data.nat.choose data.real.cau_seq_filter import analysis.limits analysis.polynomial import tactic.ring noncomputable theory local attribute [instance] classical.prop_decidable lemma padic_polynomial_dist {p : ℕ} [p.prime] (F : polynomial ℤ_[p]) (x y : ℤ_[p]) : ∥F.eval x - F.eval y∥ ≤ ∥x - y∥ := let ⟨z, hz⟩ := F.eval_sub_factor x y in calc ∥F.eval x - F.eval y∥ = ∥z∥ * ∥x - y∥ : by simp [hz] ... ≤ 1 * ∥x - y∥ : mul_le_mul_of_nonneg_right (padic_norm_z.le_one _) (norm_nonneg _) ... = ∥x - y∥ : by simp open filter private lemma comp_tendsto_lim {p : ℕ} [p.prime] {F : polynomial ℤ_[p]} (ncs : cau_seq ℤ_[p] norm) : tendsto (λ i, F.eval (ncs i)) at_top (nhds (F.eval ncs.lim)) := @tendsto.comp _ _ _ ncs (λ k, F.eval k) _ _ _ (tendsto_limit ncs) (continuous_iff_tendsto.1 F.continuous_eval _) section parameters {p : ℕ} [nat.prime p] {ncs : cau_seq ℤ_[p] norm} {F : polynomial ℤ_[p]} {a : ℤ_[p]} (ncs_der_val : ∀ n, ∥F.derivative.eval (ncs n)∥ = ∥F.derivative.eval a∥) include ncs_der_val private lemma ncs_tendsto_const : tendsto (λ i, ∥F.derivative.eval (ncs i)∥) at_top (nhds ∥F.derivative.eval a∥) := by convert tendsto_const_nhds; ext; rw ncs_der_val private lemma ncs_tendsto_lim : tendsto (λ i, ∥F.derivative.eval (ncs i)∥) at_top (nhds (∥F.derivative.eval ncs.lim∥)) := tendsto.comp (comp_tendsto_lim _) (continuous_iff_tendsto.1 continuous_norm _) private lemma norm_deriv_eq : ∥F.derivative.eval ncs.lim∥ = ∥F.derivative.eval a∥ := tendsto_nhds_unique at_top_ne_bot ncs_tendsto_lim ncs_tendsto_const end section parameters {p : ℕ} [nat.prime p] {ncs : cau_seq ℤ_[p] norm} {F : polynomial ℤ_[p]} (hnorm : tendsto (λ i, ∥F.eval (ncs i)∥) at_top (nhds 0)) include hnorm private lemma tendsto_zero_of_norm_tendsto_zero : tendsto (λ i, F.eval (ncs i)) at_top (nhds 0) := tendsto_iff_norm_tendsto_zero.2 (by simpa using hnorm) lemma limit_zero_of_norm_tendsto_zero : F.eval ncs.lim = 0 := tendsto_nhds_unique at_top_ne_bot (comp_tendsto_lim _) tendsto_zero_of_norm_tendsto_zero end section hensel open nat parameters {p : ℕ} [nat.prime p] {F : polynomial ℤ_[p]} {a : ℤ_[p]} (hnorm : ∥F.eval a∥ < ∥F.derivative.eval a∥^2) (hnsol : F.eval a ≠ 0) include hnorm private def T : ℝ := ∥(F.eval a).val / ((F.derivative.eval a).val)^2∥ private lemma deriv_sq_norm_pos : 0 < ∥F.derivative.eval a∥ ^ 2 := lt_of_le_of_lt (norm_nonneg _) hnorm private lemma deriv_sq_norm_ne_zero : ∥F.derivative.eval a∥^2 ≠ 0 := ne_of_gt deriv_sq_norm_pos private lemma deriv_norm_ne_zero : ∥F.derivative.eval a∥ ≠ 0 := λ h, deriv_sq_norm_ne_zero (by simp [*, _root_.pow_two]) private lemma deriv_norm_pos : 0 < ∥F.derivative.eval a∥ := lt_of_le_of_ne (norm_nonneg _) (ne.symm deriv_norm_ne_zero) private lemma deriv_ne_zero : F.derivative.eval a ≠ 0 := mt (norm_eq_zero _).2 deriv_norm_ne_zero private lemma T_def : T = ∥F.eval a∥ / ∥F.derivative.eval a∥^2 := calc T = ∥(F.eval a).val∥ / ∥((F.derivative.eval a).val)^2∥ : norm_div _ _ ... = ∥F.eval a∥ / ∥(F.derivative.eval a)^2∥ : by simp [norm, padic_norm_z] ... = ∥F.eval a∥ / ∥(F.derivative.eval a)∥^2 : by simp [pow, monoid.pow] private lemma T_lt_one : T < 1 := let h := (div_lt_one_iff_lt deriv_sq_norm_pos).2 hnorm in by rw T_def; apply h private lemma T_pow {n : ℕ} (hn : n > 0) : T ^ n < 1 := have T ^ n ≤ T ^ 1, from pow_le_pow_of_le_one (norm_nonneg _) (le_of_lt T_lt_one) (succ_le_of_lt hn), lt_of_le_of_lt (by simpa) T_lt_one private lemma T_pow' (n : ℕ) : T ^ (2 ^ n) < 1 := (T_pow (nat.pow_pos (by norm_num) _)) private lemma T_pow_nonneg (n : ℕ) : T ^ n ≥ 0 := pow_nonneg (norm_nonneg _) _ private def ih (n : ℕ) (z : ℤ_[p]) : Prop := ∥F.derivative.eval z∥ = ∥F.derivative.eval a∥ ∧ ∥F.eval z∥ ≤ ∥F.derivative.eval a∥^2 * T ^ (2^n) private lemma ih_0 : ih 0 a := ⟨ rfl, by simp [T_def, mul_div_cancel' _ (ne_of_gt (deriv_sq_norm_pos hnorm))] ⟩ private lemma calc_norm_le_one {n : ℕ} {z : ℤ_[p]} (hz : ih n z) : ∥(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)∥ ≤ 1 := calc ∥(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)∥ = ∥(↑(F.eval z) : ℚ_[p])∥ / ∥(↑(F.derivative.eval z) : ℚ_[p])∥ : norm_div _ _ ... = ∥F.eval z∥ / ∥F.derivative.eval a∥ : by simp [hz.1] ... ≤ ∥F.derivative.eval a∥^2 * T^(2^n) / ∥F.derivative.eval a∥ : (div_le_div_right deriv_norm_pos).2 hz.2 ... = ∥F.derivative.eval a∥ * T^(2^n) : div_sq_cancel (ne_of_gt deriv_norm_pos) _ ... ≤ 1 : mul_le_one (padic_norm_z.le_one _) (T_pow_nonneg _) (le_of_lt (T_pow' _)) private lemma calc_deriv_dist {z z' z1 : ℤ_[p]} (hz' : z' = z - z1) (hz1 : ∥z1∥ = ∥F.eval z∥ / ∥F.derivative.eval a∥) {n} (hz : ih n z) : ∥F.derivative.eval z' - F.derivative.eval z∥ < ∥F.derivative.eval a∥ := calc ∥F.derivative.eval z' - F.derivative.eval z∥ ≤ ∥z' - z∥ : padic_polynomial_dist _ _ _ ... = ∥z1∥ : by simp [hz'] ... = ∥F.eval z∥ / ∥F.derivative.eval a∥ : hz1 ... ≤ ∥F.derivative.eval a∥^2 * T^(2^n) / ∥F.derivative.eval a∥ : (div_le_div_right deriv_norm_pos).2 hz.2 ... = ∥F.derivative.eval a∥ * T^(2^n) : div_sq_cancel deriv_norm_ne_zero _ ... < ∥F.derivative.eval a∥ : (mul_lt_iff_lt_one_right deriv_norm_pos).2 (T_pow (pow_pos (by norm_num) _)) private def calc_eval_z' {z z' z1 : ℤ_[p]} (hz' : z' = z - z1) {n} (hz : ih n z) (h1 : ∥(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)∥ ≤ 1) (hzeq : z1 = ⟨_, h1⟩) : {q : ℤ_[p] // F.eval z' = q * z1^2} := have hdzne' : (↑(F.derivative.eval z) : ℚ_[p]) ≠ 0, from have hdzne : F.derivative.eval z ≠ 0, from mt (norm_eq_zero _).2 (by rw hz.1; apply deriv_norm_ne_zero; assumption), λ h, hdzne $ subtype.ext.2 h, let ⟨q, hq⟩ := F.binom_expansion z (-z1) in have ∥(↑(F.derivative.eval z) * (↑(F.eval z) / ↑(F.derivative.eval z)) : ℚ_[p])∥ ≤ 1, by {rw padic_norm_e.mul, apply mul_le_one, apply padic_norm_z.le_one, apply norm_nonneg, apply h1}, have F.derivative.eval z * (-z1) = -F.eval z, from calc F.derivative.eval z * (-z1) = (F.derivative.eval z) * -⟨↑(F.eval z) / ↑(F.derivative.eval z), h1⟩ : by rw [hzeq] ... = -((F.derivative.eval z) * ⟨↑(F.eval z) / ↑(F.derivative.eval z), h1⟩) : by simp ... = -(⟨↑(F.derivative.eval z) * (↑(F.eval z) / ↑(F.derivative.eval z)), this⟩) : subtype.ext.2 $ by simp ... = -(F.eval z) : by simp [mul_div_cancel' _ hdzne'], have heq : F.eval z' = q * z1^2, by simpa [this, hz'] using hq, ⟨q, heq⟩ private def calc_eval_z'_norm {z z' z1 : ℤ_[p]} {n} (hz : ih n z) {q} (heq : F.eval z' = q * z1^2) (h1 : ∥(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)∥ ≤ 1) (hzeq : z1 = ⟨_, h1⟩) : ∥F.eval z'∥ ≤ ∥F.derivative.eval a∥^2 * T^(2^(n+1)) := calc ∥F.eval z'∥ = ∥q∥ * ∥z1∥^2 : by simp [heq] ... ≤ 1 * ∥z1∥^2 : mul_le_mul_of_nonneg_right (padic_norm_z.le_one _) (pow_nonneg (norm_nonneg _) _) ... = ∥F.eval z∥^2 / ∥F.derivative.eval a∥^2 : by simp [hzeq, hz.1, div_pow _ (deriv_norm_ne_zero hnorm)] ... ≤ (∥F.derivative.eval a∥^2 * T^(2^n))^2 / ∥F.derivative.eval a∥^2 : (div_le_div_right deriv_sq_norm_pos).2 (pow_le_pow_of_le_left (norm_nonneg _) hz.2 _) ... = (∥F.derivative.eval a∥^2)^2 * (T^(2^n))^2 / ∥F.derivative.eval a∥^2 : by simp only [_root_.mul_pow] ... = ∥F.derivative.eval a∥^2 * (T^(2^n))^2 : div_sq_cancel deriv_sq_norm_ne_zero _ ... = ∥F.derivative.eval a∥^2 * T^(2^(n + 1)) : by rw [←pow_mul]; refl set_option eqn_compiler.zeta true -- we need (ih k) in order to construct the value for k+1, otherwise it might not be an integer. private def ih_n {n : ℕ} {z : ℤ_[p]} (hz : ih n z) : {z' : ℤ_[p] // ih (n+1) z'} := have h1 : ∥(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)∥ ≤ 1, from calc_norm_le_one hz, let z1 : ℤ_[p] := ⟨_, h1⟩, z' : ℤ_[p] := z - z1 in ⟨ z', have hdist : ∥F.derivative.eval z' - F.derivative.eval z∥ < ∥F.derivative.eval a∥, from calc_deriv_dist rfl (by simp [z1, hz.1]) hz, have hfeq : ∥F.derivative.eval z'∥ = ∥F.derivative.eval a∥, begin rw [sub_eq_add_neg, ← hz.1, ←norm_neg (F.derivative.eval z)] at hdist, have := padic_norm_z.eq_of_norm_add_lt_right hdist, rwa [norm_neg, hz.1] at this end, let ⟨q, heq⟩ := calc_eval_z' rfl hz h1 rfl in have hnle : ∥F.eval z'∥ ≤ ∥F.derivative.eval a∥^2 * T^(2^(n+1)), from calc_eval_z'_norm hz heq h1 rfl, ⟨hfeq, hnle⟩⟩ set_option eqn_compiler.zeta false -- why doesn't "noncomputable theory" stick here? private noncomputable def newton_seq_aux : Π n : ℕ, {z : ℤ_[p] // ih n z} | 0 := ⟨a, ih_0⟩ | (k+1) := ih_n (newton_seq_aux k).2 private def newton_seq (n : ℕ) : ℤ_[p] := (newton_seq_aux n).1 private lemma newton_seq_deriv_norm (n : ℕ) : ∥F.derivative.eval (newton_seq n)∥ = ∥F.derivative.eval a∥ := (newton_seq_aux n).2.1 private lemma newton_seq_norm_le (n : ℕ) : ∥F.eval (newton_seq n)∥ ≤ ∥F.derivative.eval a∥^2 * T ^ (2^n) := (newton_seq_aux n).2.2 private lemma newton_seq_norm_eq (n : ℕ) : ∥newton_seq (n+1) - newton_seq n∥ = ∥F.eval (newton_seq n)∥ / ∥F.derivative.eval (newton_seq n)∥ := by induction n; simp [newton_seq, newton_seq_aux, ih_n] private lemma newton_seq_succ_dist (n : ℕ) : ∥newton_seq (n+1) - newton_seq n∥ ≤ ∥F.derivative.eval a∥ * T^(2^n) := calc ∥newton_seq (n+1) - newton_seq n∥ = ∥F.eval (newton_seq n)∥ / ∥F.derivative.eval (newton_seq n)∥ : newton_seq_norm_eq _ ... = ∥F.eval (newton_seq n)∥ / ∥F.derivative.eval a∥ : by rw newton_seq_deriv_norm ... ≤ ∥F.derivative.eval a∥^2 * T ^ (2^n) / ∥F.derivative.eval a∥ : (div_le_div_right deriv_norm_pos).2 (newton_seq_norm_le _) ... = ∥F.derivative.eval a∥ * T^(2^n) : div_sq_cancel (ne_of_gt deriv_norm_pos) _ include hnsol private lemma T_pos : T > 0 := begin rw T_def, apply div_pos_of_pos_of_pos, { apply (norm_pos_iff _).2, apply hnsol }, { exact deriv_sq_norm_pos hnorm } end private lemma newton_seq_succ_dist_weak (n : ℕ) : ∥newton_seq (n+2) - newton_seq (n+1)∥ < ∥F.eval a∥ / ∥F.derivative.eval a∥ := have 2 ≤ 2^(n+1), from have _, from pow_le_pow (by norm_num : 1 ≤ 2) (nat.le_add_left _ _ : 1 ≤ n + 1), by simpa using this, calc ∥newton_seq (n+2) - newton_seq (n+1)∥ ≤ ∥F.derivative.eval a∥ * T^(2^(n+1)) : newton_seq_succ_dist _ ... ≤ ∥F.derivative.eval a∥ * T^2 : mul_le_mul_of_nonneg_left (pow_le_pow_of_le_one (norm_nonneg _) (le_of_lt T_lt_one) this) (norm_nonneg _) ... < ∥F.derivative.eval a∥ * T^1 : mul_lt_mul_of_pos_left (pow_lt_pow_of_lt_one T_pos T_lt_one (by norm_num)) deriv_norm_pos ... = ∥F.eval a∥ / ∥F.derivative.eval a∥ : begin rw [T, _root_.pow_two, _root_.pow_one, norm_div, ←mul_div_assoc, padic_norm_e.mul], apply mul_div_mul_left', apply deriv_norm_ne_zero; assumption end private lemma newton_seq_dist_aux (n : ℕ) : ∀ k : ℕ, ∥newton_seq (n + k) - newton_seq n∥ ≤ ∥F.derivative.eval a∥ * T^(2^n) | 0 := begin simp, apply mul_nonneg, {apply norm_nonneg}, {apply T_pow_nonneg} end | (k+1) := have 2^n ≤ 2^(n+k), by {rw [←nat.pow_eq_pow, ←nat.pow_eq_pow], apply pow_le_pow, norm_num, apply nat.le_add_right}, calc ∥newton_seq (n + (k + 1)) - newton_seq n∥ = ∥newton_seq ((n + k) + 1) - newton_seq n∥ : by simp ... = ∥(newton_seq ((n + k) + 1) - newton_seq (n+k)) + (newton_seq (n+k) - newton_seq n)∥ : by rw ←sub_add_sub_cancel ... ≤ max (∥newton_seq ((n + k) + 1) - newton_seq (n+k)∥) (∥newton_seq (n+k) - newton_seq n∥) : padic_norm_z.nonarchimedean _ _ ... ≤ max (∥F.derivative.eval a∥ * T^(2^((n + k)))) (∥F.derivative.eval a∥ * T^(2^n)) : max_le_max (newton_seq_succ_dist _) (newton_seq_dist_aux _) ... = ∥F.derivative.eval a∥ * T^(2^n) : max_eq_right $ mul_le_mul_of_nonneg_left (pow_le_pow_of_le_one (norm_nonneg _) (le_of_lt T_lt_one) this) (norm_nonneg _) private lemma newton_seq_dist {n k : ℕ} (hnk : n ≤ k) : ∥newton_seq k - newton_seq n∥ ≤ ∥F.derivative.eval a∥ * T^(2^n) := have hex : ∃ m, k = n + m, from exists_eq_add_of_le hnk, -- ⟨k - n, by rw [←nat.add_sub_assoc hnk, add_comm, nat.add_sub_assoc (le_refl n), nat.sub_self, nat.add_zero]⟩, let ⟨_, hex'⟩ := hex in by rw hex'; apply newton_seq_dist_aux; assumption private lemma newton_seq_dist_to_a : ∀ n : ℕ, 0 < n → ∥newton_seq n - a∥ = ∥F.eval a∥ / ∥F.derivative.eval a∥ | 1 h := by simp [newton_seq, newton_seq_aux, ih_n]; apply norm_div | (k+2) h := have hlt : ∥newton_seq (k+2) - newton_seq (k+1)∥ < ∥newton_seq (k+1) - a∥, by rw newton_seq_dist_to_a (k+1) (succ_pos _); apply newton_seq_succ_dist_weak; assumption, have hne' : ∥newton_seq (k + 2) - newton_seq (k+1)∥ ≠ ∥newton_seq (k+1) - a∥, from ne_of_lt hlt, calc ∥newton_seq (k + 2) - a∥ = ∥(newton_seq (k + 2) - newton_seq (k+1)) + (newton_seq (k+1) - a)∥ : by rw ←sub_add_sub_cancel ... = max (∥newton_seq (k + 2) - newton_seq (k+1)∥) (∥newton_seq (k+1) - a∥) : padic_norm_z.add_eq_max_of_ne hne' ... = ∥newton_seq (k+1) - a∥ : max_eq_right_of_lt hlt ... = ∥polynomial.eval a F∥ / ∥polynomial.eval a (polynomial.derivative F)∥ : newton_seq_dist_to_a (k+1) (succ_pos _) private lemma bound' : tendsto (λ n : ℕ, ∥F.derivative.eval a∥ * T^(2^n)) at_top (nhds 0) := begin rw ←mul_zero (∥F.derivative.eval a∥), exact tendsto_mul (tendsto_const_nhds) (tendsto.comp (tendsto_pow_at_top_at_top_of_gt_1_nat (by norm_num)) (tendsto_pow_at_top_nhds_0_of_lt_1 (norm_nonneg _) (T_lt_one hnorm))) end private lemma bound : ∀ {ε}, ε > 0 → ∃ N : ℕ, ∀ {n}, n ≥ N → ∥F.derivative.eval a∥ * T^(2^n) < ε := have mtn : ∀ n : ℕ, ∥polynomial.eval a (polynomial.derivative F)∥ * T ^ (2 ^ n) ≥ 0, from λ n, mul_nonneg (norm_nonneg _) (T_pow_nonneg _), begin have := bound' hnorm hnsol, simp [tendsto, nhds] at this, intros ε hε, cases this (ball 0 ε) (mem_ball_self hε) (is_open_ball) with N hN, existsi N, intros n hn, simpa [normed_field.norm_mul, real.norm_eq_abs, abs_of_nonneg (mtn n)] using hN _ hn end private lemma bound'_sq : tendsto (λ n : ℕ, ∥F.derivative.eval a∥^2 * T^(2^n)) at_top (nhds 0) := begin rw [←mul_zero (∥F.derivative.eval a∥), _root_.pow_two], simp only [mul_assoc], apply tendsto_mul, { apply tendsto_const_nhds }, { apply bound', assumption } end private theorem newton_seq_is_cauchy : is_cau_seq norm newton_seq := begin intros ε hε, cases bound hnorm hnsol hε with N hN, existsi N, intros j hj, apply lt_of_le_of_lt, { apply newton_seq_dist _ _ hj, assumption }, { apply hN, apply le_refl } end private def newton_cau_seq : cau_seq ℤ_[p] norm := ⟨_, newton_seq_is_cauchy⟩ private def soln : ℤ_[p] := newton_cau_seq.lim private lemma soln_spec {ε : ℝ} (hε : ε > 0) : ∃ (N : ℕ), ∀ {i : ℕ}, i ≥ N → ∥soln - newton_cau_seq i∥ < ε := setoid.symm (cau_seq.equiv_lim newton_cau_seq) _ hε private lemma soln_deriv_norm : ∥F.derivative.eval soln∥ = ∥F.derivative.eval a∥ := norm_deriv_eq newton_seq_deriv_norm private lemma newton_seq_norm_tendsto_zero : tendsto (λ i, ∥F.eval (newton_cau_seq i)∥) at_top (nhds 0) := squeeze_zero (λ _, norm_nonneg _) newton_seq_norm_le bound'_sq private lemma newton_seq_dist_tendsto : tendsto (λ n, ∥newton_cau_seq n - a∥) at_top (nhds (∥F.eval a∥ / ∥F.derivative.eval a∥)) := tendsto_cong (tendsto_const_nhds) $ suffices ∃ k, ∀ n ≥ k, ∥F.eval a∥ / ∥F.derivative.eval a∥ = ∥newton_cau_seq n - a∥, by simpa, ⟨1, λ _ hx, (newton_seq_dist_to_a _ hx).symm⟩ private lemma newton_seq_dist_tendsto' : tendsto (λ n, ∥newton_cau_seq n - a∥) at_top (nhds ∥soln - a∥) := tendsto.comp (tendsto_sub (tendsto_limit _) tendsto_const_nhds) (continuous_iff_tendsto.1 continuous_norm _) private lemma soln_dist_to_a : ∥soln - a∥ = ∥F.eval a∥ / ∥F.derivative.eval a∥ := tendsto_nhds_unique at_top_ne_bot newton_seq_dist_tendsto' newton_seq_dist_tendsto private lemma soln_dist_to_a_lt_deriv : ∥soln - a∥ < ∥F.derivative.eval a∥ := begin rw soln_dist_to_a, apply div_lt_of_mul_lt_of_pos, { apply deriv_norm_pos; assumption }, { rwa _root_.pow_two at hnorm } end private lemma eval_soln : F.eval soln = 0 := limit_zero_of_norm_tendsto_zero newton_seq_norm_tendsto_zero private lemma soln_unique (z : ℤ_[p]) (hev : F.eval z = 0) (hnlt : ∥z - a∥ < ∥F.derivative.eval a∥) : z = soln := have soln_dist : ∥z - soln∥ < ∥F.derivative.eval a∥, from calc ∥z - soln∥ = ∥(z - a) + (a - soln)∥ : by rw sub_add_sub_cancel ... ≤ max (∥z - a∥) (∥a - soln∥) : padic_norm_z.nonarchimedean _ _ ... < ∥F.derivative.eval a∥ : max_lt hnlt (by rw norm_sub_rev; apply soln_dist_to_a_lt_deriv), let h := z - soln, ⟨q, hq⟩ := F.binom_expansion soln h in have (F.derivative.eval soln + q * h) * h = 0, from eq.symm (calc 0 = F.eval (soln + h) : by simp [hev, h] ... = F.derivative.eval soln * h + q * h^2 : by rw [hq, eval_soln, zero_add] ... = (F.derivative.eval soln + q * h) * h : by rw [_root_.pow_two, right_distrib, mul_assoc]), have h = 0, from by_contradiction $ λ hne, have F.derivative.eval soln + q * h = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_right hne, have F.derivative.eval soln = (-q) * h, by simpa using eq_neg_of_add_eq_zero this, lt_irrefl ∥F.derivative.eval soln∥ (calc ∥F.derivative.eval soln∥ = ∥(-q) * h∥ : by rw this ... ≤ 1 * ∥h∥ : by rw [padic_norm_z.mul]; exact mul_le_mul_of_nonneg_right (padic_norm_z.le_one _) (norm_nonneg _) ... = ∥z - soln∥ : by simp [h] ... < ∥F.derivative.eval soln∥ : by rw soln_deriv_norm; apply soln_dist), eq_of_sub_eq_zero (by rw ←this; refl) end hensel variables {p : ℕ} [nat.prime p] {F : polynomial ℤ_[p]} {a : ℤ_[p]} private lemma a_soln_is_unique (ha : F.eval a = 0) (z' : ℤ_[p]) (hz' : F.eval z' = 0) (hnormz' : ∥z' - a∥ < ∥F.derivative.eval a∥) : z' = a := let h := z' - a, ⟨q, hq⟩ := F.binom_expansion a h in have (F.derivative.eval a + q * h) * h = 0, from eq.symm (calc 0 = F.eval (a + h) : show 0 = F.eval (a + (z' - a)), by rw add_comm; simp [hz'] ... = F.derivative.eval a * h + q * h^2 : by rw [hq, ha, zero_add] ... = (F.derivative.eval a + q * h) * h : by rw [_root_.pow_two, right_distrib, mul_assoc]), have h = 0, from by_contradiction $ λ hne, have F.derivative.eval a + q * h = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_right hne, have F.derivative.eval a = (-q) * h, by simpa using eq_neg_of_add_eq_zero this, lt_irrefl ∥F.derivative.eval a∥ (calc ∥F.derivative.eval a∥ = ∥q∥*∥h∥ : by simp [this] ... ≤ 1*∥h∥ : mul_le_mul_of_nonneg_right (padic_norm_z.le_one _) (norm_nonneg _) ... < ∥F.derivative.eval a∥ : by simpa [h]), eq_of_sub_eq_zero (by rw ←this; refl) variable (hnorm : ∥F.eval a∥ < ∥F.derivative.eval a∥^2) include hnorm private lemma a_is_soln (ha : F.eval a = 0) : F.eval a = 0 ∧ ∥a - a∥ < ∥F.derivative.eval a∥ ∧ ∥F.derivative.eval a∥ = ∥F.derivative.eval a∥ ∧ ∀ z', F.eval z' = 0 → ∥z' - a∥ < ∥F.derivative.eval a∥ → z' = a := ⟨ha, by simp; apply deriv_norm_pos; apply hnorm, rfl, a_soln_is_unique ha⟩ lemma hensels_lemma : ∃ z : ℤ_[p], F.eval z = 0 ∧ ∥z - a∥ < ∥F.derivative.eval a∥ ∧ ∥F.derivative.eval z∥ = ∥F.derivative.eval a∥ ∧ ∀ z', F.eval z' = 0 → ∥z' - a∥ < ∥F.derivative.eval a∥ → z' = z := if ha : F.eval a = 0 then ⟨a, a_is_soln hnorm ha⟩ else by refine ⟨soln _ _, eval_soln _ _, soln_dist_to_a_lt_deriv _ _, soln_deriv_norm _ _, soln_unique _ _⟩; assumption
e2e2496823355511ae880e16b1882a237100ed2a
4727251e0cd73359b15b664c3170e5d754078599
/src/linear_algebra/eigenspace.lean
b6ffa6d59f00724274d9d6fbea5b5d50b52d727d
[ "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
29,066
lean
/- Copyright (c) 2020 Alexander Bentkamp. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp -/ import linear_algebra.charpoly.basic import linear_algebra.finsupp import linear_algebra.matrix.to_lin import algebra.algebra.spectrum import order.hom.basic /-! # Eigenvectors and eigenvalues This file defines eigenspaces, eigenvalues, and eigenvalues, as well as their generalized counterparts. We follow Axler's approach [axler2015] because it allows us to derive many properties without choosing a basis and without using matrices. An eigenspace of a linear map `f` for a scalar `μ` is the kernel of the map `(f - μ • id)`. The nonzero elements of an eigenspace are eigenvectors `x`. They have the property `f x = μ • x`. If there are eigenvectors for a scalar `μ`, the scalar `μ` is called an eigenvalue. There is no consensus in the literature whether `0` is an eigenvector. Our definition of `has_eigenvector` permits only nonzero vectors. For an eigenvector `x` that may also be `0`, we write `x ∈ f.eigenspace μ`. A generalized eigenspace of a linear map `f` for a natural number `k` and a scalar `μ` is the kernel of the map `(f - μ • id) ^ k`. The nonzero elements of a generalized eigenspace are generalized eigenvectors `x`. If there are generalized eigenvectors for a natural number `k` and a scalar `μ`, the scalar `μ` is called a generalized eigenvalue. ## References * [Sheldon Axler, *Linear Algebra Done Right*][axler2015] * https://en.wikipedia.org/wiki/Eigenvalues_and_eigenvectors ## Tags eigenspace, eigenvector, eigenvalue, eigen -/ universes u v w namespace module namespace End open module principal_ideal_ring polynomial finite_dimensional open_locale polynomial variables {K R : Type v} {V M : Type w} [comm_ring R] [add_comm_group M] [module R M] [field K] [add_comm_group V] [module K V] /-- The submodule `eigenspace f μ` for a linear map `f` and a scalar `μ` consists of all vectors `x` such that `f x = μ • x`. (Def 5.36 of [axler2015])-/ def eigenspace (f : End R M) (μ : R) : submodule R M := (f - algebra_map R (End R M) μ).ker /-- A nonzero element of an eigenspace is an eigenvector. (Def 5.7 of [axler2015]) -/ def has_eigenvector (f : End R M) (μ : R) (x : M) : Prop := x ∈ eigenspace f μ ∧ x ≠ 0 /-- A scalar `μ` is an eigenvalue for a linear map `f` if there are nonzero vectors `x` such that `f x = μ • x`. (Def 5.5 of [axler2015]) -/ def has_eigenvalue (f : End R M) (a : R) : Prop := eigenspace f a ≠ ⊥ /-- The eigenvalues of the endomorphism `f`, as a subtype of `R`. -/ def eigenvalues (f : End R M) : Type* := {μ : R // f.has_eigenvalue μ} instance (f : End R M) : has_coe f.eigenvalues R := coe_subtype lemma has_eigenvalue_of_has_eigenvector {f : End R M} {μ : R} {x : M} (h : has_eigenvector f μ x) : has_eigenvalue f μ := begin rw [has_eigenvalue, submodule.ne_bot_iff], use x, exact h, end lemma mem_eigenspace_iff {f : End R M} {μ : R} {x : M} : x ∈ eigenspace f μ ↔ f x = μ • x := by rw [eigenspace, linear_map.mem_ker, linear_map.sub_apply, algebra_map_End_apply, sub_eq_zero] lemma has_eigenvector.apply_eq_smul {f : End R M} {μ : R} {x : M} (hx : f.has_eigenvector μ x) : f x = μ • x := mem_eigenspace_iff.mp hx.1 lemma has_eigenvalue.exists_has_eigenvector {f : End R M} {μ : R} (hμ : f.has_eigenvalue μ) : ∃ v, f.has_eigenvector μ v := submodule.exists_mem_ne_zero_of_ne_bot hμ lemma mem_spectrum_of_has_eigenvalue {f : End R M} {μ : R} (hμ : has_eigenvalue f μ) : μ ∈ spectrum R f := begin refine spectrum.mem_iff.mpr (λ h_unit, _), set f' := linear_map.general_linear_group.to_linear_equiv h_unit.unit, rcases hμ.exists_has_eigenvector with ⟨v, hv⟩, refine hv.2 ((linear_map.ker_eq_bot'.mp f'.ker) v (_ : μ • v - f v = 0)), rw [hv.apply_eq_smul, sub_self] end lemma has_eigenvalue_iff_mem_spectrum [finite_dimensional K V] {f : End K V} {μ : K} : f.has_eigenvalue μ ↔ μ ∈ spectrum K f := iff.intro mem_spectrum_of_has_eigenvalue (λ h, by rwa [spectrum.mem_iff, is_unit.sub_iff, linear_map.is_unit_iff_ker_eq_bot] at h) lemma eigenspace_div (f : End K V) (a b : K) (hb : b ≠ 0) : eigenspace f (a / b) = (b • f - algebra_map K (End K V) a).ker := calc eigenspace f (a / b) = eigenspace f (b⁻¹ * a) : by { rw [div_eq_mul_inv, mul_comm] } ... = (f - (b⁻¹ * a) • linear_map.id).ker : rfl ... = (f - b⁻¹ • a • linear_map.id).ker : by rw smul_smul ... = (f - b⁻¹ • algebra_map K (End K V) a).ker : rfl ... = (b • (f - b⁻¹ • algebra_map K (End K V) a)).ker : by rw linear_map.ker_smul _ b hb ... = (b • f - algebra_map K (End K V) a).ker : by rw [smul_sub, smul_inv_smul₀ hb] lemma eigenspace_aeval_polynomial_degree_1 (f : End K V) (q : K[X]) (hq : degree q = 1) : eigenspace f (- q.coeff 0 / q.leading_coeff) = (aeval f q).ker := calc eigenspace f (- q.coeff 0 / q.leading_coeff) = (q.leading_coeff • f - algebra_map K (End K V) (- q.coeff 0)).ker : by { rw eigenspace_div, intro h, rw leading_coeff_eq_zero_iff_deg_eq_bot.1 h at hq, cases hq } ... = (aeval f (C q.leading_coeff * X + C (q.coeff 0))).ker : by { rw [C_mul', aeval_def], simp [algebra_map, algebra.to_ring_hom], } ... = (aeval f q).ker : by { congr, apply (eq_X_add_C_of_degree_eq_one hq).symm } lemma ker_aeval_ring_hom'_unit_polynomial (f : End K V) (c : (K[X])ˣ) : (aeval f (c : K[X])).ker = ⊥ := begin rw polynomial.eq_C_of_degree_eq_zero (degree_coe_units c), simp only [aeval_def, eval₂_C], apply ker_algebra_map_End, apply coeff_coe_units_zero_ne_zero c end theorem aeval_apply_of_has_eigenvector {f : End K V} {p : K[X]} {μ : K} {x : V} (h : f.has_eigenvector μ x) : aeval f p x = (p.eval μ) • x := begin apply p.induction_on, { intro a, simp [module.algebra_map_End_apply] }, { intros p q hp hq, simp [hp, hq, add_smul] }, { intros n a hna, rw [mul_comm, pow_succ, mul_assoc, alg_hom.map_mul, linear_map.mul_apply, mul_comm, hna], simp only [mem_eigenspace_iff.1 h.1, smul_smul, aeval_X, eval_mul, eval_C, eval_pow, eval_X, linear_map.map_smulₛₗ, ring_hom.id_apply, mul_comm] } end section minpoly theorem is_root_of_has_eigenvalue {f : End K V} {μ : K} (h : f.has_eigenvalue μ) : (minpoly K f).is_root μ := begin rcases (submodule.ne_bot_iff _).1 h with ⟨w, ⟨H, ne0⟩⟩, refine or.resolve_right (smul_eq_zero.1 _) ne0, simp [← aeval_apply_of_has_eigenvector ⟨H, ne0⟩, minpoly.aeval K f], end variables [finite_dimensional K V] (f : End K V) variables {f} {μ : K} theorem has_eigenvalue_of_is_root (h : (minpoly K f).is_root μ) : f.has_eigenvalue μ := begin cases dvd_iff_is_root.2 h with p hp, rw [has_eigenvalue, eigenspace], intro con, cases (linear_map.is_unit_iff_ker_eq_bot _).2 con with u hu, have p_ne_0 : p ≠ 0, { intro con, apply minpoly.ne_zero f.is_integral, rw [hp, con, mul_zero] }, have h_deg := minpoly.degree_le_of_ne_zero K f p_ne_0 _, { rw [hp, degree_mul, degree_X_sub_C, polynomial.degree_eq_nat_degree p_ne_0] at h_deg, norm_cast at h_deg, linarith, }, { have h_aeval := minpoly.aeval K f, revert h_aeval, simp [hp, ← hu] }, end theorem has_eigenvalue_iff_is_root : f.has_eigenvalue μ ↔ (minpoly K f).is_root μ := ⟨is_root_of_has_eigenvalue, has_eigenvalue_of_is_root⟩ /-- An endomorphism of a finite-dimensional vector space has finitely many eigenvalues. -/ noncomputable instance (f : End K V) : fintype f.eigenvalues := set.finite.fintype begin have h : minpoly K f ≠ 0 := minpoly.ne_zero f.is_integral, convert (minpoly K f).root_set_finite K, ext μ, have : (μ ∈ {μ : K | f.eigenspace μ = ⊥ → false}) ↔ ¬f.eigenspace μ = ⊥ := by tauto, convert rfl.mpr this, simp [polynomial.root_set_def, polynomial.mem_roots h, ← has_eigenvalue_iff_is_root, has_eigenvalue] end end minpoly /-- Every linear operator on a vector space over an algebraically closed field has an eigenvalue. -/ -- This is Lemma 5.21 of [axler2015], although we are no longer following that proof. lemma exists_eigenvalue [is_alg_closed K] [finite_dimensional K V] [nontrivial V] (f : End K V) : ∃ (c : K), f.has_eigenvalue c := by { simp_rw has_eigenvalue_iff_mem_spectrum, exact spectrum.nonempty_of_is_alg_closed_of_finite_dimensional K f } noncomputable instance [is_alg_closed K] [finite_dimensional K V] [nontrivial V] (f : End K V) : inhabited f.eigenvalues := ⟨⟨f.exists_eigenvalue.some, f.exists_eigenvalue.some_spec⟩⟩ /-- The eigenspaces of a linear operator form an independent family of subspaces of `V`. That is, any eigenspace has trivial intersection with the span of all the other eigenspaces. -/ lemma eigenspaces_independent (f : End K V) : complete_lattice.independent f.eigenspace := begin classical, -- Define an operation from `Π₀ μ : K, f.eigenspace μ`, the vector space of of finitely-supported -- choices of an eigenvector from each eigenspace, to `V`, by sending a collection to its sum. let S : @linear_map K K _ _ (ring_hom.id K) (Π₀ μ : K, f.eigenspace μ) V (@dfinsupp.add_comm_monoid K (λ μ, f.eigenspace μ) _) _ (@dfinsupp.module K _ (λ μ, f.eigenspace μ) _ _ _) _ := @dfinsupp.lsum K K ℕ _ V _ _ _ _ _ _ _ _ _ (λ μ, (f.eigenspace μ).subtype), -- We need to show that if a finitely-supported collection `l` of representatives of the -- eigenspaces has sum `0`, then it itself is zero. suffices : ∀ l : Π₀ μ, f.eigenspace μ, S l = 0 → l = 0, { rw complete_lattice.independent_iff_dfinsupp_lsum_injective, change function.injective S, rw ← @linear_map.ker_eq_bot K K (Π₀ μ, (f.eigenspace μ)) V _ _ (@dfinsupp.add_comm_group K (λ μ, f.eigenspace μ) _), rw eq_bot_iff, exact this }, intros l hl, -- We apply induction on the finite set of eigenvalues from which `l` selects a nonzero -- eigenvector, 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 dfinsupp.support_eq_empty.1 h_l_support }, -- Now assume that the support of `l` contains at least one eigenvalue `μ₀`. We define a new -- collection of representatives `l'` to apply the induction hypothesis on later. The collection -- of representatives `l'` is derived from `l` by multiplying the coefficient of the eigenvector -- with eigenvalue `μ` by `μ - μ₀`. { let l' := dfinsupp.map_range.linear_map (λ μ, (μ - μ₀) • @linear_map.id K (f.eigenspace μ) _ _ _) l, -- The support of `l'` is the support of `l` without `μ₀`. have h_l_support' : l'.support = l_support', { rw [← finset.erase_insert hμ₀, ← h_l_support], ext a, have : ¬(a = μ₀ ∨ l a = 0) ↔ ¬a = μ₀ ∧ ¬l a = 0 := not_or_distrib, simp only [l', dfinsupp.map_range.linear_map_apply, dfinsupp.map_range_apply, dfinsupp.mem_support_iff, finset.mem_erase, id.def, linear_map.id_coe, linear_map.smul_apply, ne.def, smul_eq_zero, sub_eq_zero, this] }, -- The entries of `l'` add up to `0`. have total_l' : S l' = 0, { let g := f - algebra_map K (End K V) μ₀, let a : Π₀ μ : K, V := dfinsupp.map_range.linear_map (λ μ, (f.eigenspace μ).subtype) l, calc S l' = dfinsupp.lsum ℕ (λ μ, (f.eigenspace μ).subtype.comp ((μ - μ₀) • linear_map.id)) l : _ ... = dfinsupp.lsum ℕ (λ μ, g.comp (f.eigenspace μ).subtype) l : _ ... = dfinsupp.lsum ℕ (λ μ, g) a : _ ... = g (dfinsupp.lsum ℕ (λ μ, (linear_map.id : V →ₗ[K] V)) a) : _ ... = g (S l) : _ ... = 0 : by rw [hl, g.map_zero], { exact dfinsupp.sum_map_range_index.linear_map }, { congr, ext μ v, simp only [g, eq_self_iff_true, function.comp_app, id.def, linear_map.coe_comp, linear_map.id_coe, linear_map.smul_apply, linear_map.sub_apply, module.algebra_map_End_apply, sub_left_inj, sub_smul, submodule.coe_smul_of_tower, submodule.coe_sub, submodule.subtype_apply, mem_eigenspace_iff.1 v.prop], }, { rw dfinsupp.sum_map_range_index.linear_map }, { simp only [dfinsupp.sum_add_hom_apply, linear_map.id_coe, linear_map.map_dfinsupp_sum, id.def, linear_map.to_add_monoid_hom_coe, dfinsupp.lsum_apply_apply], }, { congr, simp only [S, a, dfinsupp.sum_map_range_index.linear_map, linear_map.id_comp] } }, -- Therefore, by the induction hypothesis, all entries of `l'` are zero. have l'_eq_0 := ih l' total_l' h_l_support', -- By the definition of `l'`, this means that `(μ - μ₀) • l μ = 0` for all `μ`. have h_smul_eq_0 : ∀ μ, (μ - μ₀) • l μ = 0, { intro μ, calc (μ - μ₀) • l μ = l' μ : by simp only [l', linear_map.id_coe, id.def, linear_map.smul_apply, dfinsupp.map_range_apply, dfinsupp.map_range.linear_map_apply] ... = 0 : by { rw [l'_eq_0], refl } }, -- Thus, the eigenspace-representatives in `l` for all `μ ≠ μ₀` are `0`. have h_lμ_eq_0 : ∀ μ : K, μ ≠ μ₀ → l μ = 0, { intros μ hμ, apply or_iff_not_imp_left.1 (smul_eq_zero.1 (h_smul_eq_0 μ)), rwa [sub_eq_zero] }, -- So if we sum over all these representatives, we obtain `0`. have h_sum_l_support'_eq_0 : finset.sum l_support' (λ μ, (l μ : V)) = 0, { rw ←finset.sum_const_zero, apply finset.sum_congr rfl, intros μ hμ, rw [submodule.coe_eq_zero, h_lμ_eq_0], rintro rfl, exact hμ₀ hμ }, -- The only potentially nonzero eigenspace-representative in `l` is the one corresponding to -- `μ₀`. But since the overall sum is `0` by assumption, this representative must also be `0`. have : l μ₀ = 0, { simp only [S, dfinsupp.lsum_apply_apply, dfinsupp.sum_add_hom_apply, linear_map.to_add_monoid_hom_coe, dfinsupp.sum, h_l_support, submodule.subtype_apply, submodule.coe_eq_zero, finset.sum_insert hμ₀, h_sum_l_support'_eq_0, add_zero] at hl, exact hl }, -- Thus, all coefficients in `l` are `0`. show l = 0, { ext μ, by_cases h_cases : μ = μ₀, { rwa [h_cases, set_like.coe_eq_coe, dfinsupp.coe_zero, pi.zero_apply] }, exact congr_arg (coe : _ → V) (h_lμ_eq_0 μ h_cases) }} end /-- Eigenvectors corresponding to distinct eigenvalues of a linear operator are linearly independent. (Lemma 5.10 of [axler2015]) We use the eigenvalues as indexing set to ensure that there is only one eigenvector for each eigenvalue in the image of `xs`. -/ lemma eigenvectors_linear_independent (f : End K V) (μs : set K) (xs : μs → V) (h_eigenvec : ∀ μ : μs, f.has_eigenvector μ (xs μ)) : linear_independent K xs := complete_lattice.independent.linear_independent _ (f.eigenspaces_independent.comp (coe : μs → K) subtype.coe_injective) (λ μ, (h_eigenvec μ).1) (λ μ, (h_eigenvec μ).2) /-- The generalized eigenspace for a linear map `f`, a scalar `μ`, and an exponent `k ∈ ℕ` is the kernel of `(f - μ • id) ^ k`. (Def 8.10 of [axler2015]). Furthermore, a generalized eigenspace for some exponent `k` is contained in the generalized eigenspace for exponents larger than `k`. -/ def generalized_eigenspace (f : End R M) (μ : R) : ℕ →o submodule R M := { to_fun := λ k, ((f - algebra_map R (End R M) μ) ^ k).ker, monotone' := λ k m hm, begin simp only [← pow_sub_mul_pow _ hm], exact linear_map.ker_le_ker_comp ((f - algebra_map R (End R M) μ) ^ k) ((f - algebra_map R (End R M) μ) ^ (m - k)), end } @[simp] lemma mem_generalized_eigenspace (f : End R M) (μ : R) (k : ℕ) (m : M) : m ∈ f.generalized_eigenspace μ k ↔ ((f - μ • 1)^k) m = 0 := iff.rfl /-- A nonzero element of a generalized eigenspace is a generalized eigenvector. (Def 8.9 of [axler2015])-/ def has_generalized_eigenvector (f : End R M) (μ : R) (k : ℕ) (x : M) : Prop := x ≠ 0 ∧ x ∈ generalized_eigenspace f μ k /-- A scalar `μ` is a generalized eigenvalue for a linear map `f` and an exponent `k ∈ ℕ` if there are generalized eigenvectors for `f`, `k`, and `μ`. -/ def has_generalized_eigenvalue (f : End R M) (μ : R) (k : ℕ) : Prop := generalized_eigenspace f μ k ≠ ⊥ /-- The generalized eigenrange for a linear map `f`, a scalar `μ`, and an exponent `k ∈ ℕ` is the range of `(f - μ • id) ^ k`. -/ def generalized_eigenrange (f : End R M) (μ : R) (k : ℕ) : submodule R M := ((f - algebra_map R (End R M) μ) ^ k).range /-- The exponent of a generalized eigenvalue is never 0. -/ lemma exp_ne_zero_of_has_generalized_eigenvalue {f : End R M} {μ : R} {k : ℕ} (h : f.has_generalized_eigenvalue μ k) : k ≠ 0 := begin rintro rfl, exact h linear_map.ker_id end /-- The union of the kernels of `(f - μ • id) ^ k` over all `k`. -/ def maximal_generalized_eigenspace (f : End R M) (μ : R) : submodule R M := ⨆ k, f.generalized_eigenspace μ k lemma generalized_eigenspace_le_maximal (f : End R M) (μ : R) (k : ℕ) : f.generalized_eigenspace μ k ≤ f.maximal_generalized_eigenspace μ := le_supr _ _ @[simp] lemma mem_maximal_generalized_eigenspace (f : End R M) (μ : R) (m : M) : m ∈ f.maximal_generalized_eigenspace μ ↔ ∃ (k : ℕ), ((f - μ • 1)^k) m = 0 := by simp only [maximal_generalized_eigenspace, ← mem_generalized_eigenspace, submodule.mem_supr_of_chain] /-- If there exists a natural number `k` such that the kernel of `(f - μ • id) ^ k` is the maximal generalized eigenspace, then this value is the least such `k`. If not, this value is not meaningful. -/ noncomputable def maximal_generalized_eigenspace_index (f : End R M) (μ : R) := monotonic_sequence_limit_index (f.generalized_eigenspace μ) /-- For an endomorphism of a Noetherian module, the maximal eigenspace is always of the form kernel `(f - μ • id) ^ k` for some `k`. -/ lemma maximal_generalized_eigenspace_eq [h : is_noetherian R M] (f : End R M) (μ : R) : maximal_generalized_eigenspace f μ = f.generalized_eigenspace μ (maximal_generalized_eigenspace_index f μ) := begin rw is_noetherian_iff_well_founded at h, exact (well_founded.supr_eq_monotonic_sequence_limit h (f.generalized_eigenspace μ) : _), end /-- A generalized eigenvalue for some exponent `k` is also a generalized eigenvalue for exponents larger than `k`. -/ lemma has_generalized_eigenvalue_of_has_generalized_eigenvalue_of_le {f : End R M} {μ : R} {k : ℕ} {m : ℕ} (hm : k ≤ m) (hk : f.has_generalized_eigenvalue μ k) : f.has_generalized_eigenvalue μ m := begin unfold has_generalized_eigenvalue at *, contrapose! hk, rw [←le_bot_iff, ←hk], exact (f.generalized_eigenspace μ).monotone hm, end /-- The eigenspace is a subspace of the generalized eigenspace. -/ lemma eigenspace_le_generalized_eigenspace {f : End R M} {μ : R} {k : ℕ} (hk : 0 < k) : f.eigenspace μ ≤ f.generalized_eigenspace μ k := (f.generalized_eigenspace μ).monotone (nat.succ_le_of_lt hk) /-- All eigenvalues are generalized eigenvalues. -/ lemma has_generalized_eigenvalue_of_has_eigenvalue {f : End R M} {μ : R} {k : ℕ} (hk : 0 < k) (hμ : f.has_eigenvalue μ) : f.has_generalized_eigenvalue μ k := begin apply has_generalized_eigenvalue_of_has_generalized_eigenvalue_of_le hk, rw [has_generalized_eigenvalue, generalized_eigenspace, order_hom.coe_fun_mk, pow_one], exact hμ, end /-- All generalized eigenvalues are eigenvalues. -/ lemma has_eigenvalue_of_has_generalized_eigenvalue {f : End R M} {μ : R} {k : ℕ} (hμ : f.has_generalized_eigenvalue μ k) : f.has_eigenvalue μ := begin intros contra, apply hμ, erw linear_map.ker_eq_bot at ⊢ contra, rw linear_map.coe_pow, exact function.injective.iterate contra k, end /-- Generalized eigenvalues are actually just eigenvalues. -/ @[simp] lemma has_generalized_eigenvalue_iff_has_eigenvalue {f : End R M} {μ : R} {k : ℕ} (hk : 0 < k) : f.has_generalized_eigenvalue μ k ↔ f.has_eigenvalue μ := ⟨has_eigenvalue_of_has_generalized_eigenvalue, has_generalized_eigenvalue_of_has_eigenvalue hk⟩ /-- Every generalized eigenvector is a generalized eigenvector for exponent `finrank K V`. (Lemma 8.11 of [axler2015]) -/ lemma generalized_eigenspace_le_generalized_eigenspace_finrank [finite_dimensional K V] (f : End K V) (μ : K) (k : ℕ) : f.generalized_eigenspace μ k ≤ f.generalized_eigenspace μ (finrank K V) := ker_pow_le_ker_pow_finrank _ _ /-- Generalized eigenspaces for exponents at least `finrank K V` are equal to each other. -/ lemma generalized_eigenspace_eq_generalized_eigenspace_finrank_of_le [finite_dimensional K V] (f : End K V) (μ : K) {k : ℕ} (hk : finrank K V ≤ k) : f.generalized_eigenspace μ k = f.generalized_eigenspace μ (finrank K V) := ker_pow_eq_ker_pow_finrank_of_le hk /-- If `f` maps a subspace `p` into itself, then the generalized eigenspace of the restriction of `f` to `p` is the part of the generalized eigenspace of `f` that lies in `p`. -/ lemma generalized_eigenspace_restrict (f : End R M) (p : submodule R M) (k : ℕ) (μ : R) (hfp : ∀ (x : M), x ∈ p → f x ∈ p) : generalized_eigenspace (linear_map.restrict f hfp) μ k = submodule.comap p.subtype (f.generalized_eigenspace μ k) := begin simp only [generalized_eigenspace, order_hom.coe_fun_mk, ← linear_map.ker_comp], induction k with k ih, { rw [pow_zero, pow_zero, linear_map.one_eq_id], apply (submodule.ker_subtype _).symm }, { erw [pow_succ', pow_succ', linear_map.ker_comp, linear_map.ker_comp, ih, ← linear_map.ker_comp, linear_map.comp_assoc] }, end /-- If `p` is an invariant submodule of an endomorphism `f`, then the `μ`-eigenspace of the restriction of `f` to `p` is a submodule of the `μ`-eigenspace of `f`. -/ lemma eigenspace_restrict_le_eigenspace (f : End R M) {p : submodule R M} (hfp : ∀ x ∈ p, f x ∈ p) (μ : R) : (eigenspace (f.restrict hfp) μ).map p.subtype ≤ f.eigenspace μ := begin rintros a ⟨x, hx, rfl⟩, simp only [set_like.mem_coe, mem_eigenspace_iff, linear_map.restrict_apply] at hx ⊢, exact congr_arg coe hx end /-- Generalized eigenrange and generalized eigenspace for exponent `finrank K V` are disjoint. -/ lemma generalized_eigenvec_disjoint_range_ker [finite_dimensional K V] (f : End K V) (μ : K) : disjoint (f.generalized_eigenrange μ (finrank K V)) (f.generalized_eigenspace μ (finrank K V)) := begin have h := calc submodule.comap ((f - algebra_map _ _ μ) ^ finrank K V) (f.generalized_eigenspace μ (finrank K V)) = ((f - algebra_map _ _ μ) ^ finrank K V * (f - algebra_map K (End K V) μ) ^ finrank K V).ker : by { simpa only [generalized_eigenspace, order_hom.coe_fun_mk, ← linear_map.ker_comp] } ... = f.generalized_eigenspace μ (finrank K V + finrank K V) : by { rw ←pow_add, refl } ... = f.generalized_eigenspace μ (finrank K V) : by { rw generalized_eigenspace_eq_generalized_eigenspace_finrank_of_le, linarith }, rw [disjoint, generalized_eigenrange, linear_map.range_eq_map, submodule.map_inf_eq_map_inf_comap, top_inf_eq, h], apply submodule.map_comap_le end /-- If an invariant subspace `p` of an endomorphism `f` is disjoint from the `μ`-eigenspace of `f`, then the restriction of `f` to `p` has trivial `μ`-eigenspace. -/ lemma eigenspace_restrict_eq_bot {f : End R M} {p : submodule R M} (hfp : ∀ x ∈ p, f x ∈ p) {μ : R} (hμp : disjoint (f.eigenspace μ) p) : eigenspace (f.restrict hfp) μ = ⊥ := begin rw eq_bot_iff, intros x hx, simpa using hμp ⟨eigenspace_restrict_le_eigenspace f hfp μ ⟨x, hx, rfl⟩, x.prop⟩, end /-- The generalized eigenspace of an eigenvalue has positive dimension for positive exponents. -/ lemma pos_finrank_generalized_eigenspace_of_has_eigenvalue [finite_dimensional K V] {f : End K V} {k : ℕ} {μ : K} (hx : f.has_eigenvalue μ) (hk : 0 < k): 0 < finrank K (f.generalized_eigenspace μ k) := calc 0 = finrank K (⊥ : submodule K V) : by rw finrank_bot ... < finrank K (f.eigenspace μ) : submodule.finrank_lt_finrank_of_lt (bot_lt_iff_ne_bot.2 hx) ... ≤ finrank K (f.generalized_eigenspace μ k) : submodule.finrank_mono ((f.generalized_eigenspace μ).monotone (nat.succ_le_of_lt hk)) /-- A linear map maps a generalized eigenrange into itself. -/ lemma map_generalized_eigenrange_le {f : End K V} {μ : K} {n : ℕ} : submodule.map f (f.generalized_eigenrange μ n) ≤ f.generalized_eigenrange μ n := calc submodule.map f (f.generalized_eigenrange μ n) = (f * ((f - algebra_map _ _ μ) ^ n)).range : (linear_map.range_comp _ _).symm ... = (((f - algebra_map _ _ μ) ^ n) * f).range : by rw algebra.mul_sub_algebra_map_pow_commutes ... = submodule.map ((f - algebra_map _ _ μ) ^ n) f.range : linear_map.range_comp _ _ ... ≤ f.generalized_eigenrange μ n : linear_map.map_le_range /-- The generalized eigenvectors span the entire vector space (Lemma 8.21 of [axler2015]). -/ lemma supr_generalized_eigenspace_eq_top [is_alg_closed K] [finite_dimensional K V] (f : End K V) : (⨆ (μ : K) (k : ℕ), f.generalized_eigenspace μ k) = ⊤ := begin -- We prove the claim by strong induction on the dimension of the vector space. unfreezingI { induction h_dim : finrank K V using nat.strong_induction_on with n ih generalizing V }, cases n, -- If the vector space is 0-dimensional, the result is trivial. { rw ←top_le_iff, simp only [finrank_eq_zero.1 (eq.trans finrank_top h_dim), bot_le] }, -- Otherwise the vector space is nontrivial. { haveI : nontrivial V := finrank_pos_iff.1 (by { rw h_dim, apply nat.zero_lt_succ }), -- Hence, `f` has an eigenvalue `μ₀`. obtain ⟨μ₀, hμ₀⟩ : ∃ μ₀, f.has_eigenvalue μ₀ := exists_eigenvalue f, -- We define `ES` to be the generalized eigenspace let ES := f.generalized_eigenspace μ₀ (finrank K V), -- and `ER` to be the generalized eigenrange. let ER := f.generalized_eigenrange μ₀ (finrank K V), -- `f` maps `ER` into itself. have h_f_ER : ∀ (x : V), x ∈ ER → f x ∈ ER, from λ x hx, map_generalized_eigenrange_le (submodule.mem_map_of_mem hx), -- Therefore, we can define the restriction `f'` of `f` to `ER`. let f' : End K ER := f.restrict h_f_ER, -- The dimension of `ES` is positive have h_dim_ES_pos : 0 < finrank K ES, { dsimp only [ES], rw h_dim, apply pos_finrank_generalized_eigenspace_of_has_eigenvalue hμ₀ (nat.zero_lt_succ n) }, -- and the dimensions of `ES` and `ER` add up to `finrank K V`. have h_dim_add : finrank K ER + finrank K ES = finrank K V, { apply linear_map.finrank_range_add_finrank_ker }, -- Therefore the dimension `ER` mus be smaller than `finrank K V`. have h_dim_ER : finrank K ER < n.succ, by linarith, -- This allows us to apply the induction hypothesis on `ER`: have ih_ER : (⨆ (μ : K) (k : ℕ), f'.generalized_eigenspace μ k) = ⊤, from ih (finrank K ER) h_dim_ER f' rfl, -- The induction hypothesis gives us a statement about subspaces of `ER`. We can transfer this -- to a statement about subspaces of `V` via `submodule.subtype`: have ih_ER' : (⨆ (μ : K) (k : ℕ), (f'.generalized_eigenspace μ k).map ER.subtype) = ER, by simp only [(submodule.map_supr _ _).symm, ih_ER, submodule.map_subtype_top ER], -- Moreover, every generalized eigenspace of `f'` is contained in the corresponding generalized -- eigenspace of `f`. have hff' : ∀ μ k, (f'.generalized_eigenspace μ k).map ER.subtype ≤ f.generalized_eigenspace μ k, { intros, rw generalized_eigenspace_restrict, apply submodule.map_comap_le }, -- It follows that `ER` is contained in the span of all generalized eigenvectors. have hER : ER ≤ ⨆ (μ : K) (k : ℕ), f.generalized_eigenspace μ k, { rw ← ih_ER', exact supr₂_mono hff' }, -- `ES` is contained in this span by definition. have hES : ES ≤ ⨆ (μ : K) (k : ℕ), f.generalized_eigenspace μ k, from le_trans (le_supr (λ k, f.generalized_eigenspace μ₀ k) (finrank K V)) (le_supr (λ (μ : K), ⨆ (k : ℕ), f.generalized_eigenspace μ k) μ₀), -- Moreover, we know that `ER` and `ES` are disjoint. have h_disjoint : disjoint ER ES, from generalized_eigenvec_disjoint_range_ker f μ₀, -- Since the dimensions of `ER` and `ES` add up to the dimension of `V`, it follows that the -- span of all generalized eigenvectors is all of `V`. show (⨆ (μ : K) (k : ℕ), f.generalized_eigenspace μ k) = ⊤, { rw [←top_le_iff, ←submodule.eq_top_of_disjoint ER ES h_dim_add h_disjoint], apply sup_le hER hES } } end end End end module
a82549fcae2737b87e18f38272ae2b300be8581a
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/convex/strict_convex_space.lean
39d0309c9d23d1a41e4ad666920f4fe0a97f40c9
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
14,185
lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Yury Kudryashov -/ import analysis.convex.strict import analysis.convex.topology import analysis.normed.order.basic import analysis.normed_space.add_torsor import analysis.normed_space.pointwise import analysis.normed_space.affine_isometry /-! # Strictly convex spaces This file defines strictly convex spaces. A normed space is strictly convex if all closed balls are strictly convex. This does **not** mean that the norm is strictly convex (in fact, it never is). ## Main definitions `strict_convex_space`: a typeclass saying that a given normed space over a normed linear ordered field (e.g., `ℝ` or `ℚ`) is strictly convex. The definition requires strict convexity of a closed ball of positive radius with center at the origin; strict convexity of any other closed ball follows from this assumption. ## Main results In a strictly convex space, we prove - `strict_convex_closed_ball`: a closed ball is strictly convex. - `combo_mem_ball_of_ne`, `open_segment_subset_ball_of_ne`, `norm_combo_lt_of_ne`: a nontrivial convex combination of two points in a closed ball belong to the corresponding open ball; - `norm_add_lt_of_not_same_ray`, `same_ray_iff_norm_add`, `dist_add_dist_eq_iff`: the triangle inequality `dist x y + dist y z ≤ dist x z` is a strict inequality unless `y` belongs to the segment `[x -[ℝ] z]`. - `isometry.affine_isometry_of_strict_convex_space`: an isometry of `normed_add_torsor`s for real normed spaces, strictly convex in the case of the codomain, is an affine isometry. We also provide several lemmas that can be used as alternative constructors for `strict_convex ℝ E`: - `strict_convex_space.of_strict_convex_closed_unit_ball`: if `closed_ball (0 : E) 1` is strictly convex, then `E` is a strictly convex space; - `strict_convex_space.of_norm_add`: if `‖x + y‖ = ‖x‖ + ‖y‖` implies `same_ray ℝ x y` for all nonzero `x y : E`, then `E` is a strictly convex space. ## Implementation notes While the definition is formulated for any normed linear ordered field, most of the lemmas are formulated only for the case `𝕜 = ℝ`. ## Tags convex, strictly convex -/ open set metric open_locale convex pointwise /-- A *strictly convex space* is a normed space where the closed balls are strictly convex. We only require balls of positive radius with center at the origin to be strictly convex in the definition, then prove that any closed ball is strictly convex in `strict_convex_closed_ball` below. See also `strict_convex_space.of_strict_convex_closed_unit_ball`. -/ class strict_convex_space (𝕜 E : Type*) [normed_linear_ordered_field 𝕜] [normed_add_comm_group E] [normed_space 𝕜 E] : Prop := (strict_convex_closed_ball : ∀ r : ℝ, 0 < r → strict_convex 𝕜 (closed_ball (0 : E) r)) variables (𝕜 : Type*) {E : Type*} [normed_linear_ordered_field 𝕜] [normed_add_comm_group E] [normed_space 𝕜 E] /-- A closed ball in a strictly convex space is strictly convex. -/ lemma strict_convex_closed_ball [strict_convex_space 𝕜 E] (x : E) (r : ℝ) : strict_convex 𝕜 (closed_ball x r) := begin cases le_or_lt r 0 with hr hr, { exact (subsingleton_closed_ball x hr).strict_convex }, rw ← vadd_closed_ball_zero, exact (strict_convex_space.strict_convex_closed_ball r hr).vadd _, end variables [normed_space ℝ E] /-- A real normed vector space is strictly convex provided that the unit ball is strictly convex. -/ lemma strict_convex_space.of_strict_convex_closed_unit_ball [linear_map.compatible_smul E E 𝕜 ℝ] (h : strict_convex 𝕜 (closed_ball (0 : E) 1)) : strict_convex_space 𝕜 E := ⟨λ r hr, by simpa only [smul_closed_unit_ball_of_nonneg hr.le] using h.smul r⟩ /-- Strict convexity is equivalent to `‖a • x + b • y‖ < 1` for all `x` and `y` of norm at most `1` and all strictly positive `a` and `b` such that `a + b = 1`. This lemma shows that it suffices to check this for points of norm one and some `a`, `b` such that `a + b = 1`. -/ lemma strict_convex_space.of_norm_combo_lt_one (h : ∀ x y : E, ‖x‖ = 1 → ‖y‖ = 1 → x ≠ y → ∃ a b : ℝ, a + b = 1 ∧ ‖a • x + b • y‖ < 1) : strict_convex_space ℝ E := begin refine strict_convex_space.of_strict_convex_closed_unit_ball ℝ ((convex_closed_ball _ _).strict_convex' $ λ x hx y hy hne, _), rw [interior_closed_ball (0 : E) one_ne_zero, closed_ball_diff_ball, mem_sphere_zero_iff_norm] at hx hy, rcases h x y hx hy hne with ⟨a, b, hab, hlt⟩, use b, rwa [affine_map.line_map_apply_module, interior_closed_ball (0 : E) one_ne_zero, mem_ball_zero_iff, sub_eq_iff_eq_add.2 hab.symm] end lemma strict_convex_space.of_norm_combo_ne_one (h : ∀ x y : E, ‖x‖ = 1 → ‖y‖ = 1 → x ≠ y → ∃ a b : ℝ, 0 ≤ a ∧ 0 ≤ b ∧ a + b = 1 ∧ ‖a • x + b • y‖ ≠ 1) : strict_convex_space ℝ E := begin refine strict_convex_space.of_strict_convex_closed_unit_ball ℝ ((convex_closed_ball _ _).strict_convex _), simp only [interior_closed_ball _ one_ne_zero, closed_ball_diff_ball, set.pairwise, frontier_closed_ball _ one_ne_zero, mem_sphere_zero_iff_norm], intros x hx y hy hne, rcases h x y hx hy hne with ⟨a, b, ha, hb, hab, hne'⟩, exact ⟨_, ⟨a, b, ha, hb, hab, rfl⟩, mt mem_sphere_zero_iff_norm.1 hne'⟩ end lemma strict_convex_space.of_norm_add_ne_two (h : ∀ ⦃x y : E⦄, ‖x‖ = 1 → ‖y‖ = 1 → x ≠ y → ‖x + y‖ ≠ 2) : strict_convex_space ℝ E := begin refine strict_convex_space.of_norm_combo_ne_one (λ x y hx hy hne, ⟨1/2, 1/2, one_half_pos.le, one_half_pos.le, add_halves _, _⟩), rw [← smul_add, norm_smul, real.norm_of_nonneg one_half_pos.le, one_div, ← div_eq_inv_mul, ne.def, div_eq_one_iff_eq (two_ne_zero' ℝ)], exact h hx hy hne, end lemma strict_convex_space.of_pairwise_sphere_norm_ne_two (h : (sphere (0 : E) 1).pairwise $ λ x y, ‖x + y‖ ≠ 2) : strict_convex_space ℝ E := strict_convex_space.of_norm_add_ne_two $ λ x y hx hy, h (mem_sphere_zero_iff_norm.2 hx) (mem_sphere_zero_iff_norm.2 hy) /-- If `‖x + y‖ = ‖x‖ + ‖y‖` implies that `x y : E` are in the same ray, then `E` is a strictly convex space. See also a more -/ lemma strict_convex_space.of_norm_add (h : ∀ x y : E, ‖x‖ = 1 → ‖y‖ = 1 → ‖x + y‖ = 2 → same_ray ℝ x y) : strict_convex_space ℝ E := begin refine strict_convex_space.of_pairwise_sphere_norm_ne_two (λ x hx y hy, mt $ λ h₂, _), rw mem_sphere_zero_iff_norm at hx hy, exact (same_ray_iff_of_norm_eq (hx.trans hy.symm)).1 (h x y hx hy h₂) end variables [strict_convex_space ℝ E] {x y z : E} {a b r : ℝ} /-- If `x ≠ y` belong to the same closed ball, then a convex combination of `x` and `y` with positive coefficients belongs to the corresponding open ball. -/ lemma combo_mem_ball_of_ne (hx : x ∈ closed_ball z r) (hy : y ∈ closed_ball z r) (hne : x ≠ y) (ha : 0 < a) (hb : 0 < b) (hab : a + b = 1) : a • x + b • y ∈ ball z r := begin rcases eq_or_ne r 0 with rfl|hr, { rw [closed_ball_zero, mem_singleton_iff] at hx hy, exact (hne (hx.trans hy.symm)).elim }, { simp only [← interior_closed_ball _ hr] at hx hy ⊢, exact strict_convex_closed_ball ℝ z r hx hy hne ha hb hab } end /-- If `x ≠ y` belong to the same closed ball, then the open segment with endpoints `x` and `y` is included in the corresponding open ball. -/ lemma open_segment_subset_ball_of_ne (hx : x ∈ closed_ball z r) (hy : y ∈ closed_ball z r) (hne : x ≠ y) : open_segment ℝ x y ⊆ ball z r := (open_segment_subset_iff _).2 $ λ a b, combo_mem_ball_of_ne hx hy hne /-- If `x` and `y` are two distinct vectors of norm at most `r`, then a convex combination of `x` and `y` with positive coefficients has norm strictly less than `r`. -/ lemma norm_combo_lt_of_ne (hx : ‖x‖ ≤ r) (hy : ‖y‖ ≤ r) (hne : x ≠ y) (ha : 0 < a) (hb : 0 < b) (hab : a + b = 1) : ‖a • x + b • y‖ < r := begin simp only [← mem_ball_zero_iff, ← mem_closed_ball_zero_iff] at hx hy ⊢, exact combo_mem_ball_of_ne hx hy hne ha hb hab end /-- In a strictly convex space, if `x` and `y` are not in the same ray, then `‖x + y‖ < ‖x‖ + ‖y‖`. -/ lemma norm_add_lt_of_not_same_ray (h : ¬same_ray ℝ x y) : ‖x + y‖ < ‖x‖ + ‖y‖ := begin simp only [same_ray_iff_inv_norm_smul_eq, not_or_distrib, ← ne.def] at h, rcases h with ⟨hx, hy, hne⟩, rw ← norm_pos_iff at hx hy, have hxy : 0 < ‖x‖ + ‖y‖ := add_pos hx hy, have := combo_mem_ball_of_ne (inv_norm_smul_mem_closed_unit_ball x) (inv_norm_smul_mem_closed_unit_ball y) hne (div_pos hx hxy) (div_pos hy hxy) (by rw [← add_div, div_self hxy.ne']), rwa [mem_ball_zero_iff, div_eq_inv_mul, div_eq_inv_mul, mul_smul, mul_smul, smul_inv_smul₀ hx.ne', smul_inv_smul₀ hy.ne', ← smul_add, norm_smul, real.norm_of_nonneg (inv_pos.2 hxy).le, ← div_eq_inv_mul, div_lt_one hxy] at this end lemma lt_norm_sub_of_not_same_ray (h : ¬same_ray ℝ x y) : ‖x‖ - ‖y‖ < ‖x - y‖ := begin nth_rewrite 0 ←sub_add_cancel x y at ⊢ h, exact sub_lt_iff_lt_add.2 (norm_add_lt_of_not_same_ray $ λ H', h $ H'.add_left same_ray.rfl), end lemma abs_lt_norm_sub_of_not_same_ray (h : ¬same_ray ℝ x y) : |‖x‖ - ‖y‖| < ‖x - y‖ := begin refine abs_sub_lt_iff.2 ⟨lt_norm_sub_of_not_same_ray h, _⟩, rw norm_sub_rev, exact lt_norm_sub_of_not_same_ray (mt same_ray.symm h), end /-- In a strictly convex space, two vectors `x`, `y` are in the same ray if and only if the triangle inequality for `x` and `y` becomes an equality. -/ lemma same_ray_iff_norm_add : same_ray ℝ x y ↔ ‖x + y‖ = ‖x‖ + ‖y‖ := ⟨same_ray.norm_add, λ h, not_not.1 $ λ h', (norm_add_lt_of_not_same_ray h').ne h⟩ /-- If `x` and `y` are two vectors in a strictly convex space have the same norm and the norm of their sum is equal to the sum of their norms, then they are equal. -/ lemma eq_of_norm_eq_of_norm_add_eq (h₁ : ‖x‖ = ‖y‖) (h₂ : ‖x + y‖ = ‖x‖ + ‖y‖) : x = y := (same_ray_iff_norm_add.mpr h₂).eq_of_norm_eq h₁ /-- In a strictly convex space, two vectors `x`, `y` are not in the same ray if and only if the triangle inequality for `x` and `y` is strict. -/ lemma not_same_ray_iff_norm_add_lt : ¬ same_ray ℝ x y ↔ ‖x + y‖ < ‖x‖ + ‖y‖ := same_ray_iff_norm_add.not.trans (norm_add_le _ _).lt_iff_ne.symm lemma same_ray_iff_norm_sub : same_ray ℝ x y ↔ ‖x - y‖ = |‖x‖ - ‖y‖| := ⟨same_ray.norm_sub, λ h, not_not.1 $ λ h', (abs_lt_norm_sub_of_not_same_ray h').ne' h⟩ lemma not_same_ray_iff_abs_lt_norm_sub : ¬ same_ray ℝ x y ↔ |‖x‖ - ‖y‖| < ‖x - y‖ := same_ray_iff_norm_sub.not.trans $ ne_comm.trans (abs_norm_sub_norm_le _ _).lt_iff_ne.symm /-- In a strictly convex space, the triangle inequality turns into an equality if and only if the middle point belongs to the segment joining two other points. -/ lemma dist_add_dist_eq_iff : dist x y + dist y z = dist x z ↔ y ∈ [x -[ℝ] z] := by simp only [mem_segment_iff_same_ray, same_ray_iff_norm_add, dist_eq_norm', sub_add_sub_cancel', eq_comm] lemma norm_midpoint_lt_iff (h : ‖x‖ = ‖y‖) : ‖(1/2 : ℝ) • (x + y)‖ < ‖x‖ ↔ x ≠ y := by rw [norm_smul, real.norm_of_nonneg (one_div_nonneg.2 zero_le_two), ←inv_eq_one_div, ←div_eq_inv_mul, div_lt_iff (zero_lt_two' ℝ), mul_two, ←not_same_ray_iff_of_norm_eq h, not_same_ray_iff_norm_add_lt, h] variables {F : Type*} [normed_add_comm_group F] [normed_space ℝ F] variables {PF : Type*} {PE : Type*} [metric_space PF] [metric_space PE] variables [normed_add_torsor F PF] [normed_add_torsor E PE] include E lemma eq_line_map_of_dist_eq_mul_of_dist_eq_mul {x y z : PE} (hxy : dist x y = r * dist x z) (hyz : dist y z = (1 - r) * dist x z) : y = affine_map.line_map x z r := begin have : y -ᵥ x ∈ [(0 : E) -[ℝ] z -ᵥ x], { rw [← dist_add_dist_eq_iff, dist_zero_left, dist_vsub_cancel_right, ← dist_eq_norm_vsub', ← dist_eq_norm_vsub', hxy, hyz, ← add_mul, add_sub_cancel'_right, one_mul] }, rcases eq_or_ne x z with rfl|hne, { obtain rfl : y = x, by simpa, simp }, { rw [← dist_ne_zero] at hne, rcases this with ⟨a, b, ha, hb, hab, H⟩, rw [smul_zero, zero_add] at H, have H' := congr_arg norm H, rw [norm_smul, real.norm_of_nonneg hb, ← dist_eq_norm_vsub', ← dist_eq_norm_vsub', hxy, mul_left_inj' hne] at H', rw [affine_map.line_map_apply, ← H', H, vsub_vadd] }, end lemma eq_midpoint_of_dist_eq_half {x y z : PE} (hx : dist x y = dist x z / 2) (hy : dist y z = dist x z / 2) : y = midpoint ℝ x z := begin apply eq_line_map_of_dist_eq_mul_of_dist_eq_mul, { rwa [inv_of_eq_inv, ← div_eq_inv_mul] }, { rwa [inv_of_eq_inv, ← one_div, sub_half, one_div, ← div_eq_inv_mul] } end namespace isometry include F /-- An isometry of `normed_add_torsor`s for real normed spaces, strictly convex in the case of the codomain, is an affine isometry. Unlike Mazur-Ulam, this does not require the isometry to be surjective. -/ noncomputable def affine_isometry_of_strict_convex_space {f : PF → PE} (hi : isometry f) : PF →ᵃⁱ[ℝ] PE := { norm_map := λ x, by simp [affine_map.of_map_midpoint, ←dist_eq_norm_vsub E, hi.dist_eq], ..affine_map.of_map_midpoint f (λ x y, begin apply eq_midpoint_of_dist_eq_half, { rw [hi.dist_eq, hi.dist_eq, dist_left_midpoint, real.norm_of_nonneg zero_le_two, div_eq_inv_mul] }, { rw [hi.dist_eq, hi.dist_eq, dist_midpoint_right, real.norm_of_nonneg zero_le_two, div_eq_inv_mul] }, end) hi.continuous } @[simp] lemma coe_affine_isometry_of_strict_convex_space {f : PF → PE} (hi : isometry f) : ⇑(hi.affine_isometry_of_strict_convex_space) = f := rfl @[simp] lemma affine_isometry_of_strict_convex_space_apply {f : PF → PE} (hi : isometry f) (p : PF) : hi.affine_isometry_of_strict_convex_space p = f p := rfl end isometry
aad3a6e60c4855e99a3282a5c661531cb4b8aa19
ebb7367fa8ab324601b5abf705720fd4cc0e8598
/homotopy/spectrum.hlean
63dc0db23107963671b2f80419c119ded1f1a7f3
[ "Apache-2.0" ]
permissive
radams78/Spectral
3e34916d9bbd0939ee6a629e36744827ff27bfc2
c8145341046cfa2b4960ef3cc5a1117d12c43f63
refs/heads/master
1,610,421,583,830
1,481,232,014,000
1,481,232,014,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
20,522
hlean
/- Copyright (c) 2016 Michael Shulman. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Michael Shulman, Floris van Doorn -/ import homotopy.LES_of_homotopy_groups .splice homotopy.susp ..move_to_lib ..colim ..pointed_pi open eq nat int susp pointed pmap sigma is_equiv equiv fiber algebra trunc trunc_index pi group seq_colim /--------------------- Basic definitions ---------------------/ open succ_str /- The basic definitions of spectra and prespectra make sense for any successor-structure. -/ structure gen_prespectrum (N : succ_str) := (deloop : N → Type*) (glue : Π(n:N), (deloop n) →* (Ω (deloop (S n)))) attribute gen_prespectrum.deloop [coercion] structure is_spectrum [class] {N : succ_str} (E : gen_prespectrum N) := (is_equiv_glue : Πn, is_equiv (gen_prespectrum.glue E n)) attribute is_spectrum.is_equiv_glue [instance] structure gen_spectrum (N : succ_str) := (to_prespectrum : gen_prespectrum N) (to_is_spectrum : is_spectrum to_prespectrum) attribute gen_spectrum.to_prespectrum [coercion] attribute gen_spectrum.to_is_spectrum [instance] -- Classically, spectra and prespectra use the successor structure +ℕ. -- But we will use +ℤ instead, to reduce case analysis later on. abbreviation prespectrum := gen_prespectrum +ℤ abbreviation prespectrum.mk := @gen_prespectrum.mk +ℤ abbreviation spectrum := gen_spectrum +ℤ abbreviation spectrum.mk := @gen_spectrum.mk +ℤ namespace spectrum definition glue {{N : succ_str}} := @gen_prespectrum.glue N --definition glue := (@gen_prespectrum.glue +ℤ) definition equiv_glue {N : succ_str} (E : gen_prespectrum N) [H : is_spectrum E] (n:N) : (E n) ≃* (Ω (E (S n))) := pequiv_of_pmap (glue E n) (is_spectrum.is_equiv_glue E n) -- a square when we compose glue with transporting over a path in N definition glue_ptransport {N : succ_str} (X : gen_prespectrum N) {n n' : N} (p : n = n') : glue X n' ∘* ptransport X p ~* Ω→ (ptransport X (ap S p)) ∘* glue X n := by induction p; exact !pcompose_pid ⬝* !pid_pcompose⁻¹* ⬝* pwhisker_right _ !ap1_pid⁻¹* -- Sometimes an ℕ-indexed version does arise naturally, however, so -- we give a standard way to extend an ℕ-indexed (pre)spectrum to a -- ℤ-indexed one. definition psp_of_nat_indexed [constructor] (E : gen_prespectrum +ℕ) : gen_prespectrum +ℤ := gen_prespectrum.mk (λ(n:ℤ), match n with | of_nat k := E k | neg_succ_of_nat k := Ω[succ k] (E 0) end) begin intros n, cases n with n n: esimp, { exact (gen_prespectrum.glue E n) }, cases n with n, { exact (pid _) }, { exact (pid _) } end definition is_spectrum_of_nat_indexed [instance] (E : gen_prespectrum +ℕ) [H : is_spectrum E] : is_spectrum (psp_of_nat_indexed E) := begin apply is_spectrum.mk, intros n, cases n with n n: esimp, { apply is_spectrum.is_equiv_glue }, cases n with n: apply is_equiv_id end protected definition of_nat_indexed (E : gen_prespectrum +ℕ) [H : is_spectrum E] : spectrum := spectrum.mk (psp_of_nat_indexed E) (is_spectrum_of_nat_indexed E) -- In fact, a (pre)spectrum indexed on any pointed successor structure -- gives rise to one indexed on +ℕ, so in this sense +ℤ is a -- "universal" successor structure for indexing spectra. definition succ_str.of_nat {N : succ_str} (z : N) : ℕ → N | succ_str.of_nat zero := z | succ_str.of_nat (succ k) := S (succ_str.of_nat k) definition psp_of_gen_indexed [constructor] {N : succ_str} (z : N) (E : gen_prespectrum N) : gen_prespectrum +ℤ := psp_of_nat_indexed (gen_prespectrum.mk (λn, E (succ_str.of_nat z n)) (λn, gen_prespectrum.glue E (succ_str.of_nat z n))) definition is_spectrum_of_gen_indexed [instance] {N : succ_str} (z : N) (E : gen_prespectrum N) [H : is_spectrum E] : is_spectrum (psp_of_gen_indexed z E) := begin apply is_spectrum_of_nat_indexed, apply is_spectrum.mk, intros n, esimp, apply is_spectrum.is_equiv_glue end protected definition of_gen_indexed [constructor] {N : succ_str} (z : N) (E : gen_spectrum N) : spectrum := spectrum.mk (psp_of_gen_indexed z E) (is_spectrum_of_gen_indexed z E) -- Generally it's easiest to define a spectrum by giving 'equiv's -- directly. This works for any indexing succ_str. protected definition MK [constructor] {N : succ_str} (deloop : N → Type*) (glue : Π(n:N), (deloop n) ≃* (Ω (deloop (S n)))) : gen_spectrum N := gen_spectrum.mk (gen_prespectrum.mk deloop (λ(n:N), glue n)) (begin apply is_spectrum.mk, intros n, esimp, apply pequiv.to_is_equiv -- Why doesn't typeclass inference find this? end) -- Finally, we combine them and give a way to produce a (ℤ-)spectrum from a ℕ-indexed family of 'equiv's. protected definition Mk [constructor] (deloop : ℕ → Type*) (glue : Π(n:ℕ), (deloop n) ≃* (Ω (deloop (nat.succ n)))) : spectrum := spectrum.of_nat_indexed (spectrum.MK deloop glue) ------------------------------ -- Maps and homotopies of (pre)spectra ------------------------------ -- These make sense for any succ_str. structure smap {N : succ_str} (E F : gen_prespectrum N) := (to_fun : Π(n:N), E n →* F n) (glue_square : Π(n:N), glue F n ∘* to_fun n ~* Ω→ (to_fun (S n)) ∘* glue E n) open smap infix ` →ₛ `:30 := smap attribute smap.to_fun [coercion] -- A version of 'glue_square' in the spectrum case that uses 'equiv_glue' definition sglue_square {N : succ_str} {E F : gen_spectrum N} (f : E →ₛ F) (n : N) : equiv_glue F n ∘* f n ~* Ω→ (f (S n)) ∘* equiv_glue E n -- I guess this manual eta-expansion is necessary because structures lack definitional eta? := phomotopy.mk (glue_square f n) (to_homotopy_pt (glue_square f n)) definition sid {N : succ_str} (E : gen_spectrum N) : E →ₛ E := smap.mk (λn, pid (E n)) (λn, calc glue E n ∘* pid (E n) ~* glue E n : pcompose_pid ... ~* pid (Ω(E (S n))) ∘* glue E n : pid_pcompose ... ~* Ω→(pid (E (S n))) ∘* glue E n : pwhisker_right (glue E n) ap1_pid⁻¹*) definition scompose {N : succ_str} {X Y Z : gen_prespectrum N} (g : Y →ₛ Z) (f : X →ₛ Y) : X →ₛ Z := smap.mk (λn, g n ∘* f n) (λn, calc glue Z n ∘* to_fun g n ∘* to_fun f n ~* (glue Z n ∘* to_fun g n) ∘* to_fun f n : passoc ... ~* (Ω→(to_fun g (S n)) ∘* glue Y n) ∘* to_fun f n : pwhisker_right (to_fun f n) (glue_square g n) ... ~* Ω→(to_fun g (S n)) ∘* (glue Y n ∘* to_fun f n) : passoc ... ~* Ω→(to_fun g (S n)) ∘* (Ω→ (f (S n)) ∘* glue X n) : pwhisker_left Ω→(to_fun g (S n)) (glue_square f n) ... ~* (Ω→(to_fun g (S n)) ∘* Ω→(f (S n))) ∘* glue X n : passoc ... ~* Ω→(to_fun g (S n) ∘* to_fun f (S n)) ∘* glue X n : pwhisker_right (glue X n) (ap1_pcompose _ _)) infixr ` ∘ₛ `:60 := scompose definition szero [constructor] {N : succ_str} (E F : gen_prespectrum N) : E →ₛ F := smap.mk (λn, pconst (E n) (F n)) (λn, calc glue F n ∘* pconst (E n) (F n) ~* pconst (E n) (Ω(F (S n))) : pcompose_pconst ... ~* pconst (Ω(E (S n))) (Ω(F (S n))) ∘* glue E n : pconst_pcompose ... ~* Ω→(pconst (E (S n)) (F (S n))) ∘* glue E n : pwhisker_right (glue E n) (ap1_pconst _ _)) definition stransport [constructor] {N : succ_str} {A : Type} {a a' : A} (p : a = a') (E : A → gen_prespectrum N) : E a →ₛ E a' := smap.mk (λn, ptransport (λa, E a n) p) begin intro n, induction p, exact !pcompose_pid ⬝* !pid_pcompose⁻¹* ⬝* pwhisker_right _ !ap1_pid⁻¹*, end structure shomotopy {N : succ_str} {E F : gen_prespectrum N} (f g : E →ₛ F) := (to_phomotopy : Πn, f n ~* g n) (glue_homotopy : Πn, pwhisker_left (glue F n) (to_phomotopy n) ⬝* glue_square g n = -- Ideally this should be a "phomotopy2" glue_square f n ⬝* pwhisker_right (glue E n) (ap1_phomotopy (to_phomotopy (S n)))) infix ` ~ₛ `:50 := shomotopy ------------------------------ -- Suspension prespectra ------------------------------ -- This should probably go in 'susp' definition psuspn : ℕ → Type* → Type* | psuspn 0 X := X | psuspn (succ n) X := psusp (psuspn n X) -- Suspension prespectra are one that's naturally indexed on the natural numbers definition psp_susp (X : Type*) : gen_prespectrum +ℕ := gen_prespectrum.mk (λn, psuspn n X) (λn, loop_psusp_unit (psuspn n X)) /- Truncations -/ -- We could truncate prespectra too, but since the operation -- preserves spectra and isn't "correct" acting on prespectra -- without spectrifying them first anyway, why bother? definition strunc (k : ℕ₋₂) (E : spectrum) : spectrum := spectrum.Mk (λ(n:ℕ), ptrunc (k + n) (E n)) (λ(n:ℕ), (loop_ptrunc_pequiv (k + n) (E (succ n)))⁻¹ᵉ* ∘*ᵉ (ptrunc_pequiv_ptrunc (k + n) (equiv_glue E (int.of_nat n)))) /--------------------- Homotopy groups ---------------------/ -- Here we start to reap the rewards of using ℤ-indexing: we can -- read off the homotopy groups without any tedious case-analysis of -- n. We increment by 2 in order to ensure that they are all -- automatically abelian groups. definition shomotopy_group [constructor] (n : ℤ) (E : spectrum) : AbGroup := πag[0+2] (E (2 - n)) notation `πₛ[`:95 n:0 `]`:0 := shomotopy_group n definition shomotopy_group_fun [constructor] (n : ℤ) {E F : spectrum} (f : E →ₛ F) : πₛ[n] E →g πₛ[n] F := π→g[1+1] (f (2 - n)) notation `πₛ→[`:95 n:0 `]`:0 := shomotopy_group_fun n /------------------------------- Cotensor of spectra by types -------------------------------/ -- Makes sense for any indexing succ_str. Could be done for -- prespectra too, but as with truncation, why bother? definition sp_cotensor {N : succ_str} (A : Type*) (B : gen_spectrum N) : gen_spectrum N := spectrum.MK (λn, ppmap A (B n)) (λn, (loop_pmap_commute A (B (S n)))⁻¹ᵉ* ∘*ᵉ (pequiv_ppcompose_left (equiv_glue B n))) ---------------------------------------- -- Sections of parametrized spectra ---------------------------------------- -- this definition must be changed to use dependent maps respecting the basepoint, presumably -- definition spi {N : succ_str} (A : Type) (E : A -> gen_spectrum N) : gen_spectrum N := -- spectrum.MK (λn, ppi (λa, E a n)) -- (λn, (loop_ppi_commute (λa, E a (S n)))⁻¹ᵉ* ∘*ᵉ equiv_ppi_right (λa, equiv_glue (E a) n)) /----------------------------------------- Fibers and long exact sequences -----------------------------------------/ definition sfiber {N : succ_str} {X Y : gen_spectrum N} (f : X →ₛ Y) : gen_spectrum N := spectrum.MK (λn, pfiber (f n)) (λn, pfiber_loop_space (f (S n)) ∘*ᵉ pfiber_equiv_of_square _ _ (sglue_square f n)) /- the map from the fiber to the domain -/ definition spoint {N : succ_str} {X Y : gen_spectrum N} (f : X →ₛ Y) : sfiber f →ₛ X := smap.mk (λn, ppoint (f n)) begin intro n, refine _ ⬝* !passoc, refine _ ⬝* pwhisker_right _ !ap1_ppoint_phomotopy⁻¹*, rexact (pfiber_equiv_of_square_ppoint (equiv_glue X n) (equiv_glue Y n) (sglue_square f n))⁻¹* end definition π_glue (X : spectrum) (n : ℤ) : π[2] (X (2 - succ n)) ≃* π[3] (X (2 - n)) := begin refine homotopy_group_pequiv 2 (equiv_glue X (2 - succ n)) ⬝e* _, assert H : succ (2 - succ n) = 2 - n, exact ap succ !sub_sub⁻¹ ⬝ sub_add_cancel (2-n) 1, exact pequiv_of_eq (ap (λn, π[2] (Ω (X n))) H), end definition πg_glue (X : spectrum) (n : ℤ) : πg[1+1] (X (2 - succ n)) ≃g πg[2+1] (X (2 - n)) := begin refine homotopy_group_isomorphism_of_pequiv 1 (equiv_glue X (2 - succ n)) ⬝g _, assert H : succ (2 - succ n) = 2 - n, exact ap succ !sub_sub⁻¹ ⬝ sub_add_cancel (2-n) 1, exact isomorphism_of_eq (ap (λn, πg[1+1] (Ω (X n))) H), end definition πg_glue_homotopy_π_glue (X : spectrum) (n : ℤ) : πg_glue X n ~ π_glue X n := begin intro x, esimp [πg_glue, π_glue], apply ap (λp, cast p _), refine !ap_compose'⁻¹ ⬝ !ap_compose' end definition π_glue_square {X Y : spectrum} (f : X →ₛ Y) (n : ℤ) : π_glue Y n ∘* π→[2] (f (2 - succ n)) ~* π→[3] (f (2 - n)) ∘* π_glue X n := begin refine !passoc ⬝* _, assert H1 : homotopy_group_pequiv 2 (equiv_glue Y (2 - succ n)) ∘* π→[2] (f (2 - succ n)) ~* π→[2] (Ω→ (f (succ (2 - succ n)))) ∘* homotopy_group_pequiv 2 (equiv_glue X (2 - succ n)), { refine !homotopy_group_functor_compose⁻¹* ⬝* _, refine homotopy_group_functor_phomotopy 2 !sglue_square ⬝* _, apply homotopy_group_functor_compose }, refine pwhisker_left _ H1 ⬝* _, clear H1, refine !passoc⁻¹* ⬝* _ ⬝* !passoc, apply pwhisker_right, refine !pequiv_of_eq_commute ⬝* by reflexivity end section open chain_complex prod fin group universe variable u parameters {X Y : spectrum.{u}} (f : X →ₛ Y) definition LES_of_shomotopy_groups : chain_complex +3ℤ := splice (λ(n : ℤ), LES_of_homotopy_groups (f (2 - n))) (2, 0) (π_glue Y) (π_glue X) (π_glue_square f) -- This LES is definitionally what we want: example (n : ℤ) : LES_of_shomotopy_groups (n, 0) = πₛ[n] Y := idp example (n : ℤ) : LES_of_shomotopy_groups (n, 1) = πₛ[n] X := idp example (n : ℤ) : LES_of_shomotopy_groups (n, 2) = πₛ[n] (sfiber f) := idp example (n : ℤ) : cc_to_fn LES_of_shomotopy_groups (n, 0) = πₛ→[n] f := idp example (n : ℤ) : cc_to_fn LES_of_shomotopy_groups (n, 1) = πₛ→[n] (spoint f) := idp -- the maps are ugly for (n, 2) definition ab_group_LES_of_shomotopy_groups : Π(v : +3ℤ), ab_group (LES_of_shomotopy_groups v) | (n, fin.mk 0 H) := proof AbGroup.struct (πₛ[n] Y) qed | (n, fin.mk 1 H) := proof AbGroup.struct (πₛ[n] X) qed | (n, fin.mk 2 H) := proof AbGroup.struct (πₛ[n] (sfiber f)) qed | (n, fin.mk (k+3) H) := begin exfalso, apply lt_le_antisymm H, apply le_add_left end local attribute ab_group_LES_of_shomotopy_groups [instance] definition is_homomorphism_LES_of_shomotopy_groups : Π(v : +3ℤ), is_homomorphism (cc_to_fn LES_of_shomotopy_groups v) | (n, fin.mk 0 H) := proof homomorphism.struct (πₛ→[n] f) qed | (n, fin.mk 1 H) := proof homomorphism.struct (πₛ→[n] (spoint f)) qed | (n, fin.mk 2 H) := proof homomorphism.struct (homomorphism_LES_of_homotopy_groups_fun (f (2 - n)) (1, 2) ∘g homomorphism_change_fun (πg_glue Y n) _ (πg_glue_homotopy_π_glue Y n)) qed | (n, fin.mk (k+3) H) := begin exfalso, apply lt_le_antisymm H, apply le_add_left end -- In the comments below is a start on an explicit description of the LES for spectra -- Maybe it's slightly nicer to work with than the above version -- definition shomotopy_groups [reducible] : -3ℤ → AbGroup -- | (n, fin.mk 0 H) := πₛ[n] Y -- | (n, fin.mk 1 H) := πₛ[n] X -- | (n, fin.mk k H) := πₛ[n] (sfiber f) -- definition shomotopy_groups_fun : Π(n : -3ℤ), shomotopy_groups (S n) →g shomotopy_groups n -- | (n, fin.mk 0 H) := proof π→g[1+1] (f (n + 2)) qed --π→[2] f (n+2) -- --pmap_of_homomorphism (πₛ→[n] f) -- | (n, fin.mk 1 H) := proof π→g[1+1] (ppoint (f (n + 2))) qed -- | (n, fin.mk 2 H) := -- proof _ ∘g π→g[1+1] equiv_glue Y (pred n + 2) qed -- --π→[n] boundary_map ∘* pcast (ap (ptrunc 0) (loop_space_succ_eq_in Y n)) -- | (n, fin.mk (k+3) H) := begin exfalso, apply lt_le_antisymm H, apply le_add_left end end structure sp_chain_complex (N : succ_str) : Type := (car : N → spectrum) (fn : Π(n : N), car (S n) →ₛ car n) (is_chain_complex : Πn, fn n ∘ₛ fn (S n) ~ₛ szero _ _) section variables {N : succ_str} (X : sp_chain_complex N) (n : N) definition scc_to_car [unfold 2] [coercion] := @sp_chain_complex.car definition scc_to_fn [unfold 2] : X (S n) →ₛ X n := sp_chain_complex.fn X n definition scc_is_chain_complex [unfold 2] : scc_to_fn X n ∘ₛ scc_to_fn X (S n) ~ₛ szero _ _ := sp_chain_complex.is_chain_complex X n end /- Mapping spectra -/ definition mapping_prespectrum [constructor] {N : succ_str} (X : Type*) (Y : gen_prespectrum N) : gen_prespectrum N := gen_prespectrum.mk (λn, ppmap X (Y n)) (λn, pfunext X (Y (S n)) ∘* ppcompose_left (glue Y n)) definition mapping_spectrum [constructor] {N : succ_str} (X : Type*) (Y : gen_spectrum N) : gen_spectrum N := gen_spectrum.mk (mapping_prespectrum X Y) (is_spectrum.mk (λn, to_is_equiv (pequiv_ppcompose_left (equiv_glue Y n) ⬝e pfunext X (Y (S n))))) /- Spectrification -/ open chain_complex definition spectrify_type_term {N : succ_str} (X : gen_prespectrum N) (n : N) (k : ℕ) : Type* := Ω[k] (X (n +' k)) definition spectrify_type_fun' {N : succ_str} (X : gen_prespectrum N) (k : ℕ) (n : N) : Ω[k] (X n) →* Ω[k+1] (X (S n)) := !loopn_succ_in⁻¹ᵉ* ∘* Ω→[k] (glue X n) definition spectrify_type_fun {N : succ_str} (X : gen_prespectrum N) (n : N) (k : ℕ) : spectrify_type_term X n k →* spectrify_type_term X n (k+1) := spectrify_type_fun' X k (n +' k) definition spectrify_type {N : succ_str} (X : gen_prespectrum N) (n : N) : Type* := pseq_colim (spectrify_type_fun X n) /- Let Y = spectify X. Then Ω Y (n+1) ≡ Ω colim_k Ω^k X ((n + 1) + k) ... = colim_k Ω^{k+1} X ((n + 1) + k) ... = colim_k Ω^{k+1} X (n + (k + 1)) ... = colim_k Ω^k X(n + k) ... ≡ Y n -/ definition spectrify_pequiv {N : succ_str} (X : gen_prespectrum N) (n : N) : spectrify_type X n ≃* Ω (spectrify_type X (S n)) := begin refine _ ⬝e* !pseq_colim_loop⁻¹ᵉ*, refine !pshift_equiv ⬝e* _, transitivity pseq_colim (λk, spectrify_type_fun' X (succ k) (S n +' k)), rotate 1, refine pseq_colim_equiv_constant (λn, !ap1_pcompose⁻¹*), fapply pseq_colim_pequiv, { intro n, apply loopn_pequiv_loopn, apply pequiv_ap X, apply succ_str.add_succ }, { intro k, apply to_homotopy, refine !passoc⁻¹* ⬝* _, refine pwhisker_right _ (loopn_succ_in_inv_natural (succ k) _) ⬝* _, refine !passoc ⬝* _ ⬝* !passoc⁻¹*, apply pwhisker_left, refine !apn_pcompose⁻¹* ⬝* _ ⬝* !apn_pcompose, apply apn_phomotopy, exact !glue_ptransport⁻¹* } end definition spectrify [constructor] {N : succ_str} (X : gen_prespectrum N) : gen_spectrum N := spectrum.MK (spectrify_type X) (spectrify_pequiv X) definition gluen {N : succ_str} (X : gen_prespectrum N) (n : N) (k : ℕ) : X n →* Ω[k] (X (n +' k)) := by induction k with k f; reflexivity; exact !loopn_succ_in⁻¹ᵉ* ∘* Ω→[k] (glue X (n +' k)) ∘* f -- note: the forward map is (currently) not definitionally equal to gluen. Is that a problem? definition equiv_gluen {N : succ_str} (X : gen_spectrum N) (n : N) (k : ℕ) : X n ≃* Ω[k] (X (n +' k)) := by induction k with k f; reflexivity; exact f ⬝e* loopn_pequiv_loopn k (equiv_glue X (n +' k)) ⬝e* !loopn_succ_in⁻¹ᵉ* definition spectrify_map {N : succ_str} {X : gen_prespectrum N} {Y : gen_spectrum N} (f : X →ₛ Y) : X →ₛ spectrify X := begin fapply smap.mk, { intro n, exact pinclusion _ 0}, { intro n, exact sorry} end definition spectrify.elim {N : succ_str} {X : gen_prespectrum N} {Y : gen_spectrum N} (f : X →ₛ Y) : spectrify X →ₛ Y := begin fapply smap.mk, { intro n, fapply pseq_colim.elim, { intro k, refine !equiv_gluen⁻¹ᵉ* ∘* apn k (f (n +' k)) }, { intro k, apply to_homotopy, exact sorry }}, { intro n, exact sorry } end /- Tensor by spaces -/ /- Smash product of spectra -/ /- Cofibers and stability -/ end spectrum
00820389a8d001de33b7d90c2ed63e54f2599dab
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/order/filter/at_top_bot.lean
c22e04c66b6a54128d22a1e4294b0a735d727bed
[ "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
61,939
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, Jeremy Avigad, Yury Kudryashov, Patrick Massot -/ import order.filter.bases import data.finset.preimage /-! # `at_top` and `at_bot` filters on preorded sets, monoids and groups. In this file we define the filters * `at_top`: corresponds to `n → +∞`; * `at_bot`: corresponds to `n → -∞`. Then we prove many lemmas like “if `f → +∞`, then `f ± c → +∞`”. -/ variables {ι ι' α β γ : Type*} open set open_locale classical filter big_operators namespace filter /-- `at_top` is the filter representing the limit `→ ∞` on an ordered set. It is generated by the collection of up-sets `{b | a ≤ b}`. (The preorder need not have a top element for this to be well defined, and indeed is trivial when a top element exists.) -/ def at_top [preorder α] : filter α := ⨅ a, 𝓟 (Ici a) /-- `at_bot` is the filter representing the limit `→ -∞` on an ordered set. It is generated by the collection of down-sets `{b | b ≤ a}`. (The preorder need not have a bottom element for this to be well defined, and indeed is trivial when a bottom element exists.) -/ def at_bot [preorder α] : filter α := ⨅ a, 𝓟 (Iic a) lemma mem_at_top [preorder α] (a : α) : {b : α | a ≤ b} ∈ @at_top α _ := mem_infi_sets a $ subset.refl _ lemma Ioi_mem_at_top [preorder α] [no_top_order α] (x : α) : Ioi x ∈ (at_top : filter α) := let ⟨z, hz⟩ := no_top x in mem_sets_of_superset (mem_at_top z) $ λ y h, lt_of_lt_of_le hz h lemma mem_at_bot [preorder α] (a : α) : {b : α | b ≤ a} ∈ @at_bot α _ := mem_infi_sets a $ subset.refl _ lemma Iio_mem_at_bot [preorder α] [no_bot_order α] (x : α) : Iio x ∈ (at_bot : filter α) := let ⟨z, hz⟩ := no_bot x in mem_sets_of_superset (mem_at_bot z) $ λ y h, lt_of_le_of_lt h hz lemma at_top_basis [nonempty α] [semilattice_sup α] : (@at_top α _).has_basis (λ _, true) Ici := has_basis_infi_principal (directed_of_sup $ λ a b, Ici_subset_Ici.2) lemma at_top_basis' [semilattice_sup α] (a : α) : (@at_top α _).has_basis (λ x, a ≤ x) Ici := ⟨λ t, (@at_top_basis α ⟨a⟩ _).mem_iff.trans ⟨λ ⟨x, _, hx⟩, ⟨x ⊔ a, le_sup_right, λ y hy, hx (le_trans le_sup_left hy)⟩, λ ⟨x, _, hx⟩, ⟨x, trivial, hx⟩⟩⟩ lemma at_bot_basis [nonempty α] [semilattice_inf α] : (@at_bot α _).has_basis (λ _, true) Iic := @at_top_basis (order_dual α) _ _ lemma at_bot_basis' [semilattice_inf α] (a : α) : (@at_bot α _).has_basis (λ x, x ≤ a) Iic := @at_top_basis' (order_dual α) _ _ @[instance] lemma at_top_ne_bot [nonempty α] [semilattice_sup α] : ne_bot (at_top : filter α) := at_top_basis.ne_bot_iff.2 $ λ a _, nonempty_Ici @[instance] lemma at_bot_ne_bot [nonempty α] [semilattice_inf α] : ne_bot (at_bot : filter α) := @at_top_ne_bot (order_dual α) _ _ @[simp] lemma mem_at_top_sets [nonempty α] [semilattice_sup α] {s : set α} : s ∈ (at_top : filter α) ↔ ∃a:α, ∀b≥a, b ∈ s := at_top_basis.mem_iff.trans $ exists_congr $ λ _, exists_const _ @[simp] lemma mem_at_bot_sets [nonempty α] [semilattice_inf α] {s : set α} : s ∈ (at_bot : filter α) ↔ ∃a:α, ∀b≤a, b ∈ s := @mem_at_top_sets (order_dual α) _ _ _ @[simp] lemma eventually_at_top [semilattice_sup α] [nonempty α] {p : α → Prop} : (∀ᶠ x in at_top, p x) ↔ (∃ a, ∀ b ≥ a, p b) := mem_at_top_sets @[simp] lemma eventually_at_bot [semilattice_inf α] [nonempty α] {p : α → Prop} : (∀ᶠ x in at_bot, p x) ↔ (∃ a, ∀ b ≤ a, p b) := mem_at_bot_sets lemma eventually_ge_at_top [preorder α] (a : α) : ∀ᶠ x in at_top, a ≤ x := mem_at_top a lemma eventually_le_at_bot [preorder α] (a : α) : ∀ᶠ x in at_bot, x ≤ a := mem_at_bot a lemma eventually_gt_at_top [preorder α] [no_top_order α] (a : α) : ∀ᶠ x in at_top, a < x := Ioi_mem_at_top a lemma eventually_lt_at_bot [preorder α] [no_bot_order α] (a : α) : ∀ᶠ x in at_bot, x < a := Iio_mem_at_bot a lemma at_top_basis_Ioi [nonempty α] [semilattice_sup α] [no_top_order α] : (@at_top α _).has_basis (λ _, true) Ioi := at_top_basis.to_has_basis (λ a ha, ⟨a, ha, Ioi_subset_Ici_self⟩) $ λ a ha, (no_top a).imp $ λ b hb, ⟨ha, Ici_subset_Ioi.2 hb⟩ lemma at_top_countable_basis [nonempty α] [semilattice_sup α] [encodable α] : has_countable_basis (at_top : filter α) (λ _, true) Ici := { countable := countable_encodable _, .. at_top_basis } lemma at_bot_countable_basis [nonempty α] [semilattice_inf α] [encodable α] : has_countable_basis (at_bot : filter α) (λ _, true) Iic := { countable := countable_encodable _, .. at_bot_basis } lemma is_countably_generated_at_top [nonempty α] [semilattice_sup α] [encodable α] : (at_top : filter $ α).is_countably_generated := at_top_countable_basis.is_countably_generated lemma is_countably_generated_at_bot [nonempty α] [semilattice_inf α] [encodable α] : (at_bot : filter $ α).is_countably_generated := at_bot_countable_basis.is_countably_generated lemma order_top.at_top_eq (α) [order_top α] : (at_top : filter α) = pure ⊤ := le_antisymm (le_pure_iff.2 $ (eventually_ge_at_top ⊤).mono $ λ b, top_unique) (le_infi $ λ b, le_principal_iff.2 le_top) lemma order_bot.at_bot_eq (α) [order_bot α] : (at_bot : filter α) = pure ⊥ := @order_top.at_top_eq (order_dual α) _ @[nontriviality] lemma subsingleton.at_top_eq (α) [subsingleton α] [preorder α] : (at_top : filter α) = ⊤ := begin refine top_unique (λ s hs x, _), letI : unique α := ⟨⟨x⟩, λ y, subsingleton.elim y x⟩, rw [at_top, infi_unique, unique.default_eq x, mem_principal_sets] at hs, exact hs left_mem_Ici end @[nontriviality] lemma subsingleton.at_bot_eq (α) [subsingleton α] [preorder α] : (at_bot : filter α) = ⊤ := subsingleton.at_top_eq (order_dual α) lemma tendsto_at_top_pure [order_top α] (f : α → β) : tendsto f at_top (pure $ f ⊤) := (order_top.at_top_eq α).symm ▸ tendsto_pure_pure _ _ lemma tendsto_at_bot_pure [order_bot α] (f : α → β) : tendsto f at_bot (pure $ f ⊥) := @tendsto_at_top_pure (order_dual α) _ _ _ lemma eventually.exists_forall_of_at_top [semilattice_sup α] [nonempty α] {p : α → Prop} (h : ∀ᶠ x in at_top, p x) : ∃ a, ∀ b ≥ a, p b := eventually_at_top.mp h lemma eventually.exists_forall_of_at_bot [semilattice_inf α] [nonempty α] {p : α → Prop} (h : ∀ᶠ x in at_bot, p x) : ∃ a, ∀ b ≤ a, p b := eventually_at_bot.mp h lemma frequently_at_top [semilattice_sup α] [nonempty α] {p : α → Prop} : (∃ᶠ x in at_top, p x) ↔ (∀ a, ∃ b ≥ a, p b) := by simp [at_top_basis.frequently_iff] lemma frequently_at_bot [semilattice_inf α] [nonempty α] {p : α → Prop} : (∃ᶠ x in at_bot, p x) ↔ (∀ a, ∃ b ≤ a, p b) := @frequently_at_top (order_dual α) _ _ _ lemma frequently_at_top' [semilattice_sup α] [nonempty α] [no_top_order α] {p : α → Prop} : (∃ᶠ x in at_top, p x) ↔ (∀ a, ∃ b > a, p b) := by simp [at_top_basis_Ioi.frequently_iff] lemma frequently_at_bot' [semilattice_inf α] [nonempty α] [no_bot_order α] {p : α → Prop} : (∃ᶠ x in at_bot, p x) ↔ (∀ a, ∃ b < a, p b) := @frequently_at_top' (order_dual α) _ _ _ _ lemma frequently.forall_exists_of_at_top [semilattice_sup α] [nonempty α] {p : α → Prop} (h : ∃ᶠ x in at_top, p x) : ∀ a, ∃ b ≥ a, p b := frequently_at_top.mp h lemma frequently.forall_exists_of_at_bot [semilattice_inf α] [nonempty α] {p : α → Prop} (h : ∃ᶠ x in at_bot, p x) : ∀ a, ∃ b ≤ a, p b := frequently_at_bot.mp h lemma map_at_top_eq [nonempty α] [semilattice_sup α] {f : α → β} : at_top.map f = (⨅a, 𝓟 $ f '' {a' | a ≤ a'}) := (at_top_basis.map _).eq_infi lemma map_at_bot_eq [nonempty α] [semilattice_inf α] {f : α → β} : at_bot.map f = (⨅a, 𝓟 $ f '' {a' | a' ≤ a}) := @map_at_top_eq (order_dual α) _ _ _ _ lemma tendsto_at_top [preorder β] {m : α → β} {f : filter α} : tendsto m f at_top ↔ (∀b, ∀ᶠ a in f, b ≤ m a) := by simp only [at_top, tendsto_infi, tendsto_principal, mem_Ici] lemma tendsto_at_bot [preorder β] {m : α → β} {f : filter α} : tendsto m f at_bot ↔ (∀b, ∀ᶠ a in f, m a ≤ b) := @tendsto_at_top α (order_dual β) _ m f lemma tendsto_at_top_mono' [preorder β] (l : filter α) ⦃f₁ f₂ : α → β⦄ (h : f₁ ≤ᶠ[l] f₂) : tendsto f₁ l at_top → tendsto f₂ l at_top := assume h₁, tendsto_at_top.2 $ λ b, mp_sets (tendsto_at_top.1 h₁ b) (monotone_mem_sets (λ a ha ha₁, le_trans ha₁ ha) h) lemma tendsto_at_bot_mono' [preorder β] (l : filter α) ⦃f₁ f₂ : α → β⦄ (h : f₁ ≤ᶠ[l] f₂) : tendsto f₂ l at_bot → tendsto f₁ l at_bot := @tendsto_at_top_mono' _ (order_dual β) _ _ _ _ h lemma tendsto_at_top_mono [preorder β] {l : filter α} {f g : α → β} (h : ∀ n, f n ≤ g n) : tendsto f l at_top → tendsto g l at_top := tendsto_at_top_mono' l $ eventually_of_forall h lemma tendsto_at_bot_mono [preorder β] {l : filter α} {f g : α → β} (h : ∀ n, f n ≤ g n) : tendsto g l at_bot → tendsto f l at_bot := @tendsto_at_top_mono _ (order_dual β) _ _ _ _ h /-! ### Sequences -/ lemma inf_map_at_top_ne_bot_iff [semilattice_sup α] [nonempty α] {F : filter β} {u : α → β} : ne_bot (F ⊓ (map u at_top)) ↔ ∀ U ∈ F, ∀ N, ∃ n ≥ N, u n ∈ U := by simp_rw [inf_ne_bot_iff_frequently_left, frequently_map, frequently_at_top]; refl lemma inf_map_at_bot_ne_bot_iff [semilattice_inf α] [nonempty α] {F : filter β} {u : α → β} : ne_bot (F ⊓ (map u at_bot)) ↔ ∀ U ∈ F, ∀ N, ∃ n ≤ N, u n ∈ U := @inf_map_at_top_ne_bot_iff (order_dual α) _ _ _ _ _ lemma extraction_of_frequently_at_top' {P : ℕ → Prop} (h : ∀ N, ∃ n > N, P n) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, P (φ n) := begin choose u hu using h, cases forall_and_distrib.mp hu with hu hu', exact ⟨u ∘ (nat.rec 0 (λ n v, u v)), strict_mono.nat (λ n, hu _), λ n, hu' _⟩, end lemma extraction_of_frequently_at_top {P : ℕ → Prop} (h : ∃ᶠ n in at_top, P n) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, P (φ n) := begin rw frequently_at_top' at h, exact extraction_of_frequently_at_top' h, end lemma extraction_of_eventually_at_top {P : ℕ → Prop} (h : ∀ᶠ n in at_top, P n) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, P (φ n) := extraction_of_frequently_at_top h.frequently lemma extraction_forall_of_frequently {P : ℕ → ℕ → Prop} (h : ∀ n, ∃ᶠ k in at_top, P n k) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, P n (φ n) := begin simp only [frequently_at_top'] at h, choose u hu hu' using h, use (λ n, nat.rec_on n (u 0 0) (λ n v, u (n+1) v) : ℕ → ℕ), split, { apply strict_mono.nat, intro n, apply hu }, { intros n, cases n ; simp [hu'] }, end lemma extraction_forall_of_eventually {P : ℕ → ℕ → Prop} (h : ∀ n, ∀ᶠ k in at_top, P n k) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, P n (φ n) := extraction_forall_of_frequently (λ n, (h n).frequently) lemma extraction_forall_of_eventually' {P : ℕ → ℕ → Prop} (h : ∀ n, ∃ N, ∀ k ≥ N, P n k) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, P n (φ n) := extraction_forall_of_eventually (by simp [eventually_at_top, h]) lemma exists_le_of_tendsto_at_top [semilattice_sup α] [preorder β] {u : α → β} (h : tendsto u at_top at_top) (a : α) (b : β) : ∃ a' ≥ a, b ≤ u a' := begin have : ∀ᶠ x in at_top, a ≤ x ∧ b ≤ u x := (eventually_ge_at_top a).and (h.eventually $ eventually_ge_at_top b), haveI : nonempty α := ⟨a⟩, rcases this.exists with ⟨a', ha, hb⟩, exact ⟨a', ha, hb⟩ end @[nolint ge_or_gt] -- see Note [nolint_ge] lemma exists_le_of_tendsto_at_bot [semilattice_sup α] [preorder β] {u : α → β} (h : tendsto u at_top at_bot) : ∀ a b, ∃ a' ≥ a, u a' ≤ b := @exists_le_of_tendsto_at_top _ (order_dual β) _ _ _ h lemma exists_lt_of_tendsto_at_top [semilattice_sup α] [preorder β] [no_top_order β] {u : α → β} (h : tendsto u at_top at_top) (a : α) (b : β) : ∃ a' ≥ a, b < u a' := begin cases no_top b with b' hb', rcases exists_le_of_tendsto_at_top h a b' with ⟨a', ha', ha''⟩, exact ⟨a', ha', lt_of_lt_of_le hb' ha''⟩ end @[nolint ge_or_gt] -- see Note [nolint_ge] lemma exists_lt_of_tendsto_at_bot [semilattice_sup α] [preorder β] [no_bot_order β] {u : α → β} (h : tendsto u at_top at_bot) : ∀ a b, ∃ a' ≥ a, u a' < b := @exists_lt_of_tendsto_at_top _ (order_dual β) _ _ _ _ h /-- If `u` is a sequence which is unbounded above, then after any point, it reaches a value strictly greater than all previous values. -/ lemma high_scores [linear_order β] [no_top_order β] {u : ℕ → β} (hu : tendsto u at_top at_top) : ∀ N, ∃ n ≥ N, ∀ k < n, u k < u n := begin intros N, let A := finset.image u (finset.range $ N+1), -- A = {u 0, ..., u N} have Ane : A.nonempty, from ⟨u 0, finset.mem_image_of_mem _ (finset.mem_range.mpr $ nat.zero_lt_succ _)⟩, let M := finset.max' A Ane, have ex : ∃ n ≥ N, M < u n, from exists_lt_of_tendsto_at_top hu _ _, obtain ⟨n, hnN, hnM, hn_min⟩ : ∃ n, N ≤ n ∧ M < u n ∧ ∀ k, N ≤ k → k < n → u k ≤ M, { use nat.find ex, rw ← and_assoc, split, { simpa using nat.find_spec ex }, { intros k hk hk', simpa [hk] using nat.find_min ex hk' } }, use [n, hnN], intros k hk, by_cases H : k ≤ N, { have : u k ∈ A, from finset.mem_image_of_mem _ (finset.mem_range.mpr $ nat.lt_succ_of_le H), have : u k ≤ M, from finset.le_max' A (u k) this, exact lt_of_le_of_lt this hnM }, { push_neg at H, calc u k ≤ M : hn_min k (le_of_lt H) hk ... < u n : hnM }, end /-- If `u` is a sequence which is unbounded below, then after any point, it reaches a value strictly smaller than all previous values. -/ @[nolint ge_or_gt] -- see Note [nolint_ge] lemma low_scores [linear_order β] [no_bot_order β] {u : ℕ → β} (hu : tendsto u at_top at_bot) : ∀ N, ∃ n ≥ N, ∀ k < n, u n < u k := @high_scores (order_dual β) _ _ _ hu /-- If `u` is a sequence which is unbounded above, then it `frequently` reaches a value strictly greater than all previous values. -/ lemma frequently_high_scores [linear_order β] [no_top_order β] {u : ℕ → β} (hu : tendsto u at_top at_top) : ∃ᶠ n in at_top, ∀ k < n, u k < u n := by simpa [frequently_at_top] using high_scores hu /-- If `u` is a sequence which is unbounded below, then it `frequently` reaches a value strictly smaller than all previous values. -/ lemma frequently_low_scores [linear_order β] [no_bot_order β] {u : ℕ → β} (hu : tendsto u at_top at_bot) : ∃ᶠ n in at_top, ∀ k < n, u n < u k := @frequently_high_scores (order_dual β) _ _ _ hu lemma strict_mono_subseq_of_tendsto_at_top {β : Type*} [linear_order β] [no_top_order β] {u : ℕ → β} (hu : tendsto u at_top at_top) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ strict_mono (u ∘ φ) := let ⟨φ, h, h'⟩ := extraction_of_frequently_at_top (frequently_high_scores hu) in ⟨φ, h, λ n m hnm, h' m _ (h hnm)⟩ lemma strict_mono_subseq_of_id_le {u : ℕ → ℕ} (hu : ∀ n, n ≤ u n) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ strict_mono (u ∘ φ) := strict_mono_subseq_of_tendsto_at_top (tendsto_at_top_mono hu tendsto_id) lemma strict_mono_tendsto_at_top {φ : ℕ → ℕ} (h : strict_mono φ) : tendsto φ at_top at_top := tendsto_at_top_mono h.id_le tendsto_id section ordered_add_comm_monoid variables [ordered_add_comm_monoid β] {l : filter α} {f g : α → β} lemma tendsto_at_top_add_nonneg_left' (hf : ∀ᶠ x in l, 0 ≤ f x) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_mono' l (hf.mono (λ x, le_add_of_nonneg_left)) hg lemma tendsto_at_bot_add_nonpos_left' (hf : ∀ᶠ x in l, f x ≤ 0) (hg : tendsto g l at_bot) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_nonneg_left' _ (order_dual β) _ _ _ _ hf hg lemma tendsto_at_top_add_nonneg_left (hf : ∀ x, 0 ≤ f x) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_nonneg_left' (eventually_of_forall hf) hg lemma tendsto_at_bot_add_nonpos_left (hf : ∀ x, f x ≤ 0) (hg : tendsto g l at_bot) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_nonneg_left _ (order_dual β) _ _ _ _ hf hg lemma tendsto_at_top_add_nonneg_right' (hf : tendsto f l at_top) (hg : ∀ᶠ x in l, 0 ≤ g x) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_mono' l (monotone_mem_sets (λ x, le_add_of_nonneg_right) hg) hf lemma tendsto_at_bot_add_nonpos_right' (hf : tendsto f l at_bot) (hg : ∀ᶠ x in l, g x ≤ 0) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_nonneg_right' _ (order_dual β) _ _ _ _ hf hg lemma tendsto_at_top_add_nonneg_right (hf : tendsto f l at_top) (hg : ∀ x, 0 ≤ g x) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_nonneg_right' hf (eventually_of_forall hg) lemma tendsto_at_bot_add_nonpos_right (hf : tendsto f l at_bot) (hg : ∀ x, g x ≤ 0) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_nonneg_right _ (order_dual β) _ _ _ _ hf hg lemma tendsto_at_top_add (hf : tendsto f l at_top) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_nonneg_left' (tendsto_at_top.mp hf 0) hg lemma tendsto_at_bot_add (hf : tendsto f l at_bot) (hg : tendsto g l at_bot) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add _ (order_dual β) _ _ _ _ hf hg lemma tendsto.nsmul_at_top (hf : tendsto f l at_top) {n : ℕ} (hn : 0 < n) : tendsto (λ x, n • f x) l at_top := tendsto_at_top.2 $ λ y, (tendsto_at_top.1 hf y).mp $ (tendsto_at_top.1 hf 0).mono $ λ x h₀ hy, calc y ≤ f x : hy ... = 1 • f x : (one_nsmul _).symm ... ≤ n • f x : nsmul_le_nsmul h₀ hn lemma tendsto.nsmul_at_bot (hf : tendsto f l at_bot) {n : ℕ} (hn : 0 < n) : tendsto (λ x, n • f x) l at_bot := @tendsto.nsmul_at_top α (order_dual β) _ l f hf n hn lemma tendsto_bit0_at_top : tendsto bit0 (at_top : filter β) at_top := tendsto_at_top_add tendsto_id tendsto_id lemma tendsto_bit0_at_bot : tendsto bit0 (at_bot : filter β) at_bot := tendsto_at_bot_add tendsto_id tendsto_id end ordered_add_comm_monoid section ordered_cancel_add_comm_monoid variables [ordered_cancel_add_comm_monoid β] {l : filter α} {f g : α → β} lemma tendsto_at_top_of_add_const_left (C : β) (hf : tendsto (λ x, C + f x) l at_top) : tendsto f l at_top := tendsto_at_top.2 $ assume b, (tendsto_at_top.1 hf (C + b)).mono (λ x, le_of_add_le_add_left) lemma tendsto_at_bot_of_add_const_left (C : β) (hf : tendsto (λ x, C + f x) l at_bot) : tendsto f l at_bot := @tendsto_at_top_of_add_const_left _ (order_dual β) _ _ _ C hf lemma tendsto_at_top_of_add_const_right (C : β) (hf : tendsto (λ x, f x + C) l at_top) : tendsto f l at_top := tendsto_at_top.2 $ assume b, (tendsto_at_top.1 hf (b + C)).mono (λ x, le_of_add_le_add_right) lemma tendsto_at_bot_of_add_const_right (C : β) (hf : tendsto (λ x, f x + C) l at_bot) : tendsto f l at_bot := @tendsto_at_top_of_add_const_right _ (order_dual β) _ _ _ C hf lemma tendsto_at_top_of_add_bdd_above_left' (C) (hC : ∀ᶠ x in l, f x ≤ C) (h : tendsto (λ x, f x + g x) l at_top) : tendsto g l at_top := tendsto_at_top_of_add_const_left C (tendsto_at_top_mono' l (hC.mono (λ x hx, add_le_add_right hx (g x))) h) lemma tendsto_at_bot_of_add_bdd_below_left' (C) (hC : ∀ᶠ x in l, C ≤ f x) (h : tendsto (λ x, f x + g x) l at_bot) : tendsto g l at_bot := @tendsto_at_top_of_add_bdd_above_left' _ (order_dual β) _ _ _ _ C hC h lemma tendsto_at_top_of_add_bdd_above_left (C) (hC : ∀ x, f x ≤ C) : tendsto (λ x, f x + g x) l at_top → tendsto g l at_top := tendsto_at_top_of_add_bdd_above_left' C (univ_mem_sets' hC) lemma tendsto_at_bot_of_add_bdd_below_left (C) (hC : ∀ x, C ≤ f x) : tendsto (λ x, f x + g x) l at_bot → tendsto g l at_bot := @tendsto_at_top_of_add_bdd_above_left _ (order_dual β) _ _ _ _ C hC lemma tendsto_at_top_of_add_bdd_above_right' (C) (hC : ∀ᶠ x in l, g x ≤ C) (h : tendsto (λ x, f x + g x) l at_top) : tendsto f l at_top := tendsto_at_top_of_add_const_right C (tendsto_at_top_mono' l (hC.mono (λ x hx, add_le_add_left hx (f x))) h) lemma tendsto_at_bot_of_add_bdd_below_right' (C) (hC : ∀ᶠ x in l, C ≤ g x) (h : tendsto (λ x, f x + g x) l at_bot) : tendsto f l at_bot := @tendsto_at_top_of_add_bdd_above_right' _ (order_dual β) _ _ _ _ C hC h lemma tendsto_at_top_of_add_bdd_above_right (C) (hC : ∀ x, g x ≤ C) : tendsto (λ x, f x + g x) l at_top → tendsto f l at_top := tendsto_at_top_of_add_bdd_above_right' C (univ_mem_sets' hC) lemma tendsto_at_bot_of_add_bdd_below_right (C) (hC : ∀ x, C ≤ g x) : tendsto (λ x, f x + g x) l at_bot → tendsto f l at_bot := @tendsto_at_top_of_add_bdd_above_right _ (order_dual β) _ _ _ _ C hC end ordered_cancel_add_comm_monoid section ordered_group variables [ordered_add_comm_group β] (l : filter α) {f g : α → β} lemma tendsto_at_top_add_left_of_le' (C : β) (hf : ∀ᶠ x in l, C ≤ f x) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := @tendsto_at_top_of_add_bdd_above_left' _ _ _ l (λ x, -(f x)) (λ x, f x + g x) (-C) (by simpa) (by simpa) lemma tendsto_at_bot_add_left_of_ge' (C : β) (hf : ∀ᶠ x in l, f x ≤ C) (hg : tendsto g l at_bot) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_left_of_le' _ (order_dual β) _ _ _ _ C hf hg lemma tendsto_at_top_add_left_of_le (C : β) (hf : ∀ x, C ≤ f x) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_left_of_le' l C (univ_mem_sets' hf) hg lemma tendsto_at_bot_add_left_of_ge (C : β) (hf : ∀ x, f x ≤ C) (hg : tendsto g l at_bot) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_left_of_le _ (order_dual β) _ _ _ _ C hf hg lemma tendsto_at_top_add_right_of_le' (C : β) (hf : tendsto f l at_top) (hg : ∀ᶠ x in l, C ≤ g x) : tendsto (λ x, f x + g x) l at_top := @tendsto_at_top_of_add_bdd_above_right' _ _ _ l (λ x, f x + g x) (λ x, -(g x)) (-C) (by simp [hg]) (by simp [hf]) lemma tendsto_at_bot_add_right_of_ge' (C : β) (hf : tendsto f l at_bot) (hg : ∀ᶠ x in l, g x ≤ C) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_right_of_le' _ (order_dual β) _ _ _ _ C hf hg lemma tendsto_at_top_add_right_of_le (C : β) (hf : tendsto f l at_top) (hg : ∀ x, C ≤ g x) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_right_of_le' l C hf (univ_mem_sets' hg) lemma tendsto_at_bot_add_right_of_ge (C : β) (hf : tendsto f l at_bot) (hg : ∀ x, g x ≤ C) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_right_of_le _ (order_dual β) _ _ _ _ C hf hg lemma tendsto_at_top_add_const_left (C : β) (hf : tendsto f l at_top) : tendsto (λ x, C + f x) l at_top := tendsto_at_top_add_left_of_le' l C (univ_mem_sets' $ λ _, le_refl C) hf lemma tendsto_at_bot_add_const_left (C : β) (hf : tendsto f l at_bot) : tendsto (λ x, C + f x) l at_bot := @tendsto_at_top_add_const_left _ (order_dual β) _ _ _ C hf lemma tendsto_at_top_add_const_right (C : β) (hf : tendsto f l at_top) : tendsto (λ x, f x + C) l at_top := tendsto_at_top_add_right_of_le' l C hf (univ_mem_sets' $ λ _, le_refl C) lemma tendsto_at_bot_add_const_right (C : β) (hf : tendsto f l at_bot) : tendsto (λ x, f x + C) l at_bot := @tendsto_at_top_add_const_right _ (order_dual β) _ _ _ C hf lemma tendsto_neg_at_top_at_bot : tendsto (has_neg.neg : β → β) at_top at_bot := begin simp only [tendsto_at_bot, neg_le], exact λ b, eventually_ge_at_top _ end lemma tendsto_neg_at_bot_at_top : tendsto (has_neg.neg : β → β) at_bot at_top := @tendsto_neg_at_top_at_bot (order_dual β) _ end ordered_group section ordered_semiring variables [ordered_semiring α] {l : filter β} {f g : β → α} lemma tendsto_bit1_at_top : tendsto bit1 (at_top : filter α) at_top := tendsto_at_top_add_nonneg_right tendsto_bit0_at_top (λ _, zero_le_one) lemma tendsto.at_top_mul_at_top (hf : tendsto f l at_top) (hg : tendsto g l at_top) : tendsto (λ x, f x * g x) l at_top := begin refine tendsto_at_top_mono' _ _ hg, filter_upwards [hg.eventually (eventually_ge_at_top 0), hf.eventually (eventually_ge_at_top 1)], exact λ x, le_mul_of_one_le_left end lemma tendsto_mul_self_at_top : tendsto (λ x : α, x * x) at_top at_top := tendsto_id.at_top_mul_at_top tendsto_id /-- The monomial function `x^n` tends to `+∞` at `+∞` for any positive natural `n`. A version for positive real powers exists as `tendsto_rpow_at_top`. -/ lemma tendsto_pow_at_top {n : ℕ} (hn : 1 ≤ n) : tendsto (λ x : α, x ^ n) at_top at_top := begin refine tendsto_at_top_mono' _ ((eventually_ge_at_top 1).mono $ λ x hx, _) tendsto_id, simpa only [pow_one] using pow_le_pow hx hn end end ordered_semiring lemma zero_pow_eventually_eq [monoid_with_zero α] : (λ n : ℕ, (0 : α) ^ n) =ᶠ[at_top] (λ n, 0) := eventually_at_top.2 ⟨1, λ n hn, zero_pow (zero_lt_one.trans_le hn)⟩ section ordered_ring variables [ordered_ring α] {l : filter β} {f g : β → α} lemma tendsto.at_top_mul_at_bot (hf : tendsto f l at_top) (hg : tendsto g l at_bot) : tendsto (λ x, f x * g x) l at_bot := have _ := (hf.at_top_mul_at_top $ tendsto_neg_at_bot_at_top.comp hg), by simpa only [(∘), neg_mul_eq_mul_neg, neg_neg] using tendsto_neg_at_top_at_bot.comp this lemma tendsto.at_bot_mul_at_top (hf : tendsto f l at_bot) (hg : tendsto g l at_top) : tendsto (λ x, f x * g x) l at_bot := have tendsto (λ x, (-f x) * g x) l at_top := ( (tendsto_neg_at_bot_at_top.comp hf).at_top_mul_at_top hg), by simpa only [(∘), neg_mul_eq_neg_mul, neg_neg] using tendsto_neg_at_top_at_bot.comp this lemma tendsto.at_bot_mul_at_bot (hf : tendsto f l at_bot) (hg : tendsto g l at_bot) : tendsto (λ x, f x * g x) l at_top := have tendsto (λ x, (-f x) * (-g x)) l at_top := (tendsto_neg_at_bot_at_top.comp hf).at_top_mul_at_top (tendsto_neg_at_bot_at_top.comp hg), by simpa only [neg_mul_neg] using this end ordered_ring section linear_ordered_add_comm_group variables [linear_ordered_add_comm_group α] /-- $\lim_{x\to+\infty}|x|=+\infty$ -/ lemma tendsto_abs_at_top_at_top : tendsto (abs : α → α) at_top at_top := tendsto_at_top_mono le_abs_self tendsto_id /-- $\lim_{x\to-\infty}|x|=+\infty$ -/ lemma tendsto_abs_at_bot_at_top : tendsto (abs : α → α) at_bot at_top := tendsto_at_top_mono neg_le_abs_self tendsto_neg_at_bot_at_top end linear_ordered_add_comm_group section linear_ordered_semiring variables [linear_ordered_semiring α] {l : filter β} {f : β → α} lemma tendsto.at_top_of_const_mul {c : α} (hc : 0 < c) (hf : tendsto (λ x, c * f x) l at_top) : tendsto f l at_top := tendsto_at_top.2 $ λ b, (tendsto_at_top.1 hf (c * b)).mono $ λ x hx, le_of_mul_le_mul_left hx hc lemma tendsto.at_top_of_mul_const {c : α} (hc : 0 < c) (hf : tendsto (λ x, f x * c) l at_top) : tendsto f l at_top := tendsto_at_top.2 $ λ b, (tendsto_at_top.1 hf (b * c)).mono $ λ x hx, le_of_mul_le_mul_right hx hc end linear_ordered_semiring lemma nonneg_of_eventually_pow_nonneg [linear_ordered_ring α] {a : α} (h : ∀ᶠ n in at_top, 0 ≤ a ^ (n : ℕ)) : 0 ≤ a := let ⟨n, hn⟩ := (tendsto_bit1_at_top.eventually h).exists in pow_bit1_nonneg_iff.1 hn section linear_ordered_field variables [linear_ordered_field α] {l : filter β} {f : β → α} {r : α} /-- If a function tends to infinity along a filter, then this function multiplied by a positive constant (on the left) also tends to infinity. For a version working in `ℕ` or `ℤ`, use `filter.tendsto.const_mul_at_top'` instead. -/ lemma tendsto.const_mul_at_top (hr : 0 < r) (hf : tendsto f l at_top) : tendsto (λx, r * f x) l at_top := tendsto.at_top_of_const_mul (inv_pos.2 hr) $ by simpa only [inv_mul_cancel_left' hr.ne'] /-- If a function tends to infinity along a filter, then this function multiplied by a positive constant (on the right) also tends to infinity. For a version working in `ℕ` or `ℤ`, use `filter.tendsto.at_top_mul_const'` instead. -/ lemma tendsto.at_top_mul_const (hr : 0 < r) (hf : tendsto f l at_top) : tendsto (λx, f x * r) l at_top := by simpa only [mul_comm] using hf.const_mul_at_top hr /-- If a function tends to infinity along a filter, then this function divided by a positive constant also tends to infinity. -/ lemma tendsto.at_top_div_const (hr : 0 < r) (hf : tendsto f l at_top) : tendsto (λx, f x / r) l at_top := by simpa only [div_eq_mul_inv] using hf.at_top_mul_const (inv_pos.2 hr) /-- If a function tends to infinity along a filter, then this function multiplied by a negative constant (on the left) tends to negative infinity. -/ lemma tendsto.neg_const_mul_at_top (hr : r < 0) (hf : tendsto f l at_top) : tendsto (λ x, r * f x) l at_bot := by simpa only [(∘), neg_mul_eq_neg_mul, neg_neg] using tendsto_neg_at_top_at_bot.comp (hf.const_mul_at_top (neg_pos.2 hr)) /-- If a function tends to infinity along a filter, then this function multiplied by a negative constant (on the right) tends to negative infinity. -/ lemma tendsto.at_top_mul_neg_const (hr : r < 0) (hf : tendsto f l at_top) : tendsto (λ x, f x * r) l at_bot := by simpa only [mul_comm] using hf.neg_const_mul_at_top hr /-- If a function tends to negative infinity along a filter, then this function multiplied by a positive constant (on the left) also tends to negative infinity. -/ lemma tendsto.const_mul_at_bot (hr : 0 < r) (hf : tendsto f l at_bot) : tendsto (λx, r * f x) l at_bot := by simpa only [(∘), neg_mul_eq_mul_neg, neg_neg] using tendsto_neg_at_top_at_bot.comp ((tendsto_neg_at_bot_at_top.comp hf).const_mul_at_top hr) /-- If a function tends to negative infinity along a filter, then this function multiplied by a positive constant (on the right) also tends to negative infinity. -/ lemma tendsto.at_bot_mul_const (hr : 0 < r) (hf : tendsto f l at_bot) : tendsto (λx, f x * r) l at_bot := by simpa only [mul_comm] using hf.const_mul_at_bot hr /-- If a function tends to negative infinity along a filter, then this function divided by a positive constant also tends to negative infinity. -/ lemma tendsto.at_bot_div_const (hr : 0 < r) (hf : tendsto f l at_bot) : tendsto (λx, f x / r) l at_bot := by simpa only [div_eq_mul_inv] using hf.at_bot_mul_const (inv_pos.2 hr) /-- If a function tends to negative infinity along a filter, then this function multiplied by a negative constant (on the left) tends to positive infinity. -/ lemma tendsto.neg_const_mul_at_bot (hr : r < 0) (hf : tendsto f l at_bot) : tendsto (λ x, r * f x) l at_top := by simpa only [(∘), neg_mul_eq_neg_mul, neg_neg] using tendsto_neg_at_bot_at_top.comp (hf.const_mul_at_bot (neg_pos.2 hr)) /-- If a function tends to negative infinity along a filter, then this function multiplied by a negative constant (on the right) tends to positive infinity. -/ lemma tendsto.at_bot_mul_neg_const (hr : r < 0) (hf : tendsto f l at_bot) : tendsto (λ x, f x * r) l at_top := by simpa only [mul_comm] using hf.neg_const_mul_at_bot hr lemma tendsto_const_mul_pow_at_top {c : α} {n : ℕ} (hn : 1 ≤ n) (hc : 0 < c) : tendsto (λ x, c * x^n) at_top at_top := tendsto.const_mul_at_top hc (tendsto_pow_at_top hn) lemma tendsto_const_mul_pow_at_top_iff (c : α) (n : ℕ) : tendsto (λ x, c * x^n) at_top at_top ↔ 1 ≤ n ∧ 0 < c := begin refine ⟨λ h, _, λ h, tendsto_const_mul_pow_at_top h.1 h.2⟩, simp only [tendsto_at_top, eventually_at_top] at h, have : 0 < c := let ⟨x, hx⟩ := h 1 in pos_of_mul_pos_right (lt_of_lt_of_le zero_lt_one (hx (max x 1) (le_max_left x 1))) (pow_nonneg (le_trans zero_le_one (le_max_right x 1)) n), refine ⟨nat.succ_le_iff.mp (lt_of_le_of_ne (zero_le n) (ne.symm (λ hn, _))), this⟩, obtain ⟨x, hx⟩ := h (c + 1), specialize hx x le_rfl, rw [hn, pow_zero, mul_one, add_le_iff_nonpos_right] at hx, exact absurd hx (not_le.mpr zero_lt_one), end lemma tendsto_neg_const_mul_pow_at_top {c : α} {n : ℕ} (hn : 1 ≤ n) (hc : c < 0) : tendsto (λ x, c * x^n) at_top at_bot := tendsto.neg_const_mul_at_top hc (tendsto_pow_at_top hn) lemma tendsto_neg_const_mul_pow_at_top_iff (c : α) (n : ℕ) : tendsto (λ x, c * x^n) at_top at_bot ↔ 1 ≤ n ∧ c < 0 := begin refine ⟨λ h, _, λ h, tendsto_neg_const_mul_pow_at_top h.1 h.2⟩, simp only [tendsto_at_bot, eventually_at_top] at h, have : c < 0 := let ⟨x, hx⟩ := h (-1) in neg_of_mul_neg_right (lt_of_le_of_lt (hx (max x 1) (le_max_left x 1)) (by simp [zero_lt_one])) (pow_nonneg (le_trans zero_le_one (le_max_right x 1)) n), refine ⟨nat.succ_le_iff.mp (lt_of_le_of_ne (zero_le n) (ne.symm (λ hn, _))), this⟩, obtain ⟨x, hx⟩ := h (c - 1), specialize hx x le_rfl, rw [hn, pow_zero, mul_one, le_sub, sub_self] at hx, exact absurd hx (not_le.mpr zero_lt_one), end end linear_ordered_field open_locale filter lemma tendsto_at_top' [nonempty α] [semilattice_sup α] {f : α → β} {l : filter β} : tendsto f at_top l ↔ (∀s ∈ l, ∃a, ∀b≥a, f b ∈ s) := by simp only [tendsto_def, mem_at_top_sets]; refl lemma tendsto_at_bot' [nonempty α] [semilattice_inf α] {f : α → β} {l : filter β} : tendsto f at_bot l ↔ (∀s ∈ l, ∃a, ∀b≤a, f b ∈ s) := @tendsto_at_top' (order_dual α) _ _ _ _ _ theorem tendsto_at_top_principal [nonempty β] [semilattice_sup β] {f : β → α} {s : set α} : tendsto f at_top (𝓟 s) ↔ ∃N, ∀n≥N, f n ∈ s := by rw [tendsto_iff_comap, comap_principal, le_principal_iff, mem_at_top_sets]; refl theorem tendsto_at_bot_principal [nonempty β] [semilattice_inf β] {f : β → α} {s : set α} : tendsto f at_bot (𝓟 s) ↔ ∃N, ∀n≤N, f n ∈ s := @tendsto_at_top_principal _ (order_dual β) _ _ _ _ /-- A function `f` grows to `+∞` independent of an order-preserving embedding `e`. -/ lemma tendsto_at_top_at_top [nonempty α] [semilattice_sup α] [preorder β] {f : α → β} : tendsto f at_top at_top ↔ ∀ b : β, ∃ i : α, ∀ a : α, i ≤ a → b ≤ f a := iff.trans tendsto_infi $ forall_congr $ assume b, tendsto_at_top_principal lemma tendsto_at_top_at_bot [nonempty α] [semilattice_sup α] [preorder β] {f : α → β} : tendsto f at_top at_bot ↔ ∀ (b : β), ∃ (i : α), ∀ (a : α), i ≤ a → f a ≤ b := @tendsto_at_top_at_top α (order_dual β) _ _ _ f lemma tendsto_at_bot_at_top [nonempty α] [semilattice_inf α] [preorder β] {f : α → β} : tendsto f at_bot at_top ↔ ∀ (b : β), ∃ (i : α), ∀ (a : α), a ≤ i → b ≤ f a := @tendsto_at_top_at_top (order_dual α) β _ _ _ f lemma tendsto_at_bot_at_bot [nonempty α] [semilattice_inf α] [preorder β] {f : α → β} : tendsto f at_bot at_bot ↔ ∀ (b : β), ∃ (i : α), ∀ (a : α), a ≤ i → f a ≤ b := @tendsto_at_top_at_top (order_dual α) (order_dual β) _ _ _ f lemma tendsto_at_top_at_top_of_monotone [preorder α] [preorder β] {f : α → β} (hf : monotone f) (h : ∀ b, ∃ a, b ≤ f a) : tendsto f at_top at_top := tendsto_infi.2 $ λ b, tendsto_principal.2 $ let ⟨a, ha⟩ := h b in mem_sets_of_superset (mem_at_top a) $ λ a' ha', le_trans ha (hf ha') lemma tendsto_at_bot_at_bot_of_monotone [preorder α] [preorder β] {f : α → β} (hf : monotone f) (h : ∀ b, ∃ a, f a ≤ b) : tendsto f at_bot at_bot := tendsto_infi.2 $ λ b, tendsto_principal.2 $ let ⟨a, ha⟩ := h b in mem_sets_of_superset (mem_at_bot a) $ λ a' ha', le_trans (hf ha') ha lemma tendsto_at_top_at_top_iff_of_monotone [nonempty α] [semilattice_sup α] [preorder β] {f : α → β} (hf : monotone f) : tendsto f at_top at_top ↔ ∀ b : β, ∃ a : α, b ≤ f a := tendsto_at_top_at_top.trans $ forall_congr $ λ b, exists_congr $ λ a, ⟨λ h, h a (le_refl a), λ h a' ha', le_trans h $ hf ha'⟩ lemma tendsto_at_bot_at_bot_iff_of_monotone [nonempty α] [semilattice_inf α] [preorder β] {f : α → β} (hf : monotone f) : tendsto f at_bot at_bot ↔ ∀ b : β, ∃ a : α, f a ≤ b := tendsto_at_bot_at_bot.trans $ forall_congr $ λ b, exists_congr $ λ a, ⟨λ h, h a (le_refl a), λ h a' ha', le_trans (hf ha') h⟩ alias tendsto_at_top_at_top_of_monotone ← monotone.tendsto_at_top_at_top alias tendsto_at_bot_at_bot_of_monotone ← monotone.tendsto_at_bot_at_bot alias tendsto_at_top_at_top_iff_of_monotone ← monotone.tendsto_at_top_at_top_iff alias tendsto_at_bot_at_bot_iff_of_monotone ← monotone.tendsto_at_bot_at_bot_iff lemma tendsto_at_top_embedding [preorder β] [preorder γ] {f : α → β} {e : β → γ} {l : filter α} (hm : ∀b₁ b₂, e b₁ ≤ e b₂ ↔ b₁ ≤ b₂) (hu : ∀c, ∃b, c ≤ e b) : tendsto (e ∘ f) l at_top ↔ tendsto f l at_top := begin refine ⟨_, (tendsto_at_top_at_top_of_monotone (λ b₁ b₂, (hm b₁ b₂).2) hu).comp⟩, rw [tendsto_at_top, tendsto_at_top], exact λ hc b, (hc (e b)).mono (λ a, (hm b (f a)).1) end /-- A function `f` goes to `-∞` independent of an order-preserving embedding `e`. -/ lemma tendsto_at_bot_embedding [preorder β] [preorder γ] {f : α → β} {e : β → γ} {l : filter α} (hm : ∀b₁ b₂, e b₁ ≤ e b₂ ↔ b₁ ≤ b₂) (hu : ∀c, ∃b, e b ≤ c) : tendsto (e ∘ f) l at_bot ↔ tendsto f l at_bot := @tendsto_at_top_embedding α (order_dual β) (order_dual γ) _ _ f e l (function.swap hm) hu lemma tendsto_finset_range : tendsto finset.range at_top at_top := finset.range_mono.tendsto_at_top_at_top finset.exists_nat_subset_range lemma at_top_finset_eq_infi : (at_top : filter $ finset α) = ⨅ x : α, 𝓟 (Ici {x}) := begin refine le_antisymm (le_infi (λ i, le_principal_iff.2 $ mem_at_top {i})) _, refine le_infi (λ s, le_principal_iff.2 $ mem_infi_iff.2 _), refine ⟨↑s, s.finite_to_set, _, λ i, mem_principal_self _, _⟩, simp only [subset_def, mem_Inter, set_coe.forall, mem_Ici, finset.le_iff_subset, finset.mem_singleton, finset.subset_iff, forall_eq], dsimp, exact λ t, id end /-- If `f` is a monotone sequence of `finset`s and each `x` belongs to one of `f n`, then `tendsto f at_top at_top`. -/ lemma tendsto_at_top_finset_of_monotone [preorder β] {f : β → finset α} (h : monotone f) (h' : ∀ x : α, ∃ n, x ∈ f n) : tendsto f at_top at_top := begin simp only [at_top_finset_eq_infi, tendsto_infi, tendsto_principal], intro a, rcases h' a with ⟨b, hb⟩, exact eventually.mono (mem_at_top b) (λ b' hb', le_trans (finset.singleton_subset_iff.2 hb) (h hb')), end alias tendsto_at_top_finset_of_monotone ← monotone.tendsto_at_top_finset lemma tendsto_finset_image_at_top_at_top {i : β → γ} {j : γ → β} (h : function.left_inverse j i) : tendsto (finset.image j) at_top at_top := (finset.image_mono j).tendsto_at_top_finset $ assume a, ⟨{i a}, by simp only [finset.image_singleton, h a, finset.mem_singleton]⟩ lemma tendsto_finset_preimage_at_top_at_top {f : α → β} (hf : function.injective f) : tendsto (λ s : finset β, s.preimage f (hf.inj_on _)) at_top at_top := (finset.monotone_preimage hf).tendsto_at_top_finset $ λ x, ⟨{f x}, finset.mem_preimage.2 $ finset.mem_singleton_self _⟩ lemma prod_at_top_at_top_eq {β₁ β₂ : Type*} [semilattice_sup β₁] [semilattice_sup β₂] : (at_top : filter β₁) ×ᶠ (at_top : filter β₂) = (at_top : filter (β₁ × β₂)) := begin by_cases ne : nonempty β₁ ∧ nonempty β₂, { cases ne, resetI, simp [at_top, prod_infi_left, prod_infi_right, infi_prod], exact infi_comm }, { rw not_and_distrib at ne, cases ne; { have : ¬ (nonempty (β₁ × β₂)), by simp [ne], rw [at_top.filter_eq_bot_of_not_nonempty ne, at_top.filter_eq_bot_of_not_nonempty this], simp only [bot_prod, prod_bot] } } end lemma prod_at_bot_at_bot_eq {β₁ β₂ : Type*} [semilattice_inf β₁] [semilattice_inf β₂] : (at_bot : filter β₁) ×ᶠ (at_bot : filter β₂) = (at_bot : filter (β₁ × β₂)) := @prod_at_top_at_top_eq (order_dual β₁) (order_dual β₂) _ _ lemma prod_map_at_top_eq {α₁ α₂ β₁ β₂ : Type*} [semilattice_sup β₁] [semilattice_sup β₂] (u₁ : β₁ → α₁) (u₂ : β₂ → α₂) : (map u₁ at_top) ×ᶠ (map u₂ at_top) = map (prod.map u₁ u₂) at_top := by rw [prod_map_map_eq, prod_at_top_at_top_eq, prod.map_def] lemma prod_map_at_bot_eq {α₁ α₂ β₁ β₂ : Type*} [semilattice_inf β₁] [semilattice_inf β₂] (u₁ : β₁ → α₁) (u₂ : β₂ → α₂) : (map u₁ at_bot) ×ᶠ (map u₂ at_bot) = map (prod.map u₁ u₂) at_bot := @prod_map_at_top_eq _ _ (order_dual β₁) (order_dual β₂) _ _ _ _ lemma tendsto.subseq_mem {F : filter α} {V : ℕ → set α} (h : ∀ n, V n ∈ F) {u : ℕ → α} (hu : tendsto u at_top F) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, u (φ n) ∈ V n := extraction_forall_of_eventually' (λ n, tendsto_at_top'.mp hu _ (h n) : ∀ n, ∃ N, ∀ k ≥ N, u k ∈ V n) lemma tendsto_at_bot_diagonal [semilattice_inf α] : tendsto (λ a : α, (a, a)) at_bot at_bot := by { rw ← prod_at_bot_at_bot_eq, exact tendsto_id.prod_mk tendsto_id } lemma tendsto_at_top_diagonal [semilattice_sup α] : tendsto (λ a : α, (a, a)) at_top at_top := by { rw ← prod_at_top_at_top_eq, exact tendsto_id.prod_mk tendsto_id } lemma tendsto.prod_map_prod_at_bot [semilattice_inf γ] {F : filter α} {G : filter β} {f : α → γ} {g : β → γ} (hf : tendsto f F at_bot) (hg : tendsto g G at_bot) : tendsto (prod.map f g) (F ×ᶠ G) at_bot := by { rw ← prod_at_bot_at_bot_eq, exact hf.prod_map hg, } lemma tendsto.prod_map_prod_at_top [semilattice_sup γ] {F : filter α} {G : filter β} {f : α → γ} {g : β → γ} (hf : tendsto f F at_top) (hg : tendsto g G at_top) : tendsto (prod.map f g) (F ×ᶠ G) at_top := by { rw ← prod_at_top_at_top_eq, exact hf.prod_map hg, } lemma tendsto.prod_at_bot [semilattice_inf α] [semilattice_inf γ] {f g : α → γ} (hf : tendsto f at_bot at_bot) (hg : tendsto g at_bot at_bot) : tendsto (prod.map f g) at_bot at_bot := by { rw ← prod_at_bot_at_bot_eq, exact hf.prod_map_prod_at_bot hg, } lemma tendsto.prod_at_top [semilattice_sup α] [semilattice_sup γ] {f g : α → γ} (hf : tendsto f at_top at_top) (hg : tendsto g at_top at_top) : tendsto (prod.map f g) at_top at_top := by { rw ← prod_at_top_at_top_eq, exact hf.prod_map_prod_at_top hg, } lemma eventually_at_bot_prod_self [semilattice_inf α] [nonempty α] {p : α × α → Prop} : (∀ᶠ x in at_bot, p x) ↔ (∃ a, ∀ k l, k ≤ a → l ≤ a → p (k, l)) := by simp [← prod_at_bot_at_bot_eq, at_bot_basis.prod_self.eventually_iff] lemma eventually_at_top_prod_self [semilattice_sup α] [nonempty α] {p : α × α → Prop} : (∀ᶠ x in at_top, p x) ↔ (∃ a, ∀ k l, a ≤ k → a ≤ l → p (k, l)) := by simp [← prod_at_top_at_top_eq, at_top_basis.prod_self.eventually_iff] lemma eventually_at_bot_prod_self' [semilattice_inf α] [nonempty α] {p : α × α → Prop} : (∀ᶠ x in at_bot, p x) ↔ (∃ a, ∀ k ≤ a, ∀ l ≤ a, p (k, l)) := begin rw filter.eventually_at_bot_prod_self, apply exists_congr, tauto, end lemma eventually_at_top_prod_self' [semilattice_sup α] [nonempty α] {p : α × α → Prop} : (∀ᶠ x in at_top, p x) ↔ (∃ a, ∀ k ≥ a, ∀ l ≥ a, p (k, l)) := begin rw filter.eventually_at_top_prod_self, apply exists_congr, tauto, end /-- A function `f` maps upwards closed sets (at_top sets) to upwards closed sets when it is a Galois insertion. The Galois "insertion" and "connection" is weakened to only require it to be an insertion and a connetion above `b'`. -/ lemma map_at_top_eq_of_gc [semilattice_sup α] [semilattice_sup β] {f : α → β} (g : β → α) (b' : β) (hf : monotone f) (gc : ∀a, ∀b≥b', f a ≤ b ↔ a ≤ g b) (hgi : ∀b≥b', b ≤ f (g b)) : map f at_top = at_top := begin refine le_antisymm (hf.tendsto_at_top_at_top $ λ b, ⟨g (b ⊔ b'), le_sup_left.trans $ hgi _ le_sup_right⟩) _, rw [@map_at_top_eq _ _ ⟨g b'⟩], refine le_infi (λ a, infi_le_of_le (f a ⊔ b') $ principal_mono.2 $ λ b hb, _), rw [mem_Ici, sup_le_iff] at hb, exact ⟨g b, (gc _ _ hb.2).1 hb.1, le_antisymm ((gc _ _ hb.2).2 (le_refl _)) (hgi _ hb.2)⟩ end lemma map_at_bot_eq_of_gc [semilattice_inf α] [semilattice_inf β] {f : α → β} (g : β → α) (b' : β) (hf : monotone f) (gc : ∀a, ∀b≤b', b ≤ f a ↔ g b ≤ a) (hgi : ∀b≤b', f (g b) ≤ b) : map f at_bot = at_bot := @map_at_top_eq_of_gc (order_dual α) (order_dual β) _ _ _ _ _ hf.order_dual gc hgi lemma map_coe_at_top_of_Ici_subset [semilattice_sup α] {a : α} {s : set α} (h : Ici a ⊆ s) : map (coe : s → α) at_top = at_top := begin have : directed (≥) (λ x : s, 𝓟 (Ici x)), { intros x y, use ⟨x ⊔ y ⊔ a, h le_sup_right⟩, simp only [ge_iff_le, principal_mono, Ici_subset_Ici, ← subtype.coe_le_coe, subtype.coe_mk], exact ⟨le_sup_left.trans le_sup_left, le_sup_right.trans le_sup_left⟩ }, haveI : nonempty s := ⟨⟨a, h le_rfl⟩⟩, simp only [le_antisymm_iff, at_top, le_infi_iff, le_principal_iff, mem_map, mem_set_of_eq, map_infi_eq this, map_principal], split, { intro x, refine mem_sets_of_superset (mem_infi_sets ⟨x ⊔ a, h le_sup_right⟩ (mem_principal_self _)) _, rintro _ ⟨y, hy, rfl⟩, exact le_trans le_sup_left (subtype.coe_le_coe.2 hy) }, { intro x, filter_upwards [mem_at_top (↑x ⊔ a)], intros b hb, exact ⟨⟨b, h $ le_sup_right.trans hb⟩, subtype.coe_le_coe.1 (le_sup_left.trans hb), rfl⟩ } end /-- The image of the filter `at_top` on `Ici a` under the coercion equals `at_top`. -/ @[simp] lemma map_coe_Ici_at_top [semilattice_sup α] (a : α) : map (coe : Ici a → α) at_top = at_top := map_coe_at_top_of_Ici_subset (subset.refl _) /-- The image of the filter `at_top` on `Ioi a` under the coercion equals `at_top`. -/ @[simp] lemma map_coe_Ioi_at_top [semilattice_sup α] [no_top_order α] (a : α) : map (coe : Ioi a → α) at_top = at_top := begin rcases no_top a with ⟨b, hb⟩, exact map_coe_at_top_of_Ici_subset (Ici_subset_Ioi.2 hb) end /-- The `at_top` filter for an open interval `Ioi a` comes from the `at_top` filter in the ambient order. -/ lemma at_top_Ioi_eq [semilattice_sup α] (a : α) : at_top = comap (coe : Ioi a → α) at_top := begin nontriviality, rcases nontrivial_iff_nonempty.1 ‹_› with ⟨b, hb⟩, rw [← map_coe_at_top_of_Ici_subset (Ici_subset_Ioi.2 hb), comap_map subtype.coe_injective] end /-- The `at_top` filter for an open interval `Ici a` comes from the `at_top` filter in the ambient order. -/ lemma at_top_Ici_eq [semilattice_sup α] (a : α) : at_top = comap (coe : Ici a → α) at_top := by rw [← map_coe_Ici_at_top a, comap_map subtype.coe_injective] /-- The `at_bot` filter for an open interval `Iio a` comes from the `at_bot` filter in the ambient order. -/ @[simp] lemma map_coe_Iio_at_bot [semilattice_inf α] [no_bot_order α] (a : α) : map (coe : Iio a → α) at_bot = at_bot := @map_coe_Ioi_at_top (order_dual α) _ _ _ /-- The `at_bot` filter for an open interval `Iio a` comes from the `at_bot` filter in the ambient order. -/ lemma at_bot_Iio_eq [semilattice_inf α] (a : α) : at_bot = comap (coe : Iio a → α) at_bot := @at_top_Ioi_eq (order_dual α) _ _ /-- The `at_bot` filter for an open interval `Iic a` comes from the `at_bot` filter in the ambient order. -/ @[simp] lemma map_coe_Iic_at_bot [semilattice_inf α] (a : α) : map (coe : Iic a → α) at_bot = at_bot := @map_coe_Ici_at_top (order_dual α) _ _ /-- The `at_bot` filter for an open interval `Iic a` comes from the `at_bot` filter in the ambient order. -/ lemma at_bot_Iic_eq [semilattice_inf α] (a : α) : at_bot = comap (coe : Iic a → α) at_bot := @at_top_Ici_eq (order_dual α) _ _ lemma tendsto_Ioi_at_top [semilattice_sup α] {a : α} {f : β → Ioi a} {l : filter β} : tendsto f l at_top ↔ tendsto (λ x, (f x : α)) l at_top := by rw [at_top_Ioi_eq, tendsto_comap_iff] lemma tendsto_Iio_at_bot [semilattice_inf α] {a : α} {f : β → Iio a} {l : filter β} : tendsto f l at_bot ↔ tendsto (λ x, (f x : α)) l at_bot := by rw [at_bot_Iio_eq, tendsto_comap_iff] lemma tendsto_Ici_at_top [semilattice_sup α] {a : α} {f : β → Ici a} {l : filter β} : tendsto f l at_top ↔ tendsto (λ x, (f x : α)) l at_top := by rw [at_top_Ici_eq, tendsto_comap_iff] lemma tendsto_Iic_at_bot [semilattice_inf α] {a : α} {f : β → Iic a} {l : filter β} : tendsto f l at_bot ↔ tendsto (λ x, (f x : α)) l at_bot := by rw [at_bot_Iic_eq, tendsto_comap_iff] @[simp] lemma tendsto_comp_coe_Ioi_at_top [semilattice_sup α] [no_top_order α] {a : α} {f : α → β} {l : filter β} : tendsto (λ x : Ioi a, f x) at_top l ↔ tendsto f at_top l := by rw [← map_coe_Ioi_at_top a, tendsto_map'_iff] @[simp] lemma tendsto_comp_coe_Ici_at_top [semilattice_sup α] {a : α} {f : α → β} {l : filter β} : tendsto (λ x : Ici a, f x) at_top l ↔ tendsto f at_top l := by rw [← map_coe_Ici_at_top a, tendsto_map'_iff] @[simp] lemma tendsto_comp_coe_Iio_at_bot [semilattice_inf α] [no_bot_order α] {a : α} {f : α → β} {l : filter β} : tendsto (λ x : Iio a, f x) at_bot l ↔ tendsto f at_bot l := by rw [← map_coe_Iio_at_bot a, tendsto_map'_iff] @[simp] lemma tendsto_comp_coe_Iic_at_bot [semilattice_inf α] {a : α} {f : α → β} {l : filter β} : tendsto (λ x : Iic a, f x) at_bot l ↔ tendsto f at_bot l := by rw [← map_coe_Iic_at_bot a, tendsto_map'_iff] lemma map_add_at_top_eq_nat (k : ℕ) : map (λa, a + k) at_top = at_top := map_at_top_eq_of_gc (λa, a - k) k (assume a b h, add_le_add_right h k) (assume a b h, (nat.le_sub_right_iff_add_le h).symm) (assume a h, by rw [nat.sub_add_cancel h]) lemma map_sub_at_top_eq_nat (k : ℕ) : map (λa, a - k) at_top = at_top := map_at_top_eq_of_gc (λa, a + k) 0 (assume a b h, nat.sub_le_sub_right h _) (assume a b _, nat.sub_le_right_iff_le_add) (assume b _, by rw [nat.add_sub_cancel]) lemma tendsto_add_at_top_nat (k : ℕ) : tendsto (λa, a + k) at_top at_top := le_of_eq (map_add_at_top_eq_nat k) lemma tendsto_sub_at_top_nat (k : ℕ) : tendsto (λa, a - k) at_top at_top := le_of_eq (map_sub_at_top_eq_nat k) lemma tendsto_add_at_top_iff_nat {f : ℕ → α} {l : filter α} (k : ℕ) : tendsto (λn, f (n + k)) at_top l ↔ tendsto f at_top l := show tendsto (f ∘ (λn, n + k)) at_top l ↔ tendsto f at_top l, by rw [← tendsto_map'_iff, map_add_at_top_eq_nat] lemma map_div_at_top_eq_nat (k : ℕ) (hk : 0 < k) : map (λa, a / k) at_top = at_top := map_at_top_eq_of_gc (λb, b * k + (k - 1)) 1 (assume a b h, nat.div_le_div_right h) (assume a b _, calc a / k ≤ b ↔ a / k < b + 1 : by rw [← nat.succ_eq_add_one, nat.lt_succ_iff] ... ↔ a < (b + 1) * k : nat.div_lt_iff_lt_mul _ _ hk ... ↔ _ : begin cases k, exact (lt_irrefl _ hk).elim, simp [mul_add, add_mul, nat.succ_add, nat.lt_succ_iff] end) (assume b _, calc b = (b * k) / k : by rw [nat.mul_div_cancel b hk] ... ≤ (b * k + (k - 1)) / k : nat.div_le_div_right $ nat.le_add_right _ _) /-- If `u` is a monotone function with linear ordered codomain and the range of `u` is not bounded above, then `tendsto u at_top at_top`. -/ lemma tendsto_at_top_at_top_of_monotone' [preorder ι] [linear_order α] {u : ι → α} (h : monotone u) (H : ¬bdd_above (range u)) : tendsto u at_top at_top := begin apply h.tendsto_at_top_at_top, intro b, rcases not_bdd_above_iff.1 H b with ⟨_, ⟨N, rfl⟩, hN⟩, exact ⟨N, le_of_lt hN⟩, end /-- If `u` is a monotone function with linear ordered codomain and the range of `u` is not bounded below, then `tendsto u at_bot at_bot`. -/ lemma tendsto_at_bot_at_bot_of_monotone' [preorder ι] [linear_order α] {u : ι → α} (h : monotone u) (H : ¬bdd_below (range u)) : tendsto u at_bot at_bot := @tendsto_at_top_at_top_of_monotone' (order_dual ι) (order_dual α) _ _ _ h.order_dual H lemma unbounded_of_tendsto_at_top [nonempty α] [semilattice_sup α] [preorder β] [no_top_order β] {f : α → β} (h : tendsto f at_top at_top) : ¬ bdd_above (range f) := begin rintros ⟨M, hM⟩, cases mem_at_top_sets.mp (h $ Ioi_mem_at_top M) with a ha, apply lt_irrefl M, calc M < f a : ha a (le_refl _) ... ≤ M : hM (set.mem_range_self a) end lemma unbounded_of_tendsto_at_bot [nonempty α] [semilattice_sup α] [preorder β] [no_bot_order β] {f : α → β} (h : tendsto f at_top at_bot) : ¬ bdd_below (range f) := @unbounded_of_tendsto_at_top _ (order_dual β) _ _ _ _ _ h lemma unbounded_of_tendsto_at_top' [nonempty α] [semilattice_inf α] [preorder β] [no_top_order β] {f : α → β} (h : tendsto f at_bot at_top) : ¬ bdd_above (range f) := @unbounded_of_tendsto_at_top (order_dual α) _ _ _ _ _ _ h lemma unbounded_of_tendsto_at_bot' [nonempty α] [semilattice_inf α] [preorder β] [no_bot_order β] {f : α → β} (h : tendsto f at_bot at_bot) : ¬ bdd_below (range f) := @unbounded_of_tendsto_at_top (order_dual α) (order_dual β) _ _ _ _ _ h /-- If a monotone function `u : ι → α` tends to `at_top` along *some* non-trivial filter `l`, then it tends to `at_top` along `at_top`. -/ lemma tendsto_at_top_of_monotone_of_filter [preorder ι] [preorder α] {l : filter ι} {u : ι → α} (h : monotone u) [ne_bot l] (hu : tendsto u l at_top) : tendsto u at_top at_top := h.tendsto_at_top_at_top $ λ b, (hu.eventually (mem_at_top b)).exists /-- If a monotone function `u : ι → α` tends to `at_bot` along *some* non-trivial filter `l`, then it tends to `at_bot` along `at_bot`. -/ lemma tendsto_at_bot_of_monotone_of_filter [preorder ι] [preorder α] {l : filter ι} {u : ι → α} (h : monotone u) [ne_bot l] (hu : tendsto u l at_bot) : tendsto u at_bot at_bot := @tendsto_at_top_of_monotone_of_filter (order_dual ι) (order_dual α) _ _ _ _ h.order_dual _ hu lemma tendsto_at_top_of_monotone_of_subseq [preorder ι] [preorder α] {u : ι → α} {φ : ι' → ι} (h : monotone u) {l : filter ι'} [ne_bot l] (H : tendsto (u ∘ φ) l at_top) : tendsto u at_top at_top := tendsto_at_top_of_monotone_of_filter h (tendsto_map' H) lemma tendsto_at_bot_of_monotone_of_subseq [preorder ι] [preorder α] {u : ι → α} {φ : ι' → ι} (h : monotone u) {l : filter ι'} [ne_bot l] (H : tendsto (u ∘ φ) l at_bot) : tendsto u at_bot at_bot := tendsto_at_bot_of_monotone_of_filter h (tendsto_map' H) /-- Let `f` and `g` be two maps to the same commutative monoid. This lemma gives a sufficient condition for comparison of the filter `at_top.map (λ s, ∏ b in s, f b)` with `at_top.map (λ s, ∏ b in s, g b)`. This is useful to compare the set of limit points of `Π b in s, f b` as `s → at_top` with the similar set for `g`. -/ @[to_additive] lemma map_at_top_finset_prod_le_of_prod_eq [comm_monoid α] {f : β → α} {g : γ → α} (h_eq : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ ∏ x in u', g x = ∏ b in v', f b) : at_top.map (λs:finset β, ∏ b in s, f b) ≤ at_top.map (λs:finset γ, ∏ x in s, g x) := by rw [map_at_top_eq, map_at_top_eq]; from (le_infi $ assume b, let ⟨v, hv⟩ := h_eq b in infi_le_of_le v $ by simp [set.image_subset_iff]; exact hv) lemma has_antimono_basis.tendsto [semilattice_sup ι] [nonempty ι] {l : filter α} {p : ι → Prop} {s : ι → set α} (hl : l.has_antimono_basis p s) {φ : ι → α} (h : ∀ i : ι, φ i ∈ s i) : tendsto φ at_top l := (at_top_basis.tendsto_iff hl.to_has_basis).2 $ assume i hi, ⟨i, trivial, λ j hij, hl.decreasing hi (hl.mono hij hi) hij (h j)⟩ namespace is_countably_generated /-- An abstract version of continuity of sequentially continuous functions on metric spaces: if a filter `k` is countably generated then `tendsto f k l` iff for every sequence `u` converging to `k`, `f ∘ u` tends to `l`. -/ lemma tendsto_iff_seq_tendsto {f : α → β} {k : filter α} {l : filter β} (hcb : k.is_countably_generated) : tendsto f k l ↔ (∀ x : ℕ → α, tendsto x at_top k → tendsto (f ∘ x) at_top l) := suffices (∀ x : ℕ → α, tendsto x at_top k → tendsto (f ∘ x) at_top l) → tendsto f k l, from ⟨by intros; apply tendsto.comp; assumption, by assumption⟩, begin rcases hcb.exists_antimono_basis with ⟨g, gbasis, gmon, -⟩, contrapose, simp only [not_forall, gbasis.tendsto_left_iff, exists_const, not_exists, not_imp], rintro ⟨B, hBl, hfBk⟩, choose x h using hfBk, use x, split, { exact (at_top_basis.tendsto_iff gbasis).2 (λ i _, ⟨i, trivial, λ j hj, gmon trivial trivial hj (h j).1⟩) }, { simp only [tendsto_at_top', (∘), not_forall, not_exists], use [B, hBl], intro i, use [i, (le_refl _)], apply (h i).right }, end lemma tendsto_of_seq_tendsto {f : α → β} {k : filter α} {l : filter β} (hcb : k.is_countably_generated) : (∀ x : ℕ → α, tendsto x at_top k → tendsto (f ∘ x) at_top l) → tendsto f k l := hcb.tendsto_iff_seq_tendsto.2 lemma subseq_tendsto {f : filter α} (hf : is_countably_generated f) {u : ℕ → α} (hx : ne_bot (f ⊓ map u at_top)) : ∃ (θ : ℕ → ℕ), (strict_mono θ) ∧ (tendsto (u ∘ θ) at_top f) := begin rcases hf.exists_antimono_basis with ⟨B, h⟩, have : ∀ N, ∃ n ≥ N, u n ∈ B N, from λ N, filter.inf_map_at_top_ne_bot_iff.mp hx _ (h.to_has_basis.mem_of_mem trivial) N, choose φ hφ using this, cases forall_and_distrib.mp hφ with φ_ge φ_in, have lim_uφ : tendsto (u ∘ φ) at_top f, from h.tendsto φ_in, have lim_φ : tendsto φ at_top at_top, from (tendsto_at_top_mono φ_ge tendsto_id), obtain ⟨ψ, hψ, hψφ⟩ : ∃ ψ : ℕ → ℕ, strict_mono ψ ∧ strict_mono (φ ∘ ψ), from strict_mono_subseq_of_tendsto_at_top lim_φ, exact ⟨φ ∘ ψ, hψφ, lim_uφ.comp $ strict_mono_tendsto_at_top hψ⟩, end end is_countably_generated end filter open filter finset section variables {R : Type*} [linear_ordered_semiring R] lemma exists_lt_mul_self (a : R) : ∃ x ≥ 0, a < x * x := let ⟨x, hxa, hx0⟩ :=((tendsto_mul_self_at_top.eventually (eventually_gt_at_top a)).and (eventually_ge_at_top 0)).exists in ⟨x, hx0, hxa⟩ lemma exists_le_mul_self (a : R) : ∃ x ≥ 0, a ≤ x * x := let ⟨x, hx0, hxa⟩ := exists_lt_mul_self a in ⟨x, hx0, hxa.le⟩ end namespace order_iso variables [preorder α] [preorder β] @[simp] lemma comap_at_top (e : α ≃o β) : comap e at_top = at_top := by simp [at_top, ← e.surjective.infi_comp] @[simp] lemma comap_at_bot (e : α ≃o β) : comap e at_bot = at_bot := e.dual.comap_at_top @[simp] lemma map_at_top (e : α ≃o β) : map ⇑e at_top = at_top := by rw [← e.comap_at_top, map_comap_of_surjective e.surjective] @[simp] lemma map_at_bot (e : α ≃o β) : map ⇑e at_bot = at_bot := e.dual.map_at_top lemma tendsto_at_top (e : α ≃o β) : tendsto e at_top at_top := e.map_at_top.le lemma tendsto_at_bot (e : α ≃o β) : tendsto e at_bot at_bot := e.map_at_bot.le @[simp] lemma tendsto_at_top_iff {l : filter γ} {f : γ → α} (e : α ≃o β) : tendsto (λ x, e (f x)) l at_top ↔ tendsto f l at_top := by rw [← e.comap_at_top, tendsto_comap_iff] @[simp] lemma tendsto_at_bot_iff {l : filter γ} {f : γ → α} (e : α ≃o β) : tendsto (λ x, e (f x)) l at_bot ↔ tendsto f l at_bot := e.dual.tendsto_at_top_iff end order_iso /-- Let `g : γ → β` be an injective function and `f : β → α` be a function from the codomain of `g` to a commutative monoid. Suppose that `f x = 1` outside of the range of `g`. Then the filters `at_top.map (λ s, ∏ i in s, f (g i))` and `at_top.map (λ s, ∏ i in s, f i)` coincide. The additive version of this lemma is used to prove the equality `∑' x, f (g x) = ∑' y, f y` under the same assumptions.-/ @[to_additive] lemma function.injective.map_at_top_finset_prod_eq [comm_monoid α] {g : γ → β} (hg : function.injective g) {f : β → α} (hf : ∀ x ∉ set.range g, f x = 1) : map (λ s, ∏ i in s, f (g i)) at_top = map (λ s, ∏ i in s, f i) at_top := begin apply le_antisymm; refine map_at_top_finset_prod_le_of_prod_eq (λ s, _), { refine ⟨s.preimage g (hg.inj_on _), λ t ht, _⟩, refine ⟨t.image g ∪ s, finset.subset_union_right _ _, _⟩, rw [← finset.prod_image (hg.inj_on _)], refine (prod_subset (subset_union_left _ _) _).symm, simp only [finset.mem_union, finset.mem_image], refine λ y hy hyt, hf y (mt _ hyt), rintros ⟨x, rfl⟩, exact ⟨x, ht (finset.mem_preimage.2 $ hy.resolve_left hyt), rfl⟩ }, { refine ⟨s.image g, λ t ht, _⟩, simp only [← prod_preimage _ _ (hg.inj_on _) _ (λ x _, hf x)], exact ⟨_, (image_subset_iff_subset_preimage _).1 ht, rfl⟩ } end /-- Let `g : γ → β` be an injective function and `f : β → α` be a function from the codomain of `g` to an additive commutative monoid. Suppose that `f x = 0` outside of the range of `g`. Then the filters `at_top.map (λ s, ∑ i in s, f (g i))` and `at_top.map (λ s, ∑ i in s, f i)` coincide. This lemma is used to prove the equality `∑' x, f (g x) = ∑' y, f y` under the same assumptions.-/ add_decl_doc function.injective.map_at_top_finset_sum_eq
34bb34aef50f45d2903a5023c14ccf37ca2758cb
9028d228ac200bbefe3a711342514dd4e4458bff
/src/data/finset/lattice.lean
dad64260c9ef24ef16668c1c246c8f9fc99f2acb
[ "Apache-2.0" ]
permissive
mcncm/mathlib
8d25099344d9d2bee62822cb9ed43aa3e09fa05e
fde3d78cadeec5ef827b16ae55664ef115e66f57
refs/heads/master
1,672,743,316,277
1,602,618,514,000
1,602,618,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
24,114
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import data.finset.fold import data.multiset.lattice /-! # Lattice operations on finsets -/ variables {α β γ : Type*} namespace finset open multiset /-! ### sup -/ section sup variables [semilattice_sup_bot α] /-- Supremum of a finite set: `sup {a, b, c} f = f a ⊔ f b ⊔ f c` -/ def sup (s : finset β) (f : β → α) : α := s.fold (⊔) ⊥ f variables {s s₁ s₂ : finset β} {f : β → α} lemma sup_def : s.sup f = (s.1.map f).sup := rfl @[simp] lemma sup_empty : (∅ : finset β).sup f = ⊥ := fold_empty @[simp] lemma sup_insert [decidable_eq β] {b : β} : (insert b s : finset β).sup f = f b ⊔ s.sup f := fold_insert_idem @[simp] lemma sup_singleton {b : β} : ({b} : finset β).sup f = f b := sup_singleton lemma sup_union [decidable_eq β] : (s₁ ∪ s₂).sup f = s₁.sup f ⊔ s₂.sup f := finset.induction_on s₁ (by rw [empty_union, sup_empty, bot_sup_eq]) $ λ a s has ih, by rw [insert_union, sup_insert, sup_insert, ih, sup_assoc] theorem sup_congr {f g : β → α} (hs : s₁ = s₂) (hfg : ∀a∈s₂, f a = g a) : s₁.sup f = s₂.sup g := by subst hs; exact finset.fold_congr hfg @[simp] lemma sup_le_iff {a : α} : s.sup f ≤ a ↔ (∀b ∈ s, f b ≤ a) := begin apply iff.trans multiset.sup_le, simp only [multiset.mem_map, and_imp, exists_imp_distrib], exact ⟨λ k b hb, k _ _ hb rfl, λ k a' b hb h, h ▸ k _ hb⟩, end lemma sup_le {a : α} : (∀b ∈ s, f b ≤ a) → s.sup f ≤ a := sup_le_iff.2 lemma le_sup {b : β} (hb : b ∈ s) : f b ≤ s.sup f := sup_le_iff.1 (le_refl _) _ hb lemma sup_mono_fun {g : β → α} (h : ∀b∈s, f b ≤ g b) : s.sup f ≤ s.sup g := sup_le (λ b hb, le_trans (h b hb) (le_sup hb)) lemma sup_mono (h : s₁ ⊆ s₂) : s₁.sup f ≤ s₂.sup f := sup_le $ assume b hb, le_sup (h hb) @[simp] lemma sup_lt_iff [is_total α (≤)] {a : α} (ha : ⊥ < a) : s.sup f < a ↔ (∀b ∈ s, f b < a) := by letI := classical.dec_eq β; from ⟨ λh b hb, lt_of_le_of_lt (le_sup hb) h, finset.induction_on s (by simp [ha]) (by simp {contextual := tt}) ⟩ lemma comp_sup_eq_sup_comp [semilattice_sup_bot γ] {s : finset β} {f : β → α} (g : α → γ) (g_sup : ∀ x y, g (x ⊔ y) = g x ⊔ g y) (bot : g ⊥ = ⊥) : g (s.sup f) = s.sup (g ∘ f) := by letI := classical.dec_eq β; from finset.induction_on s (by simp [bot]) (by simp [g_sup] {contextual := tt}) lemma comp_sup_eq_sup_comp_of_is_total [is_total α (≤)] {γ : Type} [semilattice_sup_bot γ] (g : α → γ) (mono_g : monotone g) (bot : g ⊥ = ⊥) : g (s.sup f) = s.sup (g ∘ f) := comp_sup_eq_sup_comp g mono_g.map_sup bot /-- Computating `sup` in a subtype (closed under `sup`) is the same as computing it in `α`. -/ lemma sup_coe {P : α → Prop} {Pbot : P ⊥} {Psup : ∀{{x y}}, P x → P y → P (x ⊔ y)} (t : finset β) (f : β → {x : α // P x}) : (@sup _ _ (subtype.semilattice_sup_bot Pbot Psup) t f : α) = t.sup (λ x, f x) := by { classical, rw [comp_sup_eq_sup_comp coe]; intros; refl } theorem subset_range_sup_succ (s : finset ℕ) : s ⊆ range (s.sup id).succ := λ n hn, mem_range.2 $ nat.lt_succ_of_le $ le_sup hn theorem exists_nat_subset_range (s : finset ℕ) : ∃n : ℕ, s ⊆ range n := ⟨_, s.subset_range_sup_succ⟩ lemma mem_sup {α β} [decidable_eq β] {s : finset α} {f : α → multiset β} {x : β} : x ∈ s.sup f ↔ ∃ v ∈ s, x ∈ f v := begin classical, apply s.induction_on, { simp }, { intros a s has hxs, rw [finset.sup_insert, multiset.sup_eq_union, multiset.mem_union], split, { intro hxi, cases hxi with hf hf, { refine ⟨a, _, hf⟩, simp only [true_or, eq_self_iff_true, finset.mem_insert] }, { rcases hxs.mp hf with ⟨v, hv, hfv⟩, refine ⟨v, _, hfv⟩, simp only [hv, or_true, finset.mem_insert] } }, { rintros ⟨v, hv, hfv⟩, rw [finset.mem_insert] at hv, rcases hv with rfl | hv, { exact or.inl hfv }, { refine or.inr (hxs.mpr ⟨v, hv, hfv⟩) } } }, end lemma sup_subset {α β} [semilattice_sup_bot β] {s t : finset α} (hst : s ⊆ t) (f : α → β) : s.sup f ≤ t.sup f := by classical; calc t.sup f = (s ∪ t).sup f : by rw [finset.union_eq_right_iff_subset.mpr hst] ... = s.sup f ⊔ t.sup f : by rw finset.sup_union ... ≥ s.sup f : le_sup_left end sup lemma sup_eq_supr [complete_lattice β] (s : finset α) (f : α → β) : s.sup f = (⨆a∈s, f a) := le_antisymm (finset.sup_le $ assume a ha, le_supr_of_le a $ le_supr _ ha) (supr_le $ assume a, supr_le $ assume ha, le_sup ha) /-! ### inf -/ section inf variables [semilattice_inf_top α] /-- Infimum of a finite set: `inf {a, b, c} f = f a ⊓ f b ⊓ f c` -/ def inf (s : finset β) (f : β → α) : α := s.fold (⊓) ⊤ f variables {s s₁ s₂ : finset β} {f : β → α} lemma inf_def : s.inf f = (s.1.map f).inf := rfl @[simp] lemma inf_empty : (∅ : finset β).inf f = ⊤ := fold_empty lemma le_inf_iff {a : α} : a ≤ s.inf f ↔ ∀b ∈ s, a ≤ f b := @sup_le_iff (order_dual α) _ _ _ _ _ @[simp] lemma inf_insert [decidable_eq β] {b : β} : (insert b s : finset β).inf f = f b ⊓ s.inf f := fold_insert_idem @[simp] lemma inf_singleton {b : β} : ({b} : finset β).inf f = f b := inf_singleton lemma inf_union [decidable_eq β] : (s₁ ∪ s₂).inf f = s₁.inf f ⊓ s₂.inf f := @sup_union (order_dual α) _ _ _ _ _ _ theorem inf_congr {f g : β → α} (hs : s₁ = s₂) (hfg : ∀a∈s₂, f a = g a) : s₁.inf f = s₂.inf g := by subst hs; exact finset.fold_congr hfg lemma inf_le {b : β} (hb : b ∈ s) : s.inf f ≤ f b := le_inf_iff.1 (le_refl _) _ hb lemma le_inf {a : α} : (∀b ∈ s, a ≤ f b) → a ≤ s.inf f := le_inf_iff.2 lemma inf_mono_fun {g : β → α} (h : ∀b∈s, f b ≤ g b) : s.inf f ≤ s.inf g := le_inf (λ b hb, le_trans (inf_le hb) (h b hb)) lemma inf_mono (h : s₁ ⊆ s₂) : s₂.inf f ≤ s₁.inf f := le_inf $ assume b hb, inf_le (h hb) lemma lt_inf_iff [h : is_total α (≤)] {a : α} (ha : a < ⊤) : a < s.inf f ↔ (∀b ∈ s, a < f b) := @sup_lt_iff (order_dual α) _ _ _ _ (@is_total.swap α _ h) _ ha lemma comp_inf_eq_inf_comp [semilattice_inf_top γ] {s : finset β} {f : β → α} (g : α → γ) (g_inf : ∀ x y, g (x ⊓ y) = g x ⊓ g y) (top : g ⊤ = ⊤) : g (s.inf f) = s.inf (g ∘ f) := @comp_sup_eq_sup_comp (order_dual α) _ (order_dual γ) _ _ _ _ _ g_inf top lemma comp_inf_eq_inf_comp_of_is_total [h : is_total α (≤)] {γ : Type} [semilattice_inf_top γ] (g : α → γ) (mono_g : monotone g) (top : g ⊤ = ⊤) : g (s.inf f) = s.inf (g ∘ f) := comp_inf_eq_inf_comp g mono_g.map_inf top /-- Computating `inf` in a subtype (closed under `inf`) is the same as computing it in `α`. -/ lemma inf_coe {P : α → Prop} {Ptop : P ⊤} {Pinf : ∀{{x y}}, P x → P y → P (x ⊓ y)} (t : finset β) (f : β → {x : α // P x}) : (@inf _ _ (subtype.semilattice_inf_top Ptop Pinf) t f : α) = t.inf (λ x, f x) := by { classical, rw [comp_inf_eq_inf_comp coe]; intros; refl } end inf lemma inf_eq_infi [complete_lattice β] (s : finset α) (f : α → β) : s.inf f = (⨅a∈s, f a) := @sup_eq_supr _ (order_dual β) _ _ _ /-! ### max and min of finite sets -/ section max_min variables [decidable_linear_order α] /-- Let `s` be a finset in a linear order. Then `s.max` is the maximum of `s` if `s` is not empty, and `none` otherwise. It belongs to `option α`. If you want to get an element of `α`, see `s.max'`. -/ protected def max : finset α → option α := fold (option.lift_or_get max) none some theorem max_eq_sup_with_bot (s : finset α) : s.max = @sup (with_bot α) α _ s some := rfl @[simp] theorem max_empty : (∅ : finset α).max = none := rfl @[simp] theorem max_insert {a : α} {s : finset α} : (insert a s).max = option.lift_or_get max (some a) s.max := fold_insert_idem @[simp] theorem max_singleton {a : α} : finset.max {a} = some a := by { rw [← insert_emptyc_eq], exact max_insert } theorem max_of_mem {s : finset α} {a : α} (h : a ∈ s) : ∃ b, b ∈ s.max := (@le_sup (with_bot α) _ _ _ _ _ h _ rfl).imp $ λ b, Exists.fst theorem max_of_nonempty {s : finset α} (h : s.nonempty) : ∃ a, a ∈ s.max := let ⟨a, ha⟩ := h in max_of_mem ha theorem max_eq_none {s : finset α} : s.max = none ↔ s = ∅ := ⟨λ h, s.eq_empty_or_nonempty.elim id (λ H, let ⟨a, ha⟩ := max_of_nonempty H in by rw h at ha; cases ha), λ h, h.symm ▸ max_empty⟩ theorem mem_of_max {s : finset α} : ∀ {a : α}, a ∈ s.max → a ∈ s := finset.induction_on s (λ _ H, by cases H) (λ b s _ (ih : ∀ {a}, a ∈ s.max → a ∈ s) a (h : a ∈ (insert b s).max), begin by_cases p : b = a, { induction p, exact mem_insert_self b s }, { cases option.lift_or_get_choice max_choice (some b) s.max with q q; rw [max_insert, q] at h, { cases h, cases p rfl }, { exact mem_insert_of_mem (ih h) } } end) theorem le_max_of_mem {s : finset α} {a b : α} (h₁ : a ∈ s) (h₂ : b ∈ s.max) : a ≤ b := by rcases @le_sup (with_bot α) _ _ _ _ _ h₁ _ rfl with ⟨b', hb, ab⟩; cases h₂.symm.trans hb; assumption /-- Let `s` be a finset in a linear order. Then `s.min` is the minimum of `s` if `s` is not empty, and `none` otherwise. It belongs to `option α`. If you want to get an element of `α`, see `s.min'`. -/ protected def min : finset α → option α := fold (option.lift_or_get min) none some theorem min_eq_inf_with_top (s : finset α) : s.min = @inf (with_top α) α _ s some := rfl @[simp] theorem min_empty : (∅ : finset α).min = none := rfl @[simp] theorem min_insert {a : α} {s : finset α} : (insert a s).min = option.lift_or_get min (some a) s.min := fold_insert_idem @[simp] theorem min_singleton {a : α} : finset.min {a} = some a := by { rw ← insert_emptyc_eq, exact min_insert } theorem min_of_mem {s : finset α} {a : α} (h : a ∈ s) : ∃ b, b ∈ s.min := (@inf_le (with_top α) _ _ _ _ _ h _ rfl).imp $ λ b, Exists.fst theorem min_of_nonempty {s : finset α} (h : s.nonempty) : ∃ a, a ∈ s.min := let ⟨a, ha⟩ := h in min_of_mem ha theorem min_eq_none {s : finset α} : s.min = none ↔ s = ∅ := ⟨λ h, s.eq_empty_or_nonempty.elim id (λ H, let ⟨a, ha⟩ := min_of_nonempty H in by rw h at ha; cases ha), λ h, h.symm ▸ min_empty⟩ theorem mem_of_min {s : finset α} : ∀ {a : α}, a ∈ s.min → a ∈ s := finset.induction_on s (λ _ H, by cases H) $ λ b s _ (ih : ∀ {a}, a ∈ s.min → a ∈ s) a (h : a ∈ (insert b s).min), begin by_cases p : b = a, { induction p, exact mem_insert_self b s }, { cases option.lift_or_get_choice min_choice (some b) s.min with q q; rw [min_insert, q] at h, { cases h, cases p rfl }, { exact mem_insert_of_mem (ih h) } } end theorem min_le_of_mem {s : finset α} {a b : α} (h₁ : b ∈ s) (h₂ : a ∈ s.min) : a ≤ b := by rcases @inf_le (with_top α) _ _ _ _ _ h₁ _ rfl with ⟨b', hb, ab⟩; cases h₂.symm.trans hb; assumption /-- Given a nonempty finset `s` in a linear order `α `, then `s.min' h` is its minimum, as an element of `α`, where `h` is a proof of nonemptiness. Without this assumption, use instead `s.min`, taking values in `option α`. -/ def min' (s : finset α) (H : s.nonempty) : α := @option.get _ s.min $ let ⟨k, hk⟩ := H in let ⟨b, hb⟩ := min_of_mem hk in by simp at hb; simp [hb] /-- Given a nonempty finset `s` in a linear order `α `, then `s.max' h` is its maximum, as an element of `α`, where `h` is a proof of nonemptiness. Without this assumption, use instead `s.max`, taking values in `option α`. -/ def max' (s : finset α) (H : s.nonempty) : α := @option.get _ s.max $ let ⟨k, hk⟩ := H in let ⟨b, hb⟩ := max_of_mem hk in by simp at hb; simp [hb] variables (s : finset α) (H : s.nonempty) theorem min'_mem : s.min' H ∈ s := mem_of_min $ by simp [min'] theorem min'_le (x) (H2 : x ∈ s) : s.min' ⟨x, H2⟩ ≤ x := min_le_of_mem H2 $ option.get_mem _ theorem le_min' (x) (H2 : ∀ y ∈ s, x ≤ y) : x ≤ s.min' H := H2 _ $ min'_mem _ _ /-- `{a}.min' _` is `a`. -/ @[simp] lemma min'_singleton (a : α) : ({a} : finset α).min' (singleton_nonempty _) = a := by simp [min'] theorem max'_mem : s.max' H ∈ s := mem_of_max $ by simp [max'] theorem le_max' (x) (H2 : x ∈ s) : x ≤ s.max' ⟨x, H2⟩ := le_max_of_mem H2 $ option.get_mem _ theorem max'_le (x) (H2 : ∀ y ∈ s, y ≤ x) : s.max' H ≤ x := H2 _ $ max'_mem _ _ /-- `{a}.max' _` is `a`. -/ @[simp] lemma max'_singleton (a : α) : ({a} : finset α).max' (singleton_nonempty _) = a := by simp [max'] theorem min'_lt_max' {i j} (H1 : i ∈ s) (H2 : j ∈ s) (H3 : i ≠ j) : s.min' ⟨i, H1⟩ < s.max' ⟨i, H1⟩ := begin rcases lt_trichotomy i j with H4 | H4 | H4, { have H5 := min'_le s i H1, have H6 := le_max' s j H2, apply lt_of_le_of_lt H5, apply lt_of_lt_of_le H4 H6 }, { cc }, { have H5 := min'_le s j H2, have H6 := le_max' s i H1, apply lt_of_le_of_lt H5, apply lt_of_lt_of_le H4 H6 } end /-- If there's more than 1 element, the min' is less than the max'. An alternate version of `min'_lt_max'` which is sometimes more convenient. -/ lemma min'_lt_max'_of_card (h₂ : 1 < card s) : s.min' (finset.card_pos.mp $ lt_trans zero_lt_one h₂) < s.max' (finset.card_pos.mp $ lt_trans zero_lt_one h₂) := begin apply lt_of_not_ge, intro a, apply not_le_of_lt h₂ (le_of_eq _), rw card_eq_one, use (max' s (finset.card_pos.mp $ lt_trans zero_lt_one h₂)), rw eq_singleton_iff_unique_mem, refine ⟨max'_mem _ _, λ t Ht, le_antisymm (le_max' s t Ht) (le_trans a (min'_le s t Ht))⟩, end end max_min section exists_max_min variables [linear_order α] lemma exists_max_image (s : finset β) (f : β → α) (h : s.nonempty) : ∃ x ∈ s, ∀ x' ∈ s, f x' ≤ f x := begin letI := classical.DLO α, cases max_of_nonempty (h.image f) with y hy, rcases mem_image.mp (mem_of_max hy) with ⟨x, hx, rfl⟩, exact ⟨x, hx, λ x' hx', le_max_of_mem (mem_image_of_mem f hx') hy⟩, end lemma exists_min_image (s : finset β) (f : β → α) (h : s.nonempty) : ∃ x ∈ s, ∀ x' ∈ s, f x ≤ f x' := @exists_max_image (order_dual α) β _ s f h end exists_max_min end finset namespace multiset lemma count_sup [decidable_eq β] (s : finset α) (f : α → multiset β) (b : β) : count b (s.sup f) = s.sup (λa, count b (f a)) := begin letI := classical.dec_eq α, refine s.induction _ _, { exact count_zero _ }, { assume i s his ih, rw [finset.sup_insert, sup_eq_union, count_union, finset.sup_insert, ih], refl } end end multiset section lattice variables {ι : Type*} {ι' : Sort*} [complete_lattice α] /-- Supremum of `s i`, `i : ι`, is equal to the supremum over `t : finset ι` of suprema `⨆ i ∈ t, s i`. This version assumes `ι` is a `Type*`. See `supr_eq_supr_finset'` for a version that works for `ι : Sort*`. -/ lemma supr_eq_supr_finset (s : ι → α) : (⨆i, s i) = (⨆t:finset ι, ⨆i∈t, s i) := begin classical, exact le_antisymm (supr_le $ assume b, le_supr_of_le {b} $ le_supr_of_le b $ le_supr_of_le (by simp) $ le_refl _) (supr_le $ assume t, supr_le $ assume b, supr_le $ assume hb, le_supr _ _) end /-- Supremum of `s i`, `i : ι`, is equal to the supremum over `t : finset ι` of suprema `⨆ i ∈ t, s i`. This version works for `ι : Sort*`. See `supr_eq_supr_finset` for a version that assumes `ι : Type*` but has no `plift`s. -/ lemma supr_eq_supr_finset' (s : ι' → α) : (⨆i, s i) = (⨆t:finset (plift ι'), ⨆i∈t, s (plift.down i)) := by rw [← supr_eq_supr_finset, ← equiv.plift.surjective.supr_comp]; refl /-- Infimum of `s i`, `i : ι`, is equal to the infimum over `t : finset ι` of infima `⨆ i ∈ t, s i`. This version assumes `ι` is a `Type*`. See `infi_eq_infi_finset'` for a version that works for `ι : Sort*`. -/ lemma infi_eq_infi_finset (s : ι → α) : (⨅i, s i) = (⨅t:finset ι, ⨅i∈t, s i) := @supr_eq_supr_finset (order_dual α) _ _ _ /-- Infimum of `s i`, `i : ι`, is equal to the infimum over `t : finset ι` of infima `⨆ i ∈ t, s i`. This version works for `ι : Sort*`. See `infi_eq_infi_finset` for a version that assumes `ι : Type*` but has no `plift`s. -/ lemma infi_eq_infi_finset' (s : ι' → α) : (⨅i, s i) = (⨅t:finset (plift ι'), ⨅i∈t, s (plift.down i)) := @supr_eq_supr_finset' (order_dual α) _ _ _ end lattice namespace set variables {ι : Type*} {ι' : Sort*} /-- Union of an indexed family of sets `s : ι → set α` is equal to the union of the unions of finite subfamilies. This version assumes `ι : Type*`. See also `Union_eq_Union_finset'` for a version that works for `ι : Sort*`. -/ lemma Union_eq_Union_finset (s : ι → set α) : (⋃i, s i) = (⋃t:finset ι, ⋃i∈t, s i) := supr_eq_supr_finset s /-- Union of an indexed family of sets `s : ι → set α` is equal to the union of the unions of finite subfamilies. This version works for `ι : Sort*`. See also `Union_eq_Union_finset` for a version that assumes `ι : Type*` but avoids `plift`s in the right hand side. -/ lemma Union_eq_Union_finset' (s : ι' → set α) : (⋃i, s i) = (⋃t:finset (plift ι'), ⋃i∈t, s (plift.down i)) := supr_eq_supr_finset' s /-- Intersection of an indexed family of sets `s : ι → set α` is equal to the intersection of the intersections of finite subfamilies. This version assumes `ι : Type*`. See also `Inter_eq_Inter_finset'` for a version that works for `ι : Sort*`. -/ lemma Inter_eq_Inter_finset (s : ι → set α) : (⋂i, s i) = (⋂t:finset ι, ⋂i∈t, s i) := infi_eq_infi_finset s /-- Intersection of an indexed family of sets `s : ι → set α` is equal to the intersection of the intersections of finite subfamilies. This version works for `ι : Sort*`. See also `Inter_eq_Inter_finset` for a version that assumes `ι : Type*` but avoids `plift`s in the right hand side. -/ lemma Inter_eq_Inter_finset' (s : ι' → set α) : (⋂i, s i) = (⋂t:finset (plift ι'), ⋂i∈t, s (plift.down i)) := infi_eq_infi_finset' s end set namespace finset open function /-! ### Interaction with big lattice/set operations -/ section lattice lemma supr_coe [has_Sup β] (f : α → β) (s : finset α) : (⨆ x ∈ (↑s : set α), f x) = ⨆ x ∈ s, f x := rfl lemma infi_coe [has_Inf β] (f : α → β) (s : finset α) : (⨅ x ∈ (↑s : set α), f x) = ⨅ x ∈ s, f x := rfl variables [complete_lattice β] theorem supr_singleton (a : α) (s : α → β) : (⨆ x ∈ ({a} : finset α), s x) = s a := by simp theorem infi_singleton (a : α) (s : α → β) : (⨅ x ∈ ({a} : finset α), s x) = s a := by simp lemma supr_option_to_finset (o : option α) (f : α → β) : (⨆ x ∈ o.to_finset, f x) = ⨆ x ∈ o, f x := by { congr, ext, rw [option.mem_to_finset] } lemma infi_option_to_finset (o : option α) (f : α → β) : (⨅ x ∈ o.to_finset, f x) = ⨅ x ∈ o, f x := @supr_option_to_finset _ (order_dual β) _ _ _ variables [decidable_eq α] theorem supr_union {f : α → β} {s t : finset α} : (⨆ x ∈ s ∪ t, f x) = (⨆x∈s, f x) ⊔ (⨆x∈t, f x) := by simp [supr_or, supr_sup_eq] theorem infi_union {f : α → β} {s t : finset α} : (⨅ x ∈ s ∪ t, f x) = (⨅ x ∈ s, f x) ⊓ (⨅ x ∈ t, f x) := by simp [infi_or, infi_inf_eq] lemma supr_insert (a : α) (s : finset α) (t : α → β) : (⨆ x ∈ insert a s, t x) = t a ⊔ (⨆ x ∈ s, t x) := by { rw insert_eq, simp only [supr_union, finset.supr_singleton] } lemma infi_insert (a : α) (s : finset α) (t : α → β) : (⨅ x ∈ insert a s, t x) = t a ⊓ (⨅ x ∈ s, t x) := by { rw insert_eq, simp only [infi_union, finset.infi_singleton] } lemma supr_finset_image {f : γ → α} {g : α → β} {s : finset γ} : (⨆ x ∈ s.image f, g x) = (⨆ y ∈ s, g (f y)) := by rw [← supr_coe, coe_image, supr_image, supr_coe] lemma infi_finset_image {f : γ → α} {g : α → β} {s : finset γ} : (⨅ x ∈ s.image f, g x) = (⨅ y ∈ s, g (f y)) := by rw [← infi_coe, coe_image, infi_image, infi_coe] lemma supr_insert_update {x : α} {t : finset α} (f : α → β) {s : β} (hx : x ∉ t) : (⨆ (i ∈ insert x t), function.update f x s i) = (s ⊔ ⨆ (i ∈ t), f i) := begin simp only [finset.supr_insert, update_same], rcongr i hi, apply update_noteq, rintro rfl, exact hx hi end lemma infi_insert_update {x : α} {t : finset α} (f : α → β) {s : β} (hx : x ∉ t) : (⨅ (i ∈ insert x t), update f x s i) = (s ⊓ ⨅ (i ∈ t), f i) := @supr_insert_update α (order_dual β) _ _ _ _ f _ hx lemma supr_bind (s : finset γ) (t : γ → finset α) (f : α → β) : (⨆ y ∈ s.bind t, f y) = ⨆ (x ∈ s) (y ∈ t x), f y := calc (⨆ y ∈ s.bind t, f y) = ⨆ y (hy : ∃ x ∈ s, y ∈ t x), f y : congr_arg _ $ funext $ λ y, by rw [mem_bind] ... = _ : by simp only [supr_exists, @supr_comm _ α] lemma infi_bind (s : finset γ) (t : γ → finset α) (f : α → β) : (⨅ y ∈ s.bind t, f y) = ⨅ (x ∈ s) (y ∈ t x), f y := @supr_bind _ (order_dual β) _ _ _ _ _ _ end lattice @[simp] theorem bUnion_coe (s : finset α) (t : α → set β) : (⋃ x ∈ (↑s : set α), t x) = ⋃ x ∈ s, t x := rfl @[simp] theorem bInter_coe (s : finset α) (t : α → set β) : (⋂ x ∈ (↑s : set α), t x) = ⋂ x ∈ s, t x := rfl @[simp] theorem bUnion_singleton (a : α) (s : α → set β) : (⋃ x ∈ ({a} : finset α), s x) = s a := supr_singleton a s @[simp] theorem bInter_singleton (a : α) (s : α → set β) : (⋂ x ∈ ({a} : finset α), s x) = s a := infi_singleton a s @[simp] lemma bUnion_preimage_singleton (f : α → β) (s : finset β) : (⋃ y ∈ s, f ⁻¹' {y}) = f ⁻¹' ↑s := set.bUnion_preimage_singleton f ↑s @[simp] lemma bUnion_option_to_finset (o : option α) (f : α → set β) : (⋃ x ∈ o.to_finset, f x) = ⋃ x ∈ o, f x := supr_option_to_finset o f @[simp] lemma bInter_option_to_finset (o : option α) (f : α → set β) : (⋂ x ∈ o.to_finset, f x) = ⋂ x ∈ o, f x := infi_option_to_finset o f variables [decidable_eq α] lemma bUnion_union (s t : finset α) (u : α → set β) : (⋃ x ∈ s ∪ t, u x) = (⋃ x ∈ s, u x) ∪ (⋃ x ∈ t, u x) := supr_union lemma bInter_inter (s t : finset α) (u : α → set β) : (⋂ x ∈ s ∪ t, u x) = (⋂ x ∈ s, u x) ∩ (⋂ x ∈ t, u x) := infi_union @[simp] lemma bUnion_insert (a : α) (s : finset α) (t : α → set β) : (⋃ x ∈ insert a s, t x) = t a ∪ (⋃ x ∈ s, t x) := supr_insert a s t @[simp] lemma bInter_insert (a : α) (s : finset α) (t : α → set β) : (⋂ x ∈ insert a s, t x) = t a ∩ (⋂ x ∈ s, t x) := infi_insert a s t @[simp] lemma bUnion_finset_image {f : γ → α} {g : α → set β} {s : finset γ} : (⋃x ∈ s.image f, g x) = (⋃y ∈ s, g (f y)) := supr_finset_image @[simp] lemma bInter_finset_image {f : γ → α} {g : α → set β} {s : finset γ} : (⋂ x ∈ s.image f, g x) = (⋂ y ∈ s, g (f y)) := infi_finset_image lemma bUnion_insert_update {x : α} {t : finset α} (f : α → set β) {s : set β} (hx : x ∉ t) : (⋃ (i ∈ insert x t), @update _ _ _ f x s i) = (s ∪ ⋃ (i ∈ t), f i) := supr_insert_update f hx lemma bInter_insert_update {x : α} {t : finset α} (f : α → set β) {s : set β} (hx : x ∉ t) : (⋂ (i ∈ insert x t), @update _ _ _ f x s i) = (s ∩ ⋂ (i ∈ t), f i) := infi_insert_update f hx @[simp] lemma bUnion_bind (s : finset γ) (t : γ → finset α) (f : α → set β) : (⋃ y ∈ s.bind t, f y) = ⋃ (x ∈ s) (y ∈ t x), f y := supr_bind s t f @[simp] lemma bInter_bind (s : finset γ) (t : γ → finset α) (f : α → set β) : (⋂ y ∈ s.bind t, f y) = ⋂ (x ∈ s) (y ∈ t x), f y := infi_bind s t f end finset
48b937e484137d8a4cc7bb6a751031d0a72bee07
4fa161becb8ce7378a709f5992a594764699e268
/src/linear_algebra/basic.lean
68c5b577bfd9672612a6ef036fcbc2829410ac0d
[ "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
94,595
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Kevin Buzzard, Yury Kudryashov -/ import algebra.pi_instances import data.finsupp /-! # Linear algebra This file defines the basics of linear algebra. It sets up the "categorical/lattice structure" of modules over a ring, submodules, and linear maps. If `p` and `q` are submodules of a module, `p ≤ q` means that `p ⊆ q`. Many of the relevant definitions, including `module`, `submodule`, and `linear_map`, are found in `src/algebra/module.lean`. ## Main definitions * Many constructors for linear maps, including `prod` and `coprod` * `submodule.span s` is defined to be the smallest submodule containing the set `s`. * If `p` is a submodule of `M`, `submodule.quotient p` is the quotient of `M` with respect to `p`: that is, elements of `M` are identified if their difference is in `p`. This is itself a module. * The kernel `ker` and range `range` of a linear map are submodules of the domain and codomain respectively. * `linear_equiv M M₂`, the type of linear equivalences between `M` and `M₂`, is a structure that extends `linear_map` and `equiv`. * The general linear group is defined to be the group of invertible linear maps from `M` to itself. ## Main statements * The first and second isomorphism laws for modules are proved as `quot_ker_equiv_range` and `quotient_inf_equiv_sup_quotient`. ## Notations * We continue to use the notation `M →ₗ[R] M₂` for the type of linear maps from `M` to `M₂` over the ring `R`. * We introduce the notations `M ≃ₗ M₂` and `M ≃ₗ[R] M₂` for `linear_equiv M M₂`. In the first, the ring `R` is implicit. ## Implementation notes We note that, when constructing linear maps, it is convenient to use operations defined on bundled maps (`prod`, `coprod`, arithmetic operations like `+`) instead of defining a function and proving it is linear. ## Tags linear algebra, vector space, module -/ open function open_locale big_operators reserve infix ` ≃ₗ `:25 universes u v w x y z u' v' w' y' variables {R : Type u} {K : Type u'} {M : Type v} {V : Type v'} {M₂ : Type w} {V₂ : Type w'} variables {M₃ : Type y} {V₃ : Type y'} {M₄ : Type z} {ι : Type x} namespace finsupp lemma smul_sum {α : Type u} {β : Type v} {R : Type w} {M : Type y} [has_zero β] [semiring R] [add_comm_monoid M] [semimodule R M] {v : α →₀ β} {c : R} {h : α → β → M} : c • (v.sum h) = v.sum (λa b, c • h a b) := finset.smul_sum end finsupp section open_locale classical /-- decomposing `x : ι → R` as a sum along the canonical basis -/ lemma pi_eq_sum_univ {ι : Type u} [fintype ι] {R : Type v} [semiring R] (x : ι → R) : x = ∑ i, x i • (λj, if i = j then 1 else 0) := begin ext k, rw pi.finset_sum_apply, have : ∑ i, x i * ite (k = i) 1 0 = x k, by { have := finset.sum_mul_boole finset.univ x k, rwa if_pos (finset.mem_univ _) at this }, rw ← this, apply finset.sum_congr rfl (λl hl, _), simp only [smul_eq_mul, mul_ite, pi.smul_apply], conv_lhs { rw eq_comm } end end /-! ### Properties of linear maps -/ namespace linear_map section add_comm_monoid variables [semiring R] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] [semimodule R M₄] variables (f g : M →ₗ[R] M₂) include R @[simp] theorem comp_id : f.comp id = f := linear_map.ext $ λ x, rfl @[simp] theorem id_comp : id.comp f = f := linear_map.ext $ λ x, rfl theorem comp_assoc (g : M₂ →ₗ[R] M₃) (h : M₃ →ₗ[R] M₄) : (h.comp g).comp f = h.comp (g.comp f) := rfl /-- A linear map `f : M₂ → M` whose values lie in a submodule `p ⊆ M` can be restricted to a linear map M₂ → p. -/ def cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (h : ∀c, f c ∈ p) : M₂ →ₗ[R] p := by refine {to_fun := λc, ⟨f c, h c⟩, ..}; intros; apply set_coe.ext; simp @[simp] theorem cod_restrict_apply (p : submodule R M) (f : M₂ →ₗ[R] M) {h} (x : M₂) : (cod_restrict p f h x : M) = f x := rfl @[simp] lemma comp_cod_restrict (p : submodule R M₂) (h : ∀b, f b ∈ p) (g : M₃ →ₗ[R] M) : (cod_restrict p f h).comp g = cod_restrict p (f.comp g) (assume b, h _) := ext $ assume b, rfl @[simp] lemma subtype_comp_cod_restrict (p : submodule R M₂) (h : ∀b, f b ∈ p) : p.subtype.comp (cod_restrict p f h) = f := ext $ assume b, rfl /-- If a function `g` is a left and right inverse of a linear map `f`, then `g` is linear itself. -/ def inverse (g : M₂ → M) (h₁ : left_inverse g f) (h₂ : right_inverse g f) : M₂ →ₗ[R] M := by dsimp [left_inverse, function.right_inverse] at h₁ h₂; exact ⟨g, λ x y, by rw [← h₁ (g (x + y)), ← h₁ (g x + g y)]; simp [h₂], λ a b, by rw [← h₁ (g (a • b)), ← h₁ (a • g b)]; simp [h₂]⟩ /-- The constant 0 map is linear. -/ instance : has_zero (M →ₗ[R] M₂) := ⟨⟨λ _, 0, by simp, by simp⟩⟩ instance : inhabited (M →ₗ[R] M₂) := ⟨0⟩ @[simp] lemma zero_apply (x : M) : (0 : M →ₗ[R] M₂) x = 0 := rfl /-- The sum of two linear maps is linear. -/ instance : has_add (M →ₗ[R] M₂) := ⟨λ f g, ⟨λ b, f b + g b, by simp [add_comm, add_left_comm], by simp [smul_add]⟩⟩ @[simp] lemma add_apply (x : M) : (f + g) x = f x + g x := rfl /-- The type of linear maps is an additive monoid. -/ instance : add_comm_monoid (M →ₗ[R] M₂) := by refine {zero := 0, add := (+), ..}; intros; ext; simp [add_comm, add_left_comm] instance linear_map_apply_is_add_monoid_hom (a : M) : is_add_monoid_hom (λ f : M →ₗ[R] M₂, f a) := { map_add := λ f g, linear_map.add_apply f g a, map_zero := rfl } lemma sum_apply (t : finset ι) (f : ι → M →ₗ[R] M₂) (b : M) : (∑ d in t, f d) b = ∑ d in t, f d b := (t.sum_hom (λ g : M →ₗ[R] M₂, g b)).symm /-- `λb, f b • x` is a linear map. -/ def smul_right (f : M₂ →ₗ[R] R) (x : M) : M₂ →ₗ[R] M := ⟨λb, f b • x, by simp [add_smul], by simp [smul_smul]⟩. @[simp] theorem smul_right_apply (f : M₂ →ₗ[R] R) (x : M) (c : M₂) : (smul_right f x : M₂ → M) c = f c • x := rfl instance : has_one (M →ₗ[R] M) := ⟨linear_map.id⟩ instance : has_mul (M →ₗ[R] M) := ⟨linear_map.comp⟩ @[simp] lemma one_app (x : M) : (1 : M →ₗ[R] M) x = x := rfl @[simp] lemma mul_app (A B : M →ₗ[R] M) (x : M) : (A * B) x = A (B x) := rfl @[simp] theorem comp_zero : f.comp (0 : M₃ →ₗ[R] M) = 0 := ext $ assume c, by rw [comp_apply, zero_apply, zero_apply, f.map_zero] @[simp] theorem zero_comp : (0 : M₂ →ₗ[R] M₃).comp f = 0 := rfl @[norm_cast] lemma coe_fn_sum {ι : Type*} (t : finset ι) (f : ι → M →ₗ[R] M₂) : ⇑(∑ i in t, f i) = ∑ i in t, (f i : M → M₂) := add_monoid_hom.map_sum ⟨@to_fun R M M₂ _ _ _ _ _, rfl, λ x y, rfl⟩ _ _ instance : monoid (M →ₗ[R] M) := by refine {mul := (*), one := 1, ..}; { intros, apply linear_map.ext, simp {proj := ff} } section open_locale classical /-- A linear map `f` applied to `x : ι → R` can be computed using the image under `f` of elements of the canonical basis. -/ lemma pi_apply_eq_sum_univ [fintype ι] (f : (ι → R) →ₗ[R] M) (x : ι → R) : f x = ∑ i, x i • (f (λj, if i = j then 1 else 0)) := begin conv_lhs { rw [pi_eq_sum_univ x, f.map_sum] }, apply finset.sum_congr rfl (λl hl, _), rw f.map_smul end end section variables (R M M₂) /-- The first projection of a product is a linear map. -/ def fst : M × M₂ →ₗ[R] M := ⟨prod.fst, λ x y, rfl, λ x y, rfl⟩ /-- The second projection of a product is a linear map. -/ def snd : M × M₂ →ₗ[R] M₂ := ⟨prod.snd, λ x y, rfl, λ x y, rfl⟩ end @[simp] theorem fst_apply (x : M × M₂) : fst R M M₂ x = x.1 := rfl @[simp] theorem snd_apply (x : M × M₂) : snd R M M₂ x = x.2 := rfl /-- The prod of two linear maps is a linear map. -/ def prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : M →ₗ[R] M₂ × M₃ := { to_fun := λ x, (f x, g x), map_add' := λ x y, by simp only [prod.mk_add_mk, map_add], map_smul' := λ c x, by simp only [prod.smul_mk, map_smul] } @[simp] theorem prod_apply (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) (x : M) : prod f g x = (f x, g x) := rfl @[simp] theorem fst_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : (fst R M₂ M₃).comp (prod f g) = f := by ext; refl @[simp] theorem snd_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : (snd R M₂ M₃).comp (prod f g) = g := by ext; refl @[simp] theorem pair_fst_snd : prod (fst R M M₂) (snd R M M₂) = linear_map.id := by ext; refl section variables (R M M₂) /-- The left injection into a product is a linear map. -/ def inl : M →ₗ[R] M × M₂ := by refine ⟨prod.inl, _, _⟩; intros; simp [prod.inl] /-- The right injection into a product is a linear map. -/ def inr : M₂ →ₗ[R] M × M₂ := by refine ⟨prod.inr, _, _⟩; intros; simp [prod.inr] end @[simp] theorem inl_apply (x : M) : inl R M M₂ x = (x, 0) := rfl @[simp] theorem inr_apply (x : M₂) : inr R M M₂ x = (0, x) := rfl /-- The coprod function `λ x : M × M₂, f x.1 + g x.2` is a linear map. -/ def coprod (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : M × M₂ →ₗ[R] M₃ := { to_fun := λ x, f x.1 + g x.2, map_add' := λ x y, by simp only [map_add, prod.snd_add, prod.fst_add]; cc, map_smul' := λ x y, by simp only [smul_add, prod.smul_snd, prod.smul_fst, map_smul] } @[simp] theorem coprod_apply (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) (x : M) (y : M₂) : coprod f g (x, y) = f x + g y := rfl @[simp] theorem coprod_inl (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : (coprod f g).comp (inl R M M₂) = f := by ext; simp only [map_zero, add_zero, coprod_apply, inl_apply, comp_apply] @[simp] theorem coprod_inr (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : (coprod f g).comp (inr R M M₂) = g := by ext; simp only [map_zero, coprod_apply, inr_apply, zero_add, comp_apply] @[simp] theorem coprod_inl_inr : coprod (inl R M M₂) (inr R M M₂) = linear_map.id := by ext ⟨x, y⟩; simp only [prod.mk_add_mk, add_zero, id_apply, coprod_apply, inl_apply, inr_apply, zero_add] theorem fst_eq_coprod : fst R M M₂ = coprod linear_map.id 0 := by ext ⟨x, y⟩; simp theorem snd_eq_coprod : snd R M M₂ = coprod 0 linear_map.id := by ext ⟨x, y⟩; simp theorem inl_eq_prod : inl R M M₂ = prod linear_map.id 0 := rfl theorem inr_eq_prod : inr R M M₂ = prod 0 linear_map.id := rfl /-- `prod.map` of two linear maps. -/ def prod_map (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₄) : (M × M₂) →ₗ[R] (M₃ × M₄) := (f.comp (fst R M M₂)).prod (g.comp (snd R M M₂)) @[simp] theorem prod_map_apply (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₄) (x) : f.prod_map g x = (f x.1, g x.2) := rfl end add_comm_monoid section add_comm_group variables [semiring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] [add_comm_group M₄] variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] [semimodule R M₄] variables (f g : M →ₗ[R] M₂) include R /-- The negation of a linear map is linear. -/ instance : has_neg (M →ₗ[R] M₂) := ⟨λ f, ⟨λ b, - f b, by simp [add_comm], by simp⟩⟩ @[simp] lemma neg_apply (x : M) : (- f) x = - f x := rfl /-- The type of linear maps is an additive group. -/ instance : add_comm_group (M →ₗ[R] M₂) := by refine {zero := 0, add := (+), neg := has_neg.neg, ..}; intros; ext; simp [add_comm, add_left_comm] instance linear_map_apply_is_add_group_hom (a : M) : is_add_group_hom (λ f : M →ₗ[R] M₂, f a) := { map_add := λ f g, linear_map.add_apply f g a } @[simp] lemma sub_apply (x : M) : (f - g) x = f x - g x := rfl end add_comm_group section comm_semiring variables [comm_semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] variables (f g : M →ₗ[R] M₂) include R instance : has_scalar R (M →ₗ[R] M₂) := ⟨λ a f, ⟨λ b, a • f b, by simp [smul_add], by simp [smul_smul, mul_comm]⟩⟩ @[simp] lemma smul_apply (a : R) (x : M) : (a • f) x = a • f x := rfl instance : semimodule R (M →ₗ[R] M₂) := by refine { smul := (•), .. }; intros; ext; simp [smul_add, add_smul, smul_smul] /-- Composition by `f : M₂ → M₃` is a linear map from the space of linear maps `M → M₂` to the space of linear maps `M₂ → M₃`. -/ def comp_right (f : M₂ →ₗ[R] M₃) : (M →ₗ[R] M₂) →ₗ[R] (M →ₗ[R] M₃) := ⟨linear_map.comp f, λ _ _, linear_map.ext $ λ _, f.2 _ _, λ _ _, linear_map.ext $ λ _, f.3 _ _⟩ theorem smul_comp (g : M₂ →ₗ[R] M₃) (a : R) : (a • g).comp f = a • (g.comp f) := rfl theorem comp_smul (g : M₂ →ₗ[R] M₃) (a : R) : g.comp (a • f) = a • (g.comp f) := ext $ assume b, by rw [comp_apply, smul_apply, g.map_smul]; refl end comm_semiring section ring instance endomorphism_ring [ring R] [add_comm_group M] [semimodule R M] : ring (M →ₗ[R] M) := by refine {mul := (*), one := 1, ..linear_map.add_comm_group, ..}; { intros, apply linear_map.ext, simp {proj := ff} } end ring section comm_ring variables [comm_ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] /-- The family of linear maps `M₂ → M` parameterised by `f ∈ M₂ → R`, `x ∈ M`, is linear in `f`, `x`. -/ def smul_rightₗ : (M₂ →ₗ[R] R) →ₗ[R] M →ₗ[R] M₂ →ₗ[R] M := { to_fun := λ f, { to_fun := linear_map.smul_right f, map_add' := λ m m', by { ext, apply smul_add, }, map_smul' := λ c m, by { ext, apply smul_comm, } }, map_add' := λ f f', by { ext, apply add_smul, }, map_smul' := λ c f, by { ext, apply mul_smul, } } @[simp] lemma smul_rightₗ_apply (f : M₂ →ₗ[R] R) (x : M) (c : M₂) : (smul_rightₗ : (M₂ →ₗ R) →ₗ M →ₗ M₂ →ₗ M) f x c = (f c) • x := rfl end comm_ring end linear_map /-! ### Properties of submodules -/ namespace submodule section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] variables (p p' : submodule R M) (q q' : submodule R M₂) variables {r : R} {x y : M} open set instance : partial_order (submodule R M) := { le := λ p p', ∀ ⦃x⦄, x ∈ p → x ∈ p', ..partial_order.lift (coe : submodule R M → set M) coe_injective } variables {p p'} lemma le_def : p ≤ p' ↔ (p : set M) ⊆ p' := iff.rfl lemma le_def' : p ≤ p' ↔ ∀ x ∈ p, x ∈ p' := iff.rfl lemma lt_def : p < p' ↔ (p : set M) ⊂ p' := iff.rfl lemma not_le_iff_exists : ¬ (p ≤ p') ↔ ∃ x ∈ p, x ∉ p' := not_subset lemma exists_of_lt {p p' : submodule R M} : p < p' → ∃ x ∈ p', x ∉ p := exists_of_ssubset lemma lt_iff_le_and_exists : p < p' ↔ p ≤ p' ∧ ∃ x ∈ p', x ∉ p := by rw [lt_iff_le_not_le, not_le_iff_exists] /-- If two submodules `p` and `p'` satisfy `p ⊆ p'`, then `of_le p p'` is the linear map version of this inclusion. -/ def of_le (h : p ≤ p') : p →ₗ[R] p' := p.subtype.cod_restrict p' $ λ ⟨x, hx⟩, h hx @[simp] theorem coe_of_le (h : p ≤ p') (x : p) : (of_le h x : M) = x := rfl theorem of_le_apply (h : p ≤ p') (x : p) : of_le h x = ⟨x, h x.2⟩ := rfl variables (p p') lemma subtype_comp_of_le (p q : submodule R M) (h : p ≤ q) : q.subtype.comp (of_le h) = p.subtype := by { ext ⟨b, hb⟩, refl } /-- The set `{0}` is the bottom element of the lattice of submodules. -/ instance : has_bot (submodule R M) := ⟨{ carrier := {0}, smul_mem' := by simp { contextual := tt }, .. (⊥ : add_submonoid M)}⟩ instance inhabited' : inhabited (submodule R M) := ⟨⊥⟩ @[simp] lemma bot_coe : ((⊥ : submodule R M) : set M) = {0} := rfl section variables (R) @[simp] lemma mem_bot : x ∈ (⊥ : submodule R M) ↔ x = 0 := mem_singleton_iff end instance : order_bot (submodule R M) := { bot := ⊥, bot_le := λ p x, by simp {contextual := tt}, ..submodule.partial_order } /-- The universal set is the top element of the lattice of submodules. -/ instance : has_top (submodule R M) := ⟨{ carrier := univ, smul_mem' := λ _ _ _, trivial, .. (⊤ : add_submonoid M)}⟩ @[simp] lemma top_coe : ((⊤ : submodule R M) : set M) = univ := rfl @[simp] lemma mem_top : x ∈ (⊤ : submodule R M) := trivial lemma eq_bot_of_zero_eq_one (zero_eq_one : (0 : R) = 1) : p = ⊥ := by ext x; simp [semimodule.eq_zero_of_zero_eq_one x zero_eq_one] instance : order_top (submodule R M) := { top := ⊤, le_top := λ p x _, trivial, ..submodule.partial_order } instance : has_Inf (submodule R M) := ⟨λ S, { carrier := ⋂ s ∈ S, (s : set M), zero_mem' := by simp, add_mem' := by simp [add_mem] {contextual := tt}, smul_mem' := by simp [smul_mem] {contextual := tt} }⟩ private lemma Inf_le' {S : set (submodule R M)} {p} : p ∈ S → Inf S ≤ p := bInter_subset_of_mem private lemma le_Inf' {S : set (submodule R M)} {p} : (∀p' ∈ S, p ≤ p') → p ≤ Inf S := subset_bInter instance : has_inf (submodule R M) := ⟨λ p p', { carrier := p ∩ p', zero_mem' := by simp, add_mem' := by simp [add_mem] {contextual := tt}, smul_mem' := by simp [smul_mem] {contextual := tt} }⟩ instance : complete_lattice (submodule R M) := { sup := λ a b, Inf {x | a ≤ x ∧ b ≤ x}, le_sup_left := λ a b, le_Inf' $ λ x ⟨ha, hb⟩, ha, le_sup_right := λ a b, le_Inf' $ λ x ⟨ha, hb⟩, hb, sup_le := λ a b c h₁ h₂, Inf_le' ⟨h₁, h₂⟩, inf := (⊓), le_inf := λ a b c, subset_inter, inf_le_left := λ a b, inter_subset_left _ _, inf_le_right := λ a b, inter_subset_right _ _, Sup := λtt, Inf {t | ∀t'∈tt, t' ≤ t}, le_Sup := λ s p hs, le_Inf' $ λ p' hp', hp' _ hs, Sup_le := λ s p hs, Inf_le' hs, Inf := Inf, le_Inf := λ s a, le_Inf', Inf_le := λ s a, Inf_le', ..submodule.order_top, ..submodule.order_bot } instance add_comm_monoid_submodule : add_comm_monoid (submodule R M) := { add := (⊔), add_assoc := λ _ _ _, sup_assoc, zero := ⊥, zero_add := λ _, bot_sup_eq, add_zero := λ _, sup_bot_eq, add_comm := λ _ _, sup_comm } @[simp] lemma add_eq_sup (p q : submodule R M) : p + q = p ⊔ q := rfl @[simp] lemma zero_eq_bot : (0 : submodule R M) = ⊥ := rfl lemma eq_top_iff' {p : submodule R M} : p = ⊤ ↔ ∀ x, x ∈ p := eq_top_iff.trans ⟨λ h x, @h x trivial, λ h x _, h x⟩ @[simp] theorem inf_coe : (p ⊓ p' : set M) = p ∩ p' := rfl @[simp] theorem mem_inf {p p' : submodule R M} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl @[simp] theorem Inf_coe (P : set (submodule R M)) : (↑(Inf P) : set M) = ⋂ p ∈ P, ↑p := rfl @[simp] theorem infi_coe {ι} (p : ι → submodule R M) : (↑⨅ i, p i : set M) = ⋂ i, ↑(p i) := by rw [infi, Inf_coe]; ext a; simp; exact ⟨λ h i, h _ i rfl, λ h i x e, e ▸ h _⟩ @[simp] theorem mem_infi {ι} (p : ι → submodule R M) : x ∈ (⨅ i, p i) ↔ ∀ i, x ∈ p i := by rw [← mem_coe, infi_coe, mem_Inter]; refl theorem disjoint_def {p p' : submodule R M} : disjoint p p' ↔ ∀ x ∈ p, x ∈ p' → x = (0:M) := show (∀ x, x ∈ p ∧ x ∈ p' → x ∈ ({0} : set M)) ↔ _, by simp theorem mem_right_iff_eq_zero_of_disjoint {p p' : submodule R M} (h : disjoint p p') {x : p} : (x:M) ∈ p' ↔ x = 0 := ⟨λ hx, coe_eq_zero.1 $ disjoint_def.1 h x x.2 hx, λ h, h.symm ▸ p'.zero_mem⟩ theorem mem_left_iff_eq_zero_of_disjoint {p p' : submodule R M} (h : disjoint p p') {x : p'} : (x:M) ∈ p ↔ x = 0 := ⟨λ hx, coe_eq_zero.1 $ disjoint_def.1 h x hx x.2, λ h, h.symm ▸ p.zero_mem⟩ /-- The pushforward of a submodule `p ⊆ M` by `f : M → M₂` -/ def map (f : M →ₗ[R] M₂) (p : submodule R M) : submodule R M₂ := { carrier := f '' p, smul_mem' := by rintro a _ ⟨b, hb, rfl⟩; exact ⟨_, p.smul_mem _ hb, f.map_smul _ _⟩, .. p.to_add_submonoid.map f.to_add_monoid_hom } @[simp] lemma map_coe (f : M →ₗ[R] M₂) (p : submodule R M) : (map f p : set M₂) = f '' p := rfl @[simp] lemma mem_map {f : M →ₗ[R] M₂} {p : submodule R M} {x : M₂} : x ∈ map f p ↔ ∃ y, y ∈ p ∧ f y = x := iff.rfl theorem mem_map_of_mem {f : M →ₗ[R] M₂} {p : submodule R M} {r} (h : r ∈ p) : f r ∈ map f p := set.mem_image_of_mem _ h lemma map_id : map linear_map.id p = p := submodule.ext $ λ a, by simp lemma map_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) (p : submodule R M) : map (g.comp f) p = map g (map f p) := submodule.coe_injective $ by simp [map_coe]; rw ← image_comp lemma map_mono {f : M →ₗ[R] M₂} {p p' : submodule R M} : p ≤ p' → map f p ≤ map f p' := image_subset _ @[simp] lemma map_zero : map (0 : M →ₗ[R] M₂) p = ⊥ := have ∃ (x : M), x ∈ p := ⟨0, p.zero_mem⟩, ext $ by simp [this, eq_comm] /-- The pullback of a submodule `p ⊆ M₂` along `f : M → M₂` -/ def comap (f : M →ₗ[R] M₂) (p : submodule R M₂) : submodule R M := { carrier := f ⁻¹' p, smul_mem' := λ a x h, by simp [p.smul_mem _ h], .. p.to_add_submonoid.comap f.to_add_monoid_hom } @[simp] lemma comap_coe (f : M →ₗ[R] M₂) (p : submodule R M₂) : (comap f p : set M) = f ⁻¹' p := rfl @[simp] lemma mem_comap {f : M →ₗ[R] M₂} {p : submodule R M₂} : x ∈ comap f p ↔ f x ∈ p := iff.rfl lemma comap_id : comap linear_map.id p = p := submodule.coe_injective rfl lemma comap_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) (p : submodule R M₃) : comap (g.comp f) p = comap f (comap g p) := rfl lemma comap_mono {f : M →ₗ[R] M₂} {q q' : submodule R M₂} : q ≤ q' → comap f q ≤ comap f q' := preimage_mono lemma map_le_iff_le_comap {f : M →ₗ[R] M₂} {p : submodule R M} {q : submodule R M₂} : map f p ≤ q ↔ p ≤ comap f q := image_subset_iff lemma gc_map_comap (f : M →ₗ[R] M₂) : galois_connection (map f) (comap f) | p q := map_le_iff_le_comap @[simp] lemma map_bot (f : M →ₗ[R] M₂) : map f ⊥ = ⊥ := (gc_map_comap f).l_bot @[simp] lemma map_sup (f : M →ₗ[R] M₂) : map f (p ⊔ p') = map f p ⊔ map f p' := (gc_map_comap f).l_sup @[simp] lemma map_supr {ι : Sort*} (f : M →ₗ[R] M₂) (p : ι → submodule R M) : map f (⨆i, p i) = (⨆i, map f (p i)) := (gc_map_comap f).l_supr @[simp] lemma comap_top (f : M →ₗ[R] M₂) : comap f ⊤ = ⊤ := rfl @[simp] lemma comap_inf (f : M →ₗ[R] M₂) : comap f (q ⊓ q') = comap f q ⊓ comap f q' := rfl @[simp] lemma comap_infi {ι : Sort*} (f : M →ₗ[R] M₂) (p : ι → submodule R M₂) : comap f (⨅i, p i) = (⨅i, comap f (p i)) := (gc_map_comap f).u_infi @[simp] lemma comap_zero : comap (0 : M →ₗ[R] M₂) q = ⊤ := ext $ by simp lemma map_comap_le (f : M →ₗ[R] M₂) (q : submodule R M₂) : map f (comap f q) ≤ q := (gc_map_comap f).l_u_le _ lemma le_comap_map (f : M →ₗ[R] M₂) (p : submodule R M) : p ≤ comap f (map f p) := (gc_map_comap f).le_u_l _ --TODO(Mario): is there a way to prove this from order properties? lemma map_inf_eq_map_inf_comap {f : M →ₗ[R] M₂} {p : submodule R M} {p' : submodule R M₂} : map f p ⊓ p' = map f (p ⊓ comap f p') := le_antisymm (by rintro _ ⟨⟨x, h₁, rfl⟩, h₂⟩; exact ⟨_, ⟨h₁, h₂⟩, rfl⟩) (le_inf (map_mono inf_le_left) (map_le_iff_le_comap.2 inf_le_right)) lemma map_comap_subtype : map p.subtype (comap p.subtype p') = p ⊓ p' := ext $ λ x, ⟨by rintro ⟨⟨_, h₁⟩, h₂, rfl⟩; exact ⟨h₁, h₂⟩, λ ⟨h₁, h₂⟩, ⟨⟨_, h₁⟩, h₂, rfl⟩⟩ lemma eq_zero_of_bot_submodule : ∀(b : (⊥ : submodule R M)), b = 0 | ⟨b', hb⟩ := subtype.eq $ show b' = 0, from (mem_bot R).1 hb section variables (R) /-- The span of a set `s ⊆ M` is the smallest submodule of M that contains `s`. -/ def span (s : set M) : submodule R M := Inf {p | s ⊆ p} end variables {s t : set M} lemma mem_span : x ∈ span R s ↔ ∀ p : submodule R M, s ⊆ p → x ∈ p := mem_bInter_iff lemma subset_span : s ⊆ span R s := λ x h, mem_span.2 $ λ p hp, hp h lemma span_le {p} : span R s ≤ p ↔ s ⊆ p := ⟨subset.trans subset_span, λ ss x h, mem_span.1 h _ ss⟩ lemma span_mono (h : s ⊆ t) : span R s ≤ span R t := span_le.2 $ subset.trans h subset_span lemma span_eq_of_le (h₁ : s ⊆ p) (h₂ : p ≤ span R s) : span R s = p := le_antisymm (span_le.2 h₁) h₂ @[simp] lemma span_eq : span R (p : set M) = p := span_eq_of_le _ (subset.refl _) subset_span /-- An induction principle for span membership. If `p` holds for 0 and all elements of `s`, and is preserved under addition and scalar multiplication, then `p` holds for all elements of the span of `s`. -/ @[elab_as_eliminator] lemma span_induction {p : M → Prop} (h : x ∈ span R s) (Hs : ∀ x ∈ s, p x) (H0 : p 0) (H1 : ∀ x y, p x → p y → p (x + y)) (H2 : ∀ (a:R) x, p x → p (a • x)) : p x := (@span_le _ _ _ _ _ _ ⟨p, H0, H1, H2⟩).2 Hs h section variables (R M) /-- `span` forms a Galois insertion with the coercion from submodule to set. -/ protected def gi : galois_insertion (@span R M _ _ _) coe := { choice := λ s _, span R s, gc := λ s t, span_le, le_l_u := λ s, subset_span, choice_eq := λ s h, rfl } end @[simp] lemma span_empty : span R (∅ : set M) = ⊥ := (submodule.gi R M).gc.l_bot @[simp] lemma span_univ : span R (univ : set M) = ⊤ := eq_top_iff.2 $ le_def.2 $ subset_span lemma span_union (s t : set M) : span R (s ∪ t) = span R s ⊔ span R t := (submodule.gi R M).gc.l_sup lemma span_Union {ι} (s : ι → set M) : span R (⋃ i, s i) = ⨆ i, span R (s i) := (submodule.gi R M).gc.l_supr @[simp] theorem coe_supr_of_directed {ι} [hι : nonempty ι] (S : ι → submodule R M) (H : directed (≤) S) : ((supr S : submodule R M) : set M) = ⋃ i, S i := begin refine subset.antisymm _ (Union_subset $ le_supr S), suffices : (span R (⋃ i, (S i : set M)) : set M) ⊆ ⋃ (i : ι), ↑(S i), by simpa only [span_Union, span_eq] using this, refine (λ x hx, span_induction hx (λ _, id) _ _ _); simp only [mem_Union, exists_imp_distrib], { exact hι.elim (λ i, ⟨i, (S i).zero_mem⟩) }, { intros x y i hi j hj, rcases H i j with ⟨k, ik, jk⟩, exact ⟨k, add_mem _ (ik hi) (jk hj)⟩ }, { exact λ a x i hi, ⟨i, smul_mem _ a hi⟩ }, end lemma mem_supr_of_mem {ι : Sort*} {b : M} (p : ι → submodule R M) (i : ι) (h : b ∈ p i) : b ∈ (⨆i, p i) := have p i ≤ (⨆i, p i) := le_supr p i, @this b h @[simp] theorem mem_supr_of_directed {ι} [nonempty ι] (S : ι → submodule R M) (H : directed (≤) S) {x} : x ∈ supr S ↔ ∃ i, x ∈ S i := by { rw [← mem_coe, coe_supr_of_directed S H, mem_Union], refl } theorem mem_Sup_of_directed {s : set (submodule R M)} {z} (hs : s.nonempty) (hdir : directed_on (≤) s) : z ∈ Sup s ↔ ∃ y ∈ s, z ∈ y := begin haveI : nonempty s := hs.to_subtype, rw [Sup_eq_supr, supr_subtype', mem_supr_of_directed, subtype.exists], exact (directed_on_iff_directed _).1 hdir end section variables {p p'} lemma mem_sup : x ∈ p ⊔ p' ↔ ∃ (y ∈ p) (z ∈ p'), y + z = x := ⟨λ h, begin rw [← span_eq p, ← span_eq p', ← span_union] at h, apply span_induction h, { rintro y (h | h), { exact ⟨y, h, 0, by simp, by simp⟩ }, { exact ⟨0, by simp, y, h, by simp⟩ } }, { exact ⟨0, by simp, 0, by simp⟩ }, { rintro _ _ ⟨y₁, hy₁, z₁, hz₁, rfl⟩ ⟨y₂, hy₂, z₂, hz₂, rfl⟩, exact ⟨_, add_mem _ hy₁ hy₂, _, add_mem _ hz₁ hz₂, by simp [add_assoc]; cc⟩ }, { rintro a _ ⟨y, hy, z, hz, rfl⟩, exact ⟨_, smul_mem _ a hy, _, smul_mem _ a hz, by simp [smul_add]⟩ } end, by rintro ⟨y, hy, z, hz, rfl⟩; exact add_mem _ ((le_sup_left : p ≤ p ⊔ p') hy) ((le_sup_right : p' ≤ p ⊔ p') hz)⟩ lemma mem_sup' : x ∈ p ⊔ p' ↔ ∃ (y : p) (z : p'), (y:M) + z = x := mem_sup.trans $ by simp only [submodule.exists, coe_mk] end lemma mem_span_singleton_self (x : M) : x ∈ span R ({x} : set M) := subset_span (mem_def.mpr rfl) lemma mem_span_singleton {y : M} : x ∈ span R ({y} : set M) ↔ ∃ a:R, a • y = x := ⟨λ h, begin apply span_induction h, { rintro y (rfl|⟨⟨⟩⟩), exact ⟨1, by simp⟩ }, { exact ⟨0, by simp⟩ }, { rintro _ _ ⟨a, rfl⟩ ⟨b, rfl⟩, exact ⟨a + b, by simp [add_smul]⟩ }, { rintro a _ ⟨b, rfl⟩, exact ⟨a * b, by simp [smul_smul]⟩ } end, by rintro ⟨a, y, rfl⟩; exact smul_mem _ _ (subset_span $ by simp)⟩ lemma span_singleton_eq_range (y : M) : (span R ({y} : set M) : set M) = range ((• y) : R → M) := set.ext $ λ x, mem_span_singleton lemma disjoint_span_singleton {K E : Type*} [division_ring K] [add_comm_group E] [module K E] {s : submodule K E} {x : E} : disjoint s (span K {x}) ↔ (x ∈ s → x = 0) := begin refine disjoint_def.trans ⟨λ H hx, H x hx $ subset_span $ mem_singleton x, _⟩, assume H y hy hyx, obtain ⟨c, hc⟩ := mem_span_singleton.1 hyx, subst y, classical, by_cases hc : c = 0, by simp only [hc, zero_smul], rw [s.smul_mem_iff hc] at hy, rw [H hy, smul_zero] end lemma mem_span_insert {y} : x ∈ span R (insert y s) ↔ ∃ (a:R) (z ∈ span R s), x = a • y + z := begin simp only [← union_singleton, span_union, mem_sup, mem_span_singleton, exists_prop, exists_exists_eq_and], rw [exists_comm], simp only [eq_comm, add_comm, exists_and_distrib_left] end lemma span_insert_eq_span (h : x ∈ span R s) : span R (insert x s) = span R s := span_eq_of_le _ (set.insert_subset.mpr ⟨h, subset_span⟩) (span_mono $ subset_insert _ _) lemma span_span : span R (span R s : set M) = span R s := span_eq _ lemma span_eq_bot : span R (s : set M) = ⊥ ↔ ∀ x ∈ s, (x:M) = 0 := eq_bot_iff.trans ⟨ λ H x h, (mem_bot R).1 $ H $ subset_span h, λ H, span_le.2 (λ x h, (mem_bot R).2 $ H x h)⟩ lemma span_singleton_eq_bot : span R ({x} : set M) = ⊥ ↔ x = 0 := span_eq_bot.trans $ by simp @[simp] lemma span_image (f : M →ₗ[R] M₂) : span R (f '' s) = map f (span R s) := span_eq_of_le _ (image_subset _ subset_span) $ map_le_iff_le_comap.2 $ span_le.2 $ image_subset_iff.1 subset_span lemma linear_eq_on (s : set M) {f g : M →ₗ[R] M₂} (H : ∀x∈s, f x = g x) {x} (h : x ∈ span R s) : f x = g x := by apply span_induction h H; simp {contextual := tt} lemma supr_eq_span {ι : Sort w} (p : ι → submodule R M) : (⨆ (i : ι), p i) = submodule.span R (⋃ (i : ι), ↑(p i)) := le_antisymm (supr_le $ assume i, subset.trans (assume m hm, set.mem_Union.mpr ⟨i, hm⟩) subset_span) (span_le.mpr $ Union_subset_iff.mpr $ assume i m hm, mem_supr_of_mem _ i hm) lemma span_singleton_le_iff_mem (m : M) (p : submodule R M) : span R {m} ≤ p ↔ m ∈ p := by rw [span_le, singleton_subset_iff, mem_coe] lemma mem_supr {ι : Sort w} (p : ι → submodule R M) {m : M} : (m ∈ ⨆ i, p i) ↔ (∀ N, (∀ i, p i ≤ N) → m ∈ N) := begin rw [← span_singleton_le_iff_mem, le_supr_iff], simp only [span_singleton_le_iff_mem], end /-- The product of two submodules is a submodule. -/ def prod : submodule R (M × M₂) := { carrier := set.prod p q, smul_mem' := by rintro a ⟨x, y⟩ ⟨hx, hy⟩; exact ⟨smul_mem _ a hx, smul_mem _ a hy⟩, .. p.to_add_submonoid.prod q.to_add_submonoid } @[simp] lemma prod_coe : (prod p q : set (M × M₂)) = set.prod p q := rfl @[simp] lemma mem_prod {p : submodule R M} {q : submodule R M₂} {x : M × M₂} : x ∈ prod p q ↔ x.1 ∈ p ∧ x.2 ∈ q := set.mem_prod lemma span_prod_le (s : set M) (t : set M₂) : span R (set.prod s t) ≤ prod (span R s) (span R t) := span_le.2 $ set.prod_mono subset_span subset_span @[simp] lemma prod_top : (prod ⊤ ⊤ : submodule R (M × M₂)) = ⊤ := by ext; simp @[simp] lemma prod_bot : (prod ⊥ ⊥ : submodule R (M × M₂)) = ⊥ := by ext ⟨x, y⟩; simp [prod.zero_eq_mk] lemma prod_mono {p p' : submodule R M} {q q' : submodule R M₂} : p ≤ p' → q ≤ q' → prod p q ≤ prod p' q' := prod_mono @[simp] lemma prod_inf_prod : prod p q ⊓ prod p' q' = prod (p ⊓ p') (q ⊓ q') := coe_injective set.prod_inter_prod @[simp] lemma prod_sup_prod : prod p q ⊔ prod p' q' = prod (p ⊔ p') (q ⊔ q') := begin refine le_antisymm (sup_le (prod_mono le_sup_left le_sup_left) (prod_mono le_sup_right le_sup_right)) _, simp [le_def'], intros xx yy hxx hyy, rcases mem_sup.1 hxx with ⟨x, hx, x', hx', rfl⟩, rcases mem_sup.1 hyy with ⟨y, hy, y', hy', rfl⟩, refine mem_sup.2 ⟨(x, y), ⟨hx, hy⟩, (x', y'), ⟨hx', hy'⟩, rfl⟩ end end add_comm_monoid variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] variables (p p' : submodule R M) (q q' : submodule R M₂) variables {r : R} {x y : M} open set lemma mem_span_insert' {y} {s : set M} : x ∈ span R (insert y s) ↔ ∃(a:R), x + a • y ∈ span R s := begin rw mem_span_insert, split, { rintro ⟨a, z, hz, rfl⟩, exact ⟨-a, by simp [hz, add_assoc]⟩ }, { rintro ⟨a, h⟩, exact ⟨-a, _, h, by simp [add_comm, add_left_comm]⟩ } end -- TODO(Mario): Factor through add_subgroup /-- The equivalence relation associated to a submodule `p`, defined by `x ≈ y` iff `y - x ∈ p`. -/ def quotient_rel : setoid M := ⟨λ x y, x - y ∈ p, λ x, by simp, λ x y h, by simpa using neg_mem _ h, λ x y z h₁ h₂, by simpa [sub_eq_add_neg, add_left_comm, add_assoc] using add_mem _ h₁ h₂⟩ /-- The quotient of a module `M` by a submodule `p ⊆ M`. -/ def quotient : Type* := quotient (quotient_rel p) namespace quotient /-- Map associating to an element of `M` the corresponding element of `M/p`, when `p` is a submodule of `M`. -/ def mk {p : submodule R M} : M → quotient p := quotient.mk' @[simp] theorem mk_eq_mk {p : submodule R M} (x : M) : (quotient.mk x : quotient p) = mk x := rfl @[simp] theorem mk'_eq_mk {p : submodule R M} (x : M) : (quotient.mk' x : quotient p) = mk x := rfl @[simp] theorem quot_mk_eq_mk {p : submodule R M} (x : M) : (quot.mk _ x : quotient p) = mk x := rfl protected theorem eq {x y : M} : (mk x : quotient p) = mk y ↔ x - y ∈ p := quotient.eq' instance : has_zero (quotient p) := ⟨mk 0⟩ instance : inhabited (quotient p) := ⟨0⟩ @[simp] theorem mk_zero : mk 0 = (0 : quotient p) := rfl @[simp] theorem mk_eq_zero : (mk x : quotient p) = 0 ↔ x ∈ p := by simpa using (quotient.eq p : mk x = 0 ↔ _) instance : has_add (quotient p) := ⟨λ a b, quotient.lift_on₂' a b (λ a b, mk (a + b)) $ λ a₁ a₂ b₁ b₂ h₁ h₂, (quotient.eq p).2 $ by simpa [sub_eq_add_neg, add_left_comm, add_comm] using add_mem p h₁ h₂⟩ @[simp] theorem mk_add : (mk (x + y) : quotient p) = mk x + mk y := rfl instance : has_neg (quotient p) := ⟨λ a, quotient.lift_on' a (λ a, mk (-a)) $ λ a b h, (quotient.eq p).2 $ by simpa using neg_mem p h⟩ @[simp] theorem mk_neg : (mk (-x) : quotient p) = -mk x := rfl instance : add_comm_group (quotient p) := by refine {zero := 0, add := (+), neg := has_neg.neg, ..}; repeat {rintro ⟨⟩}; simp [-mk_zero, (mk_zero p).symm, -mk_add, (mk_add p).symm, -mk_neg, (mk_neg p).symm]; cc instance : has_scalar R (quotient p) := ⟨λ a x, quotient.lift_on' x (λ x, mk (a • x)) $ λ x y h, (quotient.eq p).2 $ by simpa [smul_sub] using smul_mem p a h⟩ @[simp] theorem mk_smul : (mk (r • x) : quotient p) = r • mk x := rfl instance : semimodule R (quotient p) := semimodule.of_core $ by refine {smul := (•), ..}; repeat {rintro ⟨⟩ <|> intro}; simp [smul_add, add_smul, smul_smul, -mk_add, (mk_add p).symm, -mk_smul, (mk_smul p).symm] end quotient lemma quot_hom_ext ⦃f g : quotient p →ₗ[R] M₂⦄ (h : ∀ x, f (quotient.mk x) = g (quotient.mk x)) : f = g := linear_map.ext $ λ x, quotient.induction_on' x h end submodule namespace submodule variables [field K] variables [add_comm_group V] [vector_space K V] variables [add_comm_group V₂] [vector_space K V₂] lemma comap_smul (f : V →ₗ[K] V₂) (p : submodule K V₂) (a : K) (h : a ≠ 0) : p.comap (a • f) = p.comap f := by ext b; simp only [submodule.mem_comap, p.smul_mem_iff h, linear_map.smul_apply] lemma map_smul (f : V →ₗ[K] V₂) (p : submodule K V) (a : K) (h : a ≠ 0) : p.map (a • f) = p.map f := le_antisymm begin rw [map_le_iff_le_comap, comap_smul f _ a h, ← map_le_iff_le_comap], exact le_refl _ end begin rw [map_le_iff_le_comap, ← comap_smul f _ a h, ← map_le_iff_le_comap], exact le_refl _ end lemma comap_smul' (f : V →ₗ[K] V₂) (p : submodule K V₂) (a : K) : p.comap (a • f) = (⨅ h : a ≠ 0, p.comap f) := by classical; by_cases a = 0; simp [h, comap_smul] lemma map_smul' (f : V →ₗ[K] V₂) (p : submodule K V) (a : K) : p.map (a • f) = (⨆ h : a ≠ 0, p.map f) := by classical; by_cases a = 0; simp [h, map_smul] end submodule /-! ### Properties of linear maps -/ namespace linear_map section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] include R open submodule @[simp] lemma finsupp_sum {γ} [has_zero γ] (f : M →ₗ[R] M₂) {t : ι →₀ γ} {g : ι → γ → M} : f (t.sum g) = t.sum (λi d, f (g i d)) := f.map_sum theorem map_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (h p') : submodule.map (cod_restrict p f h) p' = comap p.subtype (p'.map f) := submodule.ext $ λ ⟨x, hx⟩, by simp [subtype.coe_ext] theorem comap_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (hf p') : submodule.comap (cod_restrict p f hf) p' = submodule.comap f (map p.subtype p') := submodule.ext $ λ x, ⟨λ h, ⟨⟨_, hf x⟩, h, rfl⟩, by rintro ⟨⟨_, _⟩, h, ⟨⟩⟩; exact h⟩ /-- The range of a linear map `f : M → M₂` is a submodule of `M₂`. -/ def range (f : M →ₗ[R] M₂) : submodule R M₂ := map f ⊤ theorem range_coe (f : M →ₗ[R] M₂) : (range f : set M₂) = set.range f := set.image_univ @[simp] theorem mem_range {f : M →ₗ[R] M₂} : ∀ {x}, x ∈ range f ↔ ∃ y, f y = x := set.ext_iff.1 (range_coe f) theorem mem_range_self (f : M →ₗ[R] M₂) (x : M) : f x ∈ f.range := mem_range.2 ⟨x, rfl⟩ @[simp] theorem range_id : range (linear_map.id : M →ₗ[R] M) = ⊤ := map_id _ theorem range_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : range (g.comp f) = map g (range f) := map_comp _ _ _ theorem range_comp_le_range (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : range (g.comp f) ≤ range g := by rw range_comp; exact map_mono le_top theorem range_eq_top {f : M →ₗ[R] M₂} : range f = ⊤ ↔ surjective f := by rw [submodule.ext'_iff, range_coe, top_coe, set.range_iff_surjective] lemma range_le_iff_comap {f : M →ₗ[R] M₂} {p : submodule R M₂} : range f ≤ p ↔ comap f p = ⊤ := by rw [range, map_le_iff_le_comap, eq_top_iff] lemma map_le_range {f : M →ₗ[R] M₂} {p : submodule R M} : map f p ≤ range f := map_mono le_top lemma range_coprod (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : (f.coprod g).range = f.range ⊔ g.range := submodule.ext $ λ x, by simp [mem_sup] lemma sup_range_inl_inr : (inl R M M₂).range ⊔ (inr R M M₂).range = ⊤ := begin refine eq_top_iff'.2 (λ x, mem_sup.2 _), rcases x with ⟨x₁, x₂⟩ , have h₁ : prod.mk x₁ (0 : M₂) ∈ (inl R M M₂).range, by simp, have h₂ : prod.mk (0 : M) x₂ ∈ (inr R M M₂).range, by simp, use [⟨x₁, 0⟩, h₁, ⟨0, x₂⟩, h₂], simp end /-- Restrict the codomain of a linear map `f` to `f.range`. -/ @[reducible] def range_restrict (f : M →ₗ[R] M₂) : M →ₗ[R] f.range := f.cod_restrict f.range f.mem_range_self section variables (R) (M) /-- Given an element `x` of a module `M` over `R`, the natural map from `R` to scalar multiples of `x`.-/ def to_span_singleton (x : M) : R →ₗ[R] M := linear_map.id.smul_right x /-- The range of `to_span_singleton x` is the span of `x`.-/ lemma span_singleton_eq_range (x : M) : span R {x} = (to_span_singleton R M x).range := submodule.ext $ λ y, by {refine iff.trans _ mem_range.symm, exact mem_span_singleton } lemma to_span_singleton_one (x : M) : to_span_singleton R M x 1 = x := one_smul _ _ end /-- The kernel of a linear map `f : M → M₂` is defined to be `comap f ⊥`. This is equivalent to the set of `x : M` such that `f x = 0`. The kernel is a submodule of `M`. -/ def ker (f : M →ₗ[R] M₂) : submodule R M := comap f ⊥ @[simp] theorem mem_ker {f : M →ₗ[R] M₂} {y} : y ∈ ker f ↔ f y = 0 := mem_bot R @[simp] theorem ker_id : ker (linear_map.id : M →ₗ[R] M) = ⊥ := rfl @[simp] theorem map_coe_ker (f : M →ₗ[R] M₂) (x : ker f) : f x = 0 := mem_ker.1 x.2 theorem ker_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : ker (g.comp f) = comap f (ker g) := rfl theorem ker_le_ker_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : ker f ≤ ker (g.comp f) := by rw ker_comp; exact comap_mono bot_le theorem disjoint_ker {f : M →ₗ[R] M₂} {p : submodule R M} : disjoint p (ker f) ↔ ∀ x ∈ p, f x = 0 → x = 0 := by simp [disjoint_def] lemma disjoint_inl_inr : disjoint (inl R M M₂).range (inr R M M₂).range := by simp [disjoint_def, @eq_comm M 0, @eq_comm M₂ 0] {contextual := tt}; intros; refl theorem ker_eq_bot' {f : M →ₗ[R] M₂} : ker f = ⊥ ↔ (∀ m, f m = 0 → m = 0) := have h : (∀ m ∈ (⊤ : submodule R M), f m = 0 → m = 0) ↔ (∀ m, f m = 0 → m = 0), from ⟨λ h m, h m mem_top, λ h m _, h m⟩, by simpa [h, disjoint] using @disjoint_ker _ _ _ _ _ _ _ _ f ⊤ lemma le_ker_iff_map {f : M →ₗ[R] M₂} {p : submodule R M} : p ≤ ker f ↔ map f p = ⊥ := by rw [ker, eq_bot_iff, map_le_iff_le_comap] lemma ker_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (hf) : ker (cod_restrict p f hf) = ker f := by rw [ker, comap_cod_restrict, map_bot]; refl lemma range_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (hf) : range (cod_restrict p f hf) = comap p.subtype f.range := map_cod_restrict _ _ _ _ lemma map_comap_eq (f : M →ₗ[R] M₂) (q : submodule R M₂) : map f (comap f q) = range f ⊓ q := le_antisymm (le_inf (map_mono le_top) (map_comap_le _ _)) $ by rintro _ ⟨⟨x, _, rfl⟩, hx⟩; exact ⟨x, hx, rfl⟩ lemma map_comap_eq_self {f : M →ₗ[R] M₂} {q : submodule R M₂} (h : q ≤ range f) : map f (comap f q) = q := by rwa [map_comap_eq, inf_eq_right] @[simp] theorem ker_zero : ker (0 : M →ₗ[R] M₂) = ⊤ := eq_top_iff'.2 $ λ x, by simp @[simp] theorem range_zero : range (0 : M →ₗ[R] M₂) = ⊥ := submodule.map_zero _ theorem ker_eq_top {f : M →ₗ[R] M₂} : ker f = ⊤ ↔ f = 0 := ⟨λ h, ext $ λ x, mem_ker.1 $ h.symm ▸ trivial, λ h, h.symm ▸ ker_zero⟩ lemma range_le_bot_iff (f : M →ₗ[R] M₂) : range f ≤ ⊥ ↔ f = 0 := by rw [range_le_iff_comap]; exact ker_eq_top lemma range_le_ker_iff {f : M →ₗ[R] M₂} {g : M₂ →ₗ[R] M₃} : range f ≤ ker g ↔ g.comp f = 0 := ⟨λ h, ker_eq_top.1 $ eq_top_iff'.2 $ λ x, h $ mem_map_of_mem trivial, λ h x hx, mem_ker.2 $ exists.elim hx $ λ y ⟨_, hy⟩, by rw [←hy, ←comp_apply, h, zero_apply]⟩ theorem comap_le_comap_iff {f : M →ₗ[R] M₂} (hf : range f = ⊤) {p p'} : comap f p ≤ comap f p' ↔ p ≤ p' := ⟨λ H x hx, by rcases range_eq_top.1 hf x with ⟨y, hy, rfl⟩; exact H hx, comap_mono⟩ theorem comap_injective {f : M →ₗ[R] M₂} (hf : range f = ⊤) : injective (comap f) := λ p p' h, le_antisymm ((comap_le_comap_iff hf).1 (le_of_eq h)) ((comap_le_comap_iff hf).1 (ge_of_eq h)) theorem map_coprod_prod (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) (p : submodule R M) (q : submodule R M₂) : map (coprod f g) (p.prod q) = map f p ⊔ map g q := begin refine le_antisymm _ (sup_le (map_le_iff_le_comap.2 _) (map_le_iff_le_comap.2 _)), { rw le_def', rintro _ ⟨x, ⟨h₁, h₂⟩, rfl⟩, exact mem_sup.2 ⟨_, ⟨_, h₁, rfl⟩, _, ⟨_, h₂, rfl⟩, rfl⟩ }, { exact λ x hx, ⟨(x, 0), by simp [hx]⟩ }, { exact λ x hx, ⟨(0, x), by simp [hx]⟩ } end theorem comap_prod_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) (p : submodule R M₂) (q : submodule R M₃) : comap (prod f g) (p.prod q) = comap f p ⊓ comap g q := submodule.ext $ λ x, iff.rfl theorem prod_eq_inf_comap (p : submodule R M) (q : submodule R M₂) : p.prod q = p.comap (linear_map.fst R M M₂) ⊓ q.comap (linear_map.snd R M M₂) := submodule.ext $ λ x, iff.rfl theorem prod_eq_sup_map (p : submodule R M) (q : submodule R M₂) : p.prod q = p.map (linear_map.inl R M M₂) ⊔ q.map (linear_map.inr R M M₂) := by rw [← map_coprod_prod, coprod_inl_inr, map_id] lemma span_inl_union_inr {s : set M} {t : set M₂} : span R (prod.inl '' s ∪ prod.inr '' t) = (span R s).prod (span R t) := by rw [span_union, prod_eq_sup_map, ← span_image, ← span_image]; refl @[simp] lemma ker_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : ker (prod f g) = ker f ⊓ ker g := by rw [ker, ← prod_bot, comap_prod_prod]; refl lemma range_prod_le (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : range (prod f g) ≤ (range f).prod (range g) := begin simp only [le_def', prod_apply, mem_range, mem_coe, mem_prod, exists_imp_distrib], rintro _ x rfl, exact ⟨⟨x, rfl⟩, ⟨x, rfl⟩⟩ end theorem ker_eq_bot_of_injective {f : M →ₗ[R] M₂} (hf : injective f) : ker f = ⊥ := begin have : disjoint ⊤ f.ker, by { rw [disjoint_ker, ← map_zero f], exact λ x hx H, hf H }, simpa [disjoint] end end add_comm_monoid section add_comm_group variables [semiring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] include R open submodule lemma comap_map_eq (f : M →ₗ[R] M₂) (p : submodule R M) : comap f (map f p) = p ⊔ ker f := begin refine le_antisymm _ (sup_le (le_comap_map _ _) (comap_mono bot_le)), rintro x ⟨y, hy, e⟩, exact mem_sup.2 ⟨y, hy, x - y, by simpa using sub_eq_zero.2 e.symm, by simp⟩ end lemma comap_map_eq_self {f : M →ₗ[R] M₂} {p : submodule R M} (h : ker f ≤ p) : comap f (map f p) = p := by rw [comap_map_eq, sup_of_le_left h] theorem map_le_map_iff (f : M →ₗ[R] M₂) {p p'} : map f p ≤ map f p' ↔ p ≤ p' ⊔ ker f := by rw [map_le_iff_le_comap, comap_map_eq] theorem map_le_map_iff' {f : M →ₗ[R] M₂} (hf : ker f = ⊥) {p p'} : map f p ≤ map f p' ↔ p ≤ p' := by rw [map_le_map_iff, hf, sup_bot_eq] theorem map_injective {f : M →ₗ[R] M₂} (hf : ker f = ⊥) : injective (map f) := λ p p' h, le_antisymm ((map_le_map_iff' hf).1 (le_of_eq h)) ((map_le_map_iff' hf).1 (ge_of_eq h)) theorem map_eq_top_iff {f : M →ₗ[R] M₂} (hf : range f = ⊤) {p : submodule R M} : p.map f = ⊤ ↔ p ⊔ f.ker = ⊤ := by simp_rw [← top_le_iff, ← hf, range, map_le_map_iff] end add_comm_group section ring variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] include R open submodule theorem sub_mem_ker_iff {f : M →ₗ[R] M₂} {x y} : x - y ∈ f.ker ↔ f x = f y := by rw [mem_ker, map_sub, sub_eq_zero] theorem disjoint_ker' {f : M →ₗ[R] M₂} {p : submodule R M} : disjoint p (ker f) ↔ ∀ x y ∈ p, f x = f y → x = y := disjoint_ker.trans ⟨λ H x y hx hy h, eq_of_sub_eq_zero $ H _ (sub_mem _ hx hy) (by simp [h]), λ H x h₁ h₂, H x 0 h₁ (zero_mem _) (by simpa using h₂)⟩ theorem inj_of_disjoint_ker {f : M →ₗ[R] M₂} {p : submodule R M} {s : set M} (h : s ⊆ p) (hd : disjoint p (ker f)) : ∀ x y ∈ s, f x = f y → x = y := λ x y hx hy, disjoint_ker'.1 hd _ _ (h hx) (h hy) theorem ker_eq_bot {f : M →ₗ[R] M₂} : ker f = ⊥ ↔ injective f := by simpa [disjoint] using @disjoint_ker' _ _ _ _ _ _ _ _ f ⊤ /-- If the union of the kernels `ker f` and `ker g` spans the domain, then the range of `prod f g` is equal to the product of `range f` and `range g`. -/ lemma range_prod_eq {f : M →ₗ[R] M₂} {g : M →ₗ[R] M₃} (h : ker f ⊔ ker g = ⊤) : range (prod f g) = (range f).prod (range g) := begin refine le_antisymm (f.range_prod_le g) _, simp only [le_def', prod_apply, mem_range, mem_coe, mem_prod, exists_imp_distrib, and_imp, prod.forall], rintros _ _ x rfl y rfl, simp only [prod.mk.inj_iff, ← sub_mem_ker_iff], have : y - x ∈ ker f ⊔ ker g, { simp only [h, mem_top] }, rcases mem_sup.1 this with ⟨x', hx', y', hy', H⟩, refine ⟨x' + x, _, _⟩, { rwa add_sub_cancel }, { rwa [← eq_sub_iff_add_eq.1 H, add_sub_add_right_eq_sub, ← neg_mem_iff, neg_sub, add_sub_cancel'] } end end ring section field variables [field K] variables [add_comm_group V] [vector_space K V] variables [add_comm_group V₂] [vector_space K V₂] lemma ker_smul (f : V →ₗ[K] V₂) (a : K) (h : a ≠ 0) : ker (a • f) = ker f := submodule.comap_smul f _ a h lemma ker_smul' (f : V →ₗ[K] V₂) (a : K) : ker (a • f) = ⨅(h : a ≠ 0), ker f := submodule.comap_smul' f _ a lemma range_smul (f : V →ₗ[K] V₂) (a : K) (h : a ≠ 0) : range (a • f) = range f := submodule.map_smul f _ a h lemma range_smul' (f : V →ₗ[K] V₂) (a : K) : range (a • f) = ⨆(h : a ≠ 0), range f := submodule.map_smul' f _ a end field end linear_map lemma submodule.sup_eq_range [semiring R] [add_comm_monoid M] [semimodule R M] (p q : submodule R M) : p ⊔ q = (p.subtype.coprod q.subtype).range := submodule.ext $ λ x, by simp [submodule.mem_sup, submodule.exists] namespace is_linear_map lemma is_linear_map_add [semiring R] [add_comm_monoid M] [semimodule R M] : is_linear_map R (λ (x : M × M), x.1 + x.2) := begin apply is_linear_map.mk, { intros x y, simp, cc }, { intros x y, simp [smul_add] } end lemma is_linear_map_sub {R M : Type*} [semiring R] [add_comm_group M] [semimodule R M]: is_linear_map R (λ (x : M × M), x.1 - x.2) := begin apply is_linear_map.mk, { intros x y, simp [add_comm, add_left_comm, sub_eq_add_neg] }, { intros x y, simp [smul_sub] } end end is_linear_map namespace submodule section add_comm_monoid variables {T : semiring R} [add_comm_monoid M] [add_comm_monoid M₂] [semimodule R M] [semimodule R M₂] variables (p p' : submodule R M) (q : submodule R M₂) include T open linear_map @[simp] theorem map_top (f : M →ₗ[R] M₂) : map f ⊤ = range f := rfl @[simp] theorem comap_bot (f : M →ₗ[R] M₂) : comap f ⊥ = ker f := rfl @[simp] theorem ker_subtype : p.subtype.ker = ⊥ := ker_eq_bot_of_injective $ λ x y, subtype.eq' @[simp] theorem range_subtype : p.subtype.range = p := by simpa using map_comap_subtype p ⊤ lemma map_subtype_le (p' : submodule R p) : map p.subtype p' ≤ p := by simpa using (map_mono le_top : map p.subtype p' ≤ p.subtype.range) /-- Under the canonical linear map from a submodule `p` to the ambient space `M`, the image of the maximal submodule of `p` is just `p `. -/ @[simp] lemma map_subtype_top : map p.subtype (⊤ : submodule R p) = p := by simp @[simp] lemma comap_subtype_eq_top {p p' : submodule R M} : p'.comap p.subtype = ⊤ ↔ p ≤ p' := eq_top_iff.trans $ map_le_iff_le_comap.symm.trans $ by rw [map_subtype_top] @[simp] lemma comap_subtype_self : p.comap p.subtype = ⊤ := comap_subtype_eq_top.2 (le_refl _) @[simp] theorem ker_of_le (p p' : submodule R M) (h : p ≤ p') : (of_le h).ker = ⊥ := by rw [of_le, ker_cod_restrict, ker_subtype] lemma range_of_le (p q : submodule R M) (h : p ≤ q) : (of_le h).range = comap q.subtype p := by rw [← map_top, of_le, linear_map.map_cod_restrict, map_top, range_subtype] @[simp] theorem map_inl : p.map (inl R M M₂) = prod p ⊥ := by { ext ⟨x, y⟩, simp only [and.left_comm, eq_comm, mem_map, prod.mk.inj_iff, inl_apply, mem_bot, exists_eq_left', mem_prod] } @[simp] theorem map_inr : q.map (inr R M M₂) = prod ⊥ q := by ext ⟨x, y⟩; simp [and.left_comm, eq_comm] @[simp] theorem comap_fst : p.comap (fst R M M₂) = prod p ⊤ := by ext ⟨x, y⟩; simp @[simp] theorem comap_snd : q.comap (snd R M M₂) = prod ⊤ q := by ext ⟨x, y⟩; simp @[simp] theorem prod_comap_inl : (prod p q).comap (inl R M M₂) = p := by ext; simp @[simp] theorem prod_comap_inr : (prod p q).comap (inr R M M₂) = q := by ext; simp @[simp] theorem prod_map_fst : (prod p q).map (fst R M M₂) = p := by ext x; simp [(⟨0, zero_mem _⟩ : ∃ x, x ∈ q)] @[simp] theorem prod_map_snd : (prod p q).map (snd R M M₂) = q := by ext x; simp [(⟨0, zero_mem _⟩ : ∃ x, x ∈ p)] @[simp] theorem ker_inl : (inl R M M₂).ker = ⊥ := by rw [ker, ← prod_bot, prod_comap_inl] @[simp] theorem ker_inr : (inr R M M₂).ker = ⊥ := by rw [ker, ← prod_bot, prod_comap_inr] @[simp] theorem range_fst : (fst R M M₂).range = ⊤ := by rw [range, ← prod_top, prod_map_fst] @[simp] theorem range_snd : (snd R M M₂).range = ⊤ := by rw [range, ← prod_top, prod_map_snd] end add_comm_monoid section ring variables {T : ring R} [add_comm_group M] [add_comm_group M₂] [semimodule R M] [semimodule R M₂] variables (p p' : submodule R M) (q : submodule R M₂) include T open linear_map lemma disjoint_iff_comap_eq_bot {p q : submodule R M} : disjoint p q ↔ comap p.subtype q = ⊥ := by rw [eq_bot_iff, ← map_le_map_iff' p.ker_subtype, map_bot, map_comap_subtype, disjoint] /-- If `N ⊆ M` then submodules of `N` are the same as submodules of `M` contained in `N` -/ def map_subtype.order_iso : ((≤) : submodule R p → submodule R p → Prop) ≃o ((≤) : {p' : submodule R M // p' ≤ p} → {p' : submodule R M // p' ≤ p} → Prop) := { to_fun := λ p', ⟨map p.subtype p', map_subtype_le p _⟩, inv_fun := λ q, comap p.subtype q, left_inv := λ p', comap_map_eq_self $ by simp, right_inv := λ ⟨q, hq⟩, subtype.eq' $ by simp [map_comap_subtype p, inf_of_le_right hq], ord' := λ p₁ p₂, (map_le_map_iff' (ker_subtype p)).symm } /-- If `p ⊆ M` is a submodule, the ordering of submodules of `p` is embedded in the ordering of submodules of `M`. -/ def map_subtype.le_order_embedding : ((≤) : submodule R p → submodule R p → Prop) ≼o ((≤) : submodule R M → submodule R M → Prop) := (order_iso.to_order_embedding $ map_subtype.order_iso p).trans (subtype.order_embedding _ _) @[simp] lemma map_subtype_embedding_eq (p' : submodule R p) : map_subtype.le_order_embedding p p' = map p.subtype p' := rfl /-- If `p ⊆ M` is a submodule, the ordering of submodules of `p` is embedded in the ordering of submodules of `M`. -/ def map_subtype.lt_order_embedding : ((<) : submodule R p → submodule R p → Prop) ≼o ((<) : submodule R M → submodule R M → Prop) := (map_subtype.le_order_embedding p).lt_embedding_of_le_embedding /-- The map from a module `M` to the quotient of `M` by a submodule `p` as a linear map. -/ def mkq : M →ₗ[R] p.quotient := ⟨quotient.mk, by simp, by simp⟩ @[simp] theorem mkq_apply (x : M) : p.mkq x = quotient.mk x := rfl /-- The map from the quotient of `M` by a submodule `p` to `M₂` induced by a linear map `f : M → M₂` vanishing on `p`, as a linear map. -/ def liftq (f : M →ₗ[R] M₂) (h : p ≤ f.ker) : p.quotient →ₗ[R] M₂ := ⟨λ x, _root_.quotient.lift_on' x f $ λ a b (ab : a - b ∈ p), eq_of_sub_eq_zero $ by simpa using h ab, by rintro ⟨x⟩ ⟨y⟩; exact f.map_add x y, by rintro a ⟨x⟩; exact f.map_smul a x⟩ @[simp] theorem liftq_apply (f : M →ₗ[R] M₂) {h} (x : M) : p.liftq f h (quotient.mk x) = f x := rfl @[simp] theorem liftq_mkq (f : M →ₗ[R] M₂) (h) : (p.liftq f h).comp p.mkq = f := by ext; refl @[simp] theorem range_mkq : p.mkq.range = ⊤ := eq_top_iff'.2 $ by rintro ⟨x⟩; exact ⟨x, trivial, rfl⟩ @[simp] theorem ker_mkq : p.mkq.ker = p := by ext; simp lemma le_comap_mkq (p' : submodule R p.quotient) : p ≤ comap p.mkq p' := by simpa using (comap_mono bot_le : p.mkq.ker ≤ comap p.mkq p') @[simp] theorem mkq_map_self : map p.mkq p = ⊥ := by rw [eq_bot_iff, map_le_iff_le_comap, comap_bot, ker_mkq]; exact le_refl _ @[simp] theorem comap_map_mkq : comap p.mkq (map p.mkq p') = p ⊔ p' := by simp [comap_map_eq, sup_comm] @[simp] theorem map_mkq_eq_top : map p.mkq p' = ⊤ ↔ p ⊔ p' = ⊤ := by simp only [map_eq_top_iff p.range_mkq, sup_comm, ker_mkq] /-- The map from the quotient of `M` by submodule `p` to the quotient of `M₂` by submodule `q` along `f : M → M₂` is linear. -/ def mapq (f : M →ₗ[R] M₂) (h : p ≤ comap f q) : p.quotient →ₗ[R] q.quotient := p.liftq (q.mkq.comp f) $ by simpa [ker_comp] using h @[simp] theorem mapq_apply (f : M →ₗ[R] M₂) {h} (x : M) : mapq p q f h (quotient.mk x) = quotient.mk (f x) := rfl theorem mapq_mkq (f : M →ₗ[R] M₂) {h} : (mapq p q f h).comp p.mkq = q.mkq.comp f := by ext x; refl theorem comap_liftq (f : M →ₗ[R] M₂) (h) : q.comap (p.liftq f h) = (q.comap f).map (mkq p) := le_antisymm (by rintro ⟨x⟩ hx; exact ⟨_, hx, rfl⟩) (by rw [map_le_iff_le_comap, ← comap_comp, liftq_mkq]; exact le_refl _) theorem map_liftq (f : M →ₗ[R] M₂) (h) (q : submodule R (quotient p)) : q.map (p.liftq f h) = (q.comap p.mkq).map f := le_antisymm (by rintro _ ⟨⟨x⟩, hxq, rfl⟩; exact ⟨x, hxq, rfl⟩) (by rintro _ ⟨x, hxq, rfl⟩; exact ⟨quotient.mk x, hxq, rfl⟩) theorem ker_liftq (f : M →ₗ[R] M₂) (h) : ker (p.liftq f h) = (ker f).map (mkq p) := comap_liftq _ _ _ _ theorem range_liftq (f : M →ₗ[R] M₂) (h) : range (p.liftq f h) = range f := map_liftq _ _ _ _ theorem ker_liftq_eq_bot (f : M →ₗ[R] M₂) (h) (h' : ker f ≤ p) : ker (p.liftq f h) = ⊥ := by rw [ker_liftq, le_antisymm h h', mkq_map_self] /-- The correspondence theorem for modules: there is an order isomorphism between submodules of the quotient of `M` by `p`, and submodules of `M` larger than `p`. -/ def comap_mkq.order_iso : ((≤) : submodule R p.quotient → submodule R p.quotient → Prop) ≃o ((≤) : {p' : submodule R M // p ≤ p'} → {p' : submodule R M // p ≤ p'} → Prop) := { to_fun := λ p', ⟨comap p.mkq p', le_comap_mkq p _⟩, inv_fun := λ q, map p.mkq q, left_inv := λ p', map_comap_eq_self $ by simp, right_inv := λ ⟨q, hq⟩, subtype.eq' $ by simpa [comap_map_mkq p], ord' := λ p₁ p₂, (comap_le_comap_iff $ range_mkq _).symm } /-- The ordering on submodules of the quotient of `M` by `p` embeds into the ordering on submodules of `M`. -/ def comap_mkq.le_order_embedding : ((≤) : submodule R p.quotient → submodule R p.quotient → Prop) ≼o ((≤) : submodule R M → submodule R M → Prop) := (order_iso.to_order_embedding $ comap_mkq.order_iso p).trans (subtype.order_embedding _ _) @[simp] lemma comap_mkq_embedding_eq (p' : submodule R p.quotient) : comap_mkq.le_order_embedding p p' = comap p.mkq p' := rfl /-- The ordering on submodules of the quotient of `M` by `p` embeds into the ordering on submodules of `M`. -/ def comap_mkq.lt_order_embedding : ((<) : submodule R p.quotient → submodule R p.quotient → Prop) ≼o ((<) : submodule R M → submodule R M → Prop) := (comap_mkq.le_order_embedding p).lt_embedding_of_le_embedding end ring end submodule @[simp] lemma linear_map.range_range_restrict [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [semimodule R M] [semimodule R M₂] (f : M →ₗ[R] M₂) : f.range_restrict.range = ⊤ := by simp [f.range_cod_restrict _] /-! ### Linear equivalences -/ section set_option old_structure_cmd true /-- A linear equivalence is an invertible linear map. -/ @[nolint has_inhabited_instance] structure linear_equiv (R : Type u) (M : Type v) (M₂ : Type w) [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [semimodule R M] [semimodule R M₂] extends M →ₗ[R] M₂, M ≃ M₂ end infix ` ≃ₗ ` := linear_equiv _ notation M ` ≃ₗ[`:50 R `] ` M₂ := linear_equiv R M M₂ namespace linear_equiv section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] section variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] include R instance : has_coe (M ≃ₗ[R] M₂) (M →ₗ[R] M₂) := ⟨to_linear_map⟩ -- see Note [function coercion] instance : has_coe_to_fun (M ≃ₗ[R] M₂) := ⟨_, λ f, f.to_fun⟩ @[simp] lemma mk_apply {to_fun inv_fun map_add map_smul left_inv right_inv a} : (⟨to_fun, map_add, map_smul, inv_fun, left_inv, right_inv⟩ : M ≃ₗ[R] M₂) a = to_fun a := rfl lemma to_equiv_injective : function.injective (to_equiv : (M ≃ₗ[R] M₂) → M ≃ M₂) := λ ⟨_, _, _, _, _, _⟩ ⟨_, _, _, _, _, _⟩ h, linear_equiv.mk.inj_eq.mpr (equiv.mk.inj h) end section variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂} variables (e e' : M ≃ₗ[R] M₂) @[simp, norm_cast] theorem coe_coe : ((e : M →ₗ[R] M₂) : M → M₂) = (e : M → M₂) := rfl @[simp] lemma coe_to_equiv : ((e.to_equiv) : M → M₂) = (e : M → M₂) := rfl @[simp] lemma to_fun_apply {m : M} : e.to_fun m = e m := rfl section variables {e e'} @[ext] lemma ext (h : ∀ x, e x = e' x) : e = e' := to_equiv_injective (equiv.ext h) end section variables (M R) /-- The identity map is a linear equivalence. -/ @[refl] def refl [semimodule R M] : M ≃ₗ[R] M := { .. linear_map.id, .. equiv.refl M } end @[simp] lemma refl_apply [semimodule R M] (x : M) : refl R M x = x := rfl /-- Linear equivalences are symmetric. -/ @[symm] def symm : M₂ ≃ₗ[R] M := { .. e.to_linear_map.inverse e.inv_fun e.left_inv e.right_inv, .. e.to_equiv.symm } @[simp] lemma inv_fun_apply {m : M₂} : e.inv_fun m = e.symm m := rfl variables {semimodule_M₃ : semimodule R M₃} (e₁ : M ≃ₗ[R] M₂) (e₂ : M₂ ≃ₗ[R] M₃) /-- Linear equivalences are transitive. -/ @[trans] def trans : M ≃ₗ[R] M₃ := { .. e₂.to_linear_map.comp e₁.to_linear_map, .. e₁.to_equiv.trans e₂.to_equiv } /-- A linear equivalence is an additive equivalence. -/ def to_add_equiv : M ≃+ M₂ := { .. e } @[simp] lemma coe_to_add_equiv : ⇑(e.to_add_equiv) = e := rfl @[simp] theorem trans_apply (c : M) : (e₁.trans e₂) c = e₂ (e₁ c) := rfl @[simp] theorem apply_symm_apply (c : M₂) : e (e.symm c) = c := e.6 c @[simp] theorem symm_apply_apply (b : M) : e.symm (e b) = b := e.5 b @[simp] lemma symm_trans_apply (c : M₃) : (e₁.trans e₂).symm c = e₁.symm (e₂.symm c) := rfl @[simp] lemma trans_refl : e.trans (refl R M₂) = e := to_equiv_injective e.to_equiv.trans_refl @[simp] lemma refl_trans : (refl R M).trans e = e := to_equiv_injective e.to_equiv.refl_trans lemma symm_apply_eq {x y} : e.symm x = y ↔ x = e y := e.to_equiv.symm_apply_eq lemma eq_symm_apply {x y} : y = e.symm x ↔ e y = x := e.to_equiv.eq_symm_apply @[simp] theorem map_add (a b : M) : e (a + b) = e a + e b := e.map_add' a b @[simp] theorem map_zero : e 0 = 0 := e.to_linear_map.map_zero @[simp] theorem map_smul (c : R) (x : M) : e (c • x) = c • e x := e.map_smul' c x @[simp] theorem map_eq_zero_iff {x : M} : e x = 0 ↔ x = 0 := e.to_add_equiv.map_eq_zero_iff theorem map_ne_zero_iff {x : M} : e x ≠ 0 ↔ x ≠ 0 := e.to_add_equiv.map_ne_zero_iff @[simp] theorem symm_symm : e.symm.symm = e := by { cases e, refl } protected lemma bijective : function.bijective e := e.to_equiv.bijective protected lemma injective : function.injective e := e.to_equiv.injective protected lemma surjective : function.surjective e := e.to_equiv.surjective protected lemma image_eq_preimage (s : set M) : e '' s = e.symm ⁻¹' s := e.to_equiv.image_eq_preimage s lemma map_eq_comap {p : submodule R M} : (p.map e : submodule R M₂) = p.comap e.symm := submodule.coe_injective $ by simp [e.image_eq_preimage] end section prod variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂} variables {semimodule_M₃ : semimodule R M₃} {semimodule_M₄ : semimodule R M₄} variables (e₁ : M ≃ₗ[R] M₂) (e₂ : M₃ ≃ₗ[R] M₄) /-- Product of linear equivalences; the maps come from `equiv.prod_congr`. -/ protected def prod : (M × M₃) ≃ₗ[R] (M₂ × M₄) := { map_add' := λ x y, prod.ext (e₁.map_add _ _) (e₂.map_add _ _), map_smul' := λ c x, prod.ext (e₁.map_smul c _) (e₂.map_smul c _), .. equiv.prod_congr e₁.to_equiv e₂.to_equiv } lemma prod_symm : (e₁.prod e₂).symm = e₁.symm.prod e₂.symm := rfl @[simp] lemma prod_apply (p) : e₁.prod e₂ p = (e₁ p.1, e₂ p.2) := rfl @[simp, norm_cast] lemma coe_prod : (e₁.prod e₂ : (M × M₃) →ₗ[R] (M₂ × M₄)) = (e₁ : M →ₗ[R] M₂).prod_map (e₂ : M₃ →ₗ[R] M₄) := rfl end prod section uncurry variables (V V₂ R) /-- Linear equivalence between a curried and uncurried function. Differs from `tensor_product.curry`. -/ protected def uncurry : (V → V₂ → R) ≃ₗ[R] (V × V₂ → R) := { map_add' := λ _ _, by { ext ⟨⟩, refl }, map_smul' := λ _ _, by { ext ⟨⟩, refl }, .. equiv.arrow_arrow_equiv_prod_arrow _ _ _} @[simp] lemma coe_uncurry : ⇑(linear_equiv.uncurry R V V₂) = uncurry := rfl @[simp] lemma coe_uncurry_symm : ⇑(linear_equiv.uncurry R V V₂).symm = curry := rfl end uncurry section variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂} variables (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M) (e : M ≃ₗ[R] M₂) variables (p q : submodule R M) /-- Linear equivalence between two equal submodules. -/ def of_eq (h : p = q) : p ≃ₗ[R] q := { map_smul' := λ _ _, rfl, map_add' := λ _ _, rfl, .. equiv.set.of_eq (congr_arg _ h) } variables {p q} @[simp] lemma coe_of_eq_apply (h : p = q) (x : p) : (of_eq p q h x : M) = x := rfl @[simp] lemma of_eq_symm (h : p = q) : (of_eq p q h).symm = of_eq q p h.symm := rfl variable (p) /-- The top submodule of `M` is linearly equivalent to `M`. -/ def of_top (h : p = ⊤) : p ≃ₗ[R] M := { inv_fun := λ x, ⟨x, h.symm ▸ trivial⟩, left_inv := λ ⟨x, h⟩, rfl, right_inv := λ x, rfl, .. p.subtype } @[simp] theorem of_top_apply {h} (x : p) : of_top p h x = x := rfl @[simp] theorem coe_of_top_symm_apply {h} (x : M) : ((of_top p h).symm x : M) = x := rfl theorem of_top_symm_apply {h} (x : M) : (of_top p h).symm x = ⟨x, h.symm ▸ trivial⟩ := rfl /-- If a linear map has an inverse, it is a linear equivalence. -/ def of_linear (h₁ : f.comp g = linear_map.id) (h₂ : g.comp f = linear_map.id) : M ≃ₗ[R] M₂ := { inv_fun := g, left_inv := linear_map.ext_iff.1 h₂, right_inv := linear_map.ext_iff.1 h₁, ..f } @[simp] theorem of_linear_apply {h₁ h₂} (x : M) : of_linear f g h₁ h₂ x = f x := rfl @[simp] theorem of_linear_symm_apply {h₁ h₂} (x : M₂) : (of_linear f g h₁ h₂).symm x = g x := rfl @[simp] protected theorem range : (e : M →ₗ[R] M₂).range = ⊤ := linear_map.range_eq_top.2 e.to_equiv.surjective lemma eq_bot_of_equiv [semimodule R M₂] (e : p ≃ₗ[R] (⊥ : submodule R M₂)) : p = ⊥ := begin refine bot_unique (submodule.le_def'.2 $ assume b hb, (submodule.mem_bot R).2 _), rw [← p.mk_eq_zero hb, ← e.map_eq_zero_iff], apply submodule.eq_zero_of_bot_submodule end @[simp] protected theorem ker : (e : M →ₗ[R] M₂).ker = ⊥ := linear_map.ker_eq_bot_of_injective e.to_equiv.injective end end add_comm_monoid section add_comm_group variables [semiring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] [add_comm_group M₄] variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂} variables {semimodule_M₃ : semimodule R M₃} {semimodule_M₄ : semimodule R M₄} variables (e e₁ : M ≃ₗ[R] M₂) (e₂ : M₃ ≃ₗ[R] M₄) @[simp] theorem map_neg (a : M) : e (-a) = -e a := e.to_linear_map.map_neg a @[simp] theorem map_sub (a b : M) : e (a - b) = e a - e b := e.to_linear_map.map_sub a b /-- Equivalence given by a block lower diagonal matrix. `e₁` and `e₂` are diagonal square blocks, and `f` is a rectangular block below the diagonal. -/ protected def skew_prod (f : M →ₗ[R] M₄) : (M × M₃) ≃ₗ[R] M₂ × M₄ := { inv_fun := λ p : M₂ × M₄, (e₁.symm p.1, e₂.symm (p.2 - f (e₁.symm p.1))), left_inv := λ p, by simp, right_inv := λ p, by simp, .. ((e₁ : M →ₗ[R] M₂).comp (linear_map.fst R M M₃)).prod ((e₂ : M₃ →ₗ[R] M₄).comp (linear_map.snd R M M₃) + f.comp (linear_map.fst R M M₃)) } @[simp] lemma skew_prod_apply (f : M →ₗ[R] M₄) (x) : e₁.skew_prod e₂ f x = (e₁ x.1, e₂ x.2 + f x.1) := rfl @[simp] lemma skew_prod_symm_apply (f : M →ₗ[R] M₄) (x) : (e₁.skew_prod e₂ f).symm x = (e₁.symm x.1, e₂.symm (x.2 - f (e₁.symm x.1))) := rfl end add_comm_group section ring variables [ring R] [add_comm_group M] [add_comm_group M₂] variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂} variables (f : M →ₗ[R] M₂) (e : M ≃ₗ[R] M₂) /-- An `injective` linear map `f : M →ₗ[R] M₂` defines a linear equivalence between `M` and `f.range`. -/ noncomputable def of_injective (h : f.ker = ⊥) : M ≃ₗ[R] f.range := { .. (equiv.set.range f $ linear_map.ker_eq_bot.1 h).trans (equiv.set.of_eq f.range_coe.symm), .. f.cod_restrict f.range (λ x, f.mem_range_self x) } /-- A bijective linear map is a linear equivalence. Here, bijectivity is described by saying that the kernel of `f` is `{0}` and the range is the universal set. -/ noncomputable def of_bijective (hf₁ : f.ker = ⊥) (hf₂ : f.range = ⊤) : M ≃ₗ[R] M₂ := (of_injective f hf₁).trans (of_top _ hf₂) @[simp] theorem of_bijective_apply {hf₁ hf₂} (x : M) : of_bijective f hf₁ hf₂ x = f x := rfl end ring section comm_ring variables [comm_ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] open linear_map /-- Multiplying by a unit `a` of the ring `R` is a linear equivalence. -/ def smul_of_unit (a : units R) : M ≃ₗ[R] M := of_linear ((a:R) • 1 : M →ₗ M) (((a⁻¹ : units R) : R) • 1 : M →ₗ M) (by rw [smul_comp, comp_smul, smul_smul, units.mul_inv, one_smul]; refl) (by rw [smul_comp, comp_smul, smul_smul, units.inv_mul, one_smul]; refl) /-- A linear isomorphism between the domains and codomains of two spaces of linear maps gives a linear isomorphism between the two function spaces. -/ def arrow_congr {R M₁ M₂ M₂₁ M₂₂ : Sort*} [comm_ring R] [add_comm_group M₁] [add_comm_group M₂] [add_comm_group M₂₁] [add_comm_group M₂₂] [module R M₁] [module R M₂] [module R M₂₁] [module R M₂₂] (e₁ : M₁ ≃ₗ[R] M₂) (e₂ : M₂₁ ≃ₗ[R] M₂₂) : (M₁ →ₗ[R] M₂₁) ≃ₗ[R] (M₂ →ₗ[R] M₂₂) := { to_fun := λ f, (e₂ : M₂₁ →ₗ[R] M₂₂).comp $ f.comp e₁.symm, inv_fun := λ f, (e₂.symm : M₂₂ →ₗ[R] M₂₁).comp $ f.comp e₁, left_inv := λ f, by { ext x, simp }, right_inv := λ f, by { ext x, simp }, map_add' := λ f g, by { ext x, simp }, map_smul' := λ c f, by { ext x, simp } } @[simp] lemma arrow_congr_apply {R M₁ M₂ M₂₁ M₂₂ : Sort*} [comm_ring R] [add_comm_group M₁] [add_comm_group M₂] [add_comm_group M₂₁] [add_comm_group M₂₂] [module R M₁] [module R M₂] [module R M₂₁] [module R M₂₂] (e₁ : M₁ ≃ₗ[R] M₂) (e₂ : M₂₁ ≃ₗ[R] M₂₂) (f : M₁ →ₗ[R] M₂₁) (x : M₂) : arrow_congr e₁ e₂ f x = e₂ (f (e₁.symm x)) := rfl lemma arrow_congr_comp {N N₂ N₃ : Sort*} [add_comm_group N] [add_comm_group N₂] [add_comm_group N₃] [module R N] [module R N₂] [module R N₃] (e₁ : M ≃ₗ[R] N) (e₂ : M₂ ≃ₗ[R] N₂) (e₃ : M₃ ≃ₗ[R] N₃) (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : arrow_congr e₁ e₃ (g.comp f) = (arrow_congr e₂ e₃ g).comp (arrow_congr e₁ e₂ f) := by { ext, simp only [symm_apply_apply, arrow_congr_apply, linear_map.comp_apply], } lemma arrow_congr_trans {M₁ M₂ M₃ N₁ N₂ N₃ : Sort*} [add_comm_group M₁] [module R M₁] [add_comm_group M₂] [module R M₂] [add_comm_group M₃] [module R M₃] [add_comm_group N₁] [module R N₁] [add_comm_group N₂] [module R N₂] [add_comm_group N₃] [module R N₃] (e₁ : M₁ ≃ₗ[R] M₂) (e₂ : N₁ ≃ₗ[R] N₂) (e₃ : M₂ ≃ₗ[R] M₃) (e₄ : N₂ ≃ₗ[R] N₃) : (arrow_congr e₁ e₂).trans (arrow_congr e₃ e₄) = arrow_congr (e₁.trans e₃) (e₂.trans e₄) := rfl /-- If `M₂` and `M₃` are linearly isomorphic then the two spaces of linear maps from `M` into `M₂` and `M` into `M₃` are linearly isomorphic. -/ def congr_right (f : M₂ ≃ₗ[R] M₃) : (M →ₗ[R] M₂) ≃ₗ (M →ₗ M₃) := arrow_congr (linear_equiv.refl R M) f /-- If `M` and `M₂` are linearly isomorphic then the two spaces of linear maps from `M` and `M₂` to themselves are linearly isomorphic. -/ def conj (e : M ≃ₗ[R] M₂) : (module.End R M) ≃ₗ[R] (module.End R M₂) := arrow_congr e e @[simp] lemma conj_apply (e : M ≃ₗ[R] M₂) (f : module.End R M) (x : M₂) : (e.conj f) x = e (f (e.symm x)) := rfl @[simp] lemma conj_id (e : M ≃ₗ[R] M₂) : e.conj linear_map.id = linear_map.id := by { ext, rw [conj_apply, id_apply, id_apply, apply_symm_apply], } end comm_ring section field variables [field K] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module K M] [module K M₂] [module K M₃] variables (K) (M) open linear_map /-- Multiplying by a nonzero element `a` of the field `K` is a linear equivalence. -/ def smul_of_ne_zero (a : K) (ha : a ≠ 0) : M ≃ₗ[K] M := smul_of_unit $ units.mk0 a ha section noncomputable theory open_locale classical /-- Given a nonzero element `x` of a vector space `M` over a field `K`, the natural map from `K` to the span of `x`, with invertibility check to consider it as an isomorphism.-/ def to_span_nonzero_singleton (x : M) (h : x ≠ 0) : K ≃ₗ[K] (submodule.span K ({x} : set M)) := linear_equiv.trans ( linear_equiv.of_injective (to_span_singleton K M x) begin ext c, split, { intros hc, rw submodule.mem_bot, rw mem_ker at hc, by_contra hc', have : x = 0, calc x = c⁻¹ • (c • x) : by rw [← mul_smul, inv_mul_cancel hc', one_smul] ... = c⁻¹ • ((to_span_singleton K M x) c) : rfl ... = 0 : by rw [hc, smul_zero], tauto }, { rw [mem_ker, submodule.mem_bot], intros h, rw h, simp } end ) (of_eq (to_span_singleton K M x).range (submodule.span K {x}) (span_singleton_eq_range K M x).symm) lemma to_span_nonzero_singleton_one (x : M) (h : x ≠ 0) : to_span_nonzero_singleton K M x h 1 = (⟨x, submodule.mem_span_singleton_self x⟩ : submodule.span K ({x} : set M)) := begin apply submodule.coe_eq_coe.mp, have : ↑(to_span_nonzero_singleton K M x h 1) = to_span_singleton K M x 1 := rfl, rw [this, to_span_singleton_one, submodule.coe_mk], end /-- Given a nonzero element `x` of a vector space `M` over a field `K`, the natural map from the span of `x` to `K`.-/ abbreviation coord (x : M) (h : x ≠ 0) : (submodule.span K ({x} : set M)) ≃ₗ[K] K := (to_span_nonzero_singleton K M x h).symm lemma coord_self (x : M) (h : x ≠ 0) : (coord K M x h) ( ⟨x, submodule.mem_span_singleton_self x⟩ : submodule.span K ({x} : set M)) = 1 := by rw [← to_span_nonzero_singleton_one K M x h, symm_apply_apply] end end field end linear_equiv namespace submodule variables [ring R] [add_comm_group M] [module R M] variables (p : submodule R M) open linear_map /-- If `p = ⊥`, then `M / p ≃ₗ[R] M`. -/ def quot_equiv_of_eq_bot (hp : p = ⊥) : p.quotient ≃ₗ[R] M := linear_equiv.of_linear (p.liftq id $ hp.symm ▸ bot_le) p.mkq (liftq_mkq _ _ _) $ p.quot_hom_ext $ λ x, rfl @[simp] lemma quot_equiv_of_eq_bot_apply_mk (hp : p = ⊥) (x : M) : p.quot_equiv_of_eq_bot hp (quotient.mk x) = x := rfl @[simp] lemma quot_equiv_of_eq_bot_symm_apply (hp : p = ⊥) (x : M) : (p.quot_equiv_of_eq_bot hp).symm x = quotient.mk x := rfl @[simp] lemma coe_quot_equiv_of_eq_bot_symm (hp : p = ⊥) : ((p.quot_equiv_of_eq_bot hp).symm : M →ₗ[R] p.quotient) = p.mkq := rfl end submodule namespace submodule variables [comm_ring R] [add_comm_group M] [add_comm_group M₂] [module R M] [module R M₂] variables (p : submodule R M) (q : submodule R M₂) lemma comap_le_comap_smul (f : M →ₗ[R] M₂) (c : R) : comap f q ≤ comap (c • f) q := begin rw le_def', intros m h, change c • (f m) ∈ q, change f m ∈ q at h, apply q.smul_mem _ h, end lemma inf_comap_le_comap_add (f₁ f₂ : M →ₗ[R] M₂) : comap f₁ q ⊓ comap f₂ q ≤ comap (f₁ + f₂) q := begin rw le_def', intros m h, change f₁ m + f₂ m ∈ q, change f₁ m ∈ q ∧ f₂ m ∈ q at h, apply q.add_mem h.1 h.2, end /-- Given modules `M`, `M₂` over a commutative ring, together with submodules `p ⊆ M`, `q ⊆ M₂`, the set of maps $\{f ∈ Hom(M, M₂) | f(p) ⊆ q \}$ is a submodule of `Hom(M, M₂)`. -/ def compatible_maps : submodule R (M →ₗ[R] M₂) := { carrier := {f | p ≤ comap f q}, zero_mem' := by { change p ≤ comap 0 q, rw comap_zero, refine le_top, }, add_mem' := λ f₁ f₂ h₁ h₂, by { apply le_trans _ (inf_comap_le_comap_add q f₁ f₂), rw le_inf_iff, exact ⟨h₁, h₂⟩, }, smul_mem' := λ c f h, le_trans h (comap_le_comap_smul q f c), } /-- Given modules `M`, `M₂` over a commutative ring, together with submodules `p ⊆ M`, `q ⊆ M₂`, the natural map $\{f ∈ Hom(M, M₂) | f(p) ⊆ q \} \to Hom(M/p, M₂/q)$ is linear. -/ def mapq_linear : compatible_maps p q →ₗ[R] p.quotient →ₗ[R] q.quotient := { to_fun := λ f, mapq _ _ f.val f.property, map_add' := λ x y, by { ext m', apply quotient.induction_on' m', intros m, refl, }, map_smul' := λ c f, by { ext m', apply quotient.induction_on' m', intros m, refl, } } end submodule namespace equiv variables [semiring R] [add_comm_monoid M] [semimodule R M] [add_comm_monoid M₂] [semimodule R M₂] /-- An equivalence whose underlying function is linear is a linear equivalence. -/ def to_linear_equiv (e : M ≃ M₂) (h : is_linear_map R (e : M → M₂)) : M ≃ₗ[R] M₂ := { .. e, .. h.mk' e} end equiv namespace linear_map open submodule section isomorphism_laws variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] variables (f : M →ₗ[R] M₂) /-- The first isomorphism law for modules. The quotient of `M` by the kernel of `f` is linearly equivalent to the range of `f`. -/ noncomputable def quot_ker_equiv_range : f.ker.quotient ≃ₗ[R] f.range := (linear_equiv.of_injective (f.ker.liftq f $ le_refl _) $ submodule.ker_liftq_eq_bot _ _ _ (le_refl f.ker)).trans (linear_equiv.of_eq _ _ $ submodule.range_liftq _ _ _) @[simp] lemma quot_ker_equiv_range_apply_mk (x : M) : (f.quot_ker_equiv_range (submodule.quotient.mk x) : M₂) = f x := rfl @[simp] lemma quot_ker_equiv_range_symm_apply_image (x : M) (h : f x ∈ f.range) : f.quot_ker_equiv_range.symm ⟨f x, h⟩ = f.ker.mkq x := f.quot_ker_equiv_range.symm_apply_apply (f.ker.mkq x) /-- Canonical linear map from the quotient `p/(p ∩ p')` to `(p+p')/p'`, mapping `x + (p ∩ p')` to `x + p'`, where `p` and `p'` are submodules of an ambient module. -/ def quotient_inf_to_sup_quotient (p p' : submodule R M) : (comap p.subtype (p ⊓ p')).quotient →ₗ[R] (comap (p ⊔ p').subtype p').quotient := (comap p.subtype (p ⊓ p')).liftq ((comap (p ⊔ p').subtype p').mkq.comp (of_le le_sup_left)) begin rw [ker_comp, of_le, comap_cod_restrict, ker_mkq, map_comap_subtype], exact comap_mono (inf_le_inf_right _ le_sup_left) end /-- Second Isomorphism Law : the canonical map from `p/(p ∩ p')` to `(p+p')/p'` as a linear isomorphism. -/ noncomputable def quotient_inf_equiv_sup_quotient (p p' : submodule R M) : (comap p.subtype (p ⊓ p')).quotient ≃ₗ[R] (comap (p ⊔ p').subtype p').quotient := linear_equiv.of_bijective (quotient_inf_to_sup_quotient p p') begin rw [quotient_inf_to_sup_quotient, ker_liftq_eq_bot], rw [ker_comp, ker_mkq], exact λ ⟨x, hx1⟩ hx2, ⟨hx1, hx2⟩ end begin rw [quotient_inf_to_sup_quotient, range_liftq, eq_top_iff'], rintros ⟨x, hx⟩, rcases mem_sup.1 hx with ⟨y, hy, z, hz, rfl⟩, use [⟨y, hy⟩, trivial], apply (submodule.quotient.eq _).2, change y - (y + z) ∈ p', rwa [sub_add_eq_sub_sub, sub_self, zero_sub, neg_mem_iff] end @[simp] lemma coe_quotient_inf_to_sup_quotient (p p' : submodule R M) : ⇑(quotient_inf_to_sup_quotient p p') = quotient_inf_equiv_sup_quotient p p' := rfl @[simp] lemma quotient_inf_equiv_sup_quotient_apply_mk (p p' : submodule R M) (x : p) : quotient_inf_equiv_sup_quotient p p' (submodule.quotient.mk x) = submodule.quotient.mk (of_le (le_sup_left : p ≤ p ⊔ p') x) := rfl lemma quotient_inf_equiv_sup_quotient_symm_apply_left (p p' : submodule R M) (x : p ⊔ p') (hx : (x:M) ∈ p) : (quotient_inf_equiv_sup_quotient p p').symm (submodule.quotient.mk x) = submodule.quotient.mk ⟨x, hx⟩ := (linear_equiv.symm_apply_eq _).2 $ by simp [of_le_apply] @[simp] lemma quotient_inf_equiv_sup_quotient_symm_apply_eq_zero_iff {p p' : submodule R M} {x : p ⊔ p'} : (quotient_inf_equiv_sup_quotient p p').symm (submodule.quotient.mk x) = 0 ↔ (x:M) ∈ p' := (linear_equiv.symm_apply_eq _).trans $ by simp [of_le_apply] lemma quotient_inf_equiv_sup_quotient_symm_apply_right (p p' : submodule R M) {x : p ⊔ p'} (hx : (x:M) ∈ p') : (quotient_inf_equiv_sup_quotient p p').symm (submodule.quotient.mk x) = 0 := quotient_inf_equiv_sup_quotient_symm_apply_eq_zero_iff.2 hx end isomorphism_laws section prod lemma is_linear_map_prod_iso {R M M₂ M₃ : Type*} [comm_semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_group M₃] [semimodule R M] [semimodule R M₂] [semimodule R M₃] : is_linear_map R (λ(p : (M →ₗ[R] M₂) × (M →ₗ[R] M₃)), (linear_map.prod p.1 p.2 : (M →ₗ[R] (M₂ × M₃)))) := ⟨λu v, rfl, λc u, rfl⟩ end prod section pi universe i variables [semiring R] [add_comm_monoid M₂] [semimodule R M₂] [add_comm_monoid M₃] [semimodule R M₃] {φ : ι → Type i} [∀i, add_comm_monoid (φ i)] [∀i, semimodule R (φ i)] /-- `pi` construction for linear functions. From a family of linear functions it produces a linear function into a family of modules. -/ def pi (f : Πi, M₂ →ₗ[R] φ i) : M₂ →ₗ[R] (Πi, φ i) := ⟨λc i, f i c, λ c d, funext $ λ i, (f i).map_add _ _, λ c d, funext $ λ i, (f i).map_smul _ _⟩ @[simp] lemma pi_apply (f : Πi, M₂ →ₗ[R] φ i) (c : M₂) (i : ι) : pi f c i = f i c := rfl lemma ker_pi (f : Πi, M₂ →ₗ[R] φ i) : ker (pi f) = (⨅i:ι, ker (f i)) := by ext c; simp [funext_iff]; refl lemma pi_eq_zero (f : Πi, M₂ →ₗ[R] φ i) : pi f = 0 ↔ (∀i, f i = 0) := by simp only [linear_map.ext_iff, pi_apply, funext_iff]; exact ⟨λh a b, h b a, λh a b, h b a⟩ lemma pi_zero : pi (λi, 0 : Πi, M₂ →ₗ[R] φ i) = 0 := by ext; refl lemma pi_comp (f : Πi, M₂ →ₗ[R] φ i) (g : M₃ →ₗ[R] M₂) : (pi f).comp g = pi (λi, (f i).comp g) := rfl /-- The projections from a family of modules are linear maps. -/ def proj (i : ι) : (Πi, φ i) →ₗ[R] φ i := ⟨ λa, a i, assume f g, rfl, assume c f, rfl ⟩ @[simp] lemma proj_apply (i : ι) (b : Πi, φ i) : (proj i : (Πi, φ i) →ₗ[R] φ i) b = b i := rfl lemma proj_pi (f : Πi, M₂ →ₗ[R] φ i) (i : ι) : (proj i).comp (pi f) = f i := ext $ assume c, rfl lemma infi_ker_proj : (⨅i, ker (proj i) : submodule R (Πi, φ i)) = ⊥ := bot_unique $ submodule.le_def'.2 $ assume a h, begin simp only [mem_infi, mem_ker, proj_apply] at h, exact (mem_bot _).2 (funext $ assume i, h i) end section variables (R φ) /-- If `I` and `J` are disjoint index sets, the product of the kernels of the `J`th projections of `φ` is linearly equivalent to the product over `I`. -/ def infi_ker_proj_equiv {I J : set ι} [decidable_pred (λi, i ∈ I)] (hd : disjoint I J) (hu : set.univ ⊆ I ∪ J) : (⨅i ∈ J, ker (proj i) : submodule R (Πi, φ i)) ≃ₗ[R] (Πi:I, φ i) := begin refine linear_equiv.of_linear (pi $ λi, (proj (i:ι)).comp (submodule.subtype _)) (cod_restrict _ (pi $ λi, if h : i ∈ I then proj (⟨i, h⟩ : I) else 0) _) _ _, { assume b, simp only [mem_infi, mem_ker, funext_iff, proj_apply, pi_apply], assume j hjJ, have : j ∉ I := assume hjI, hd ⟨hjI, hjJ⟩, rw [dif_neg this, zero_apply] }, { simp only [pi_comp, comp_assoc, subtype_comp_cod_restrict, proj_pi, dif_pos, subtype.val_prop'], ext b ⟨j, hj⟩, refl }, { ext ⟨b, hb⟩, apply subtype.coe_ext.2, ext j, have hb : ∀i ∈ J, b i = 0, { simpa only [mem_infi, mem_ker, proj_apply] using (mem_infi _).1 hb }, simp only [comp_apply, pi_apply, id_apply, proj_apply, subtype_apply, cod_restrict_apply], split_ifs, { refl }, { exact (hb _ $ (hu trivial).resolve_left h).symm } } end end section variable [decidable_eq ι] /-- `diag i j` is the identity map if `i = j`. Otherwise it is the constant 0 map. -/ def diag (i j : ι) : φ i →ₗ[R] φ j := @function.update ι (λj, φ i →ₗ[R] φ j) _ 0 i id j lemma update_apply (f : Πi, M₂ →ₗ[R] φ i) (c : M₂) (i j : ι) (b : M₂ →ₗ[R] φ i) : (update f i b j) c = update (λi, f i c) i (b c) j := begin by_cases j = i, { rw [h, update_same, update_same] }, { rw [update_noteq h, update_noteq h] } end end section variable [decidable_eq ι] variables (R φ) /-- The standard basis of the product of `φ`. -/ def std_basis (i : ι) : φ i →ₗ[R] (Πi, φ i) := pi (diag i) lemma std_basis_apply (i : ι) (b : φ i) : std_basis R φ i b = update 0 i b := by ext j; rw [std_basis, pi_apply, diag, update_apply]; refl @[simp] lemma std_basis_same (i : ι) (b : φ i) : std_basis R φ i b i = b := by rw [std_basis_apply, update_same] lemma std_basis_ne (i j : ι) (h : j ≠ i) (b : φ i) : std_basis R φ i b j = 0 := by rw [std_basis_apply, update_noteq h]; refl lemma ker_std_basis (i : ι) : ker (std_basis R φ i) = ⊥ := ker_eq_bot_of_injective $ assume f g hfg, have std_basis R φ i f i = std_basis R φ i g i := hfg ▸ rfl, by simpa only [std_basis_same] lemma proj_comp_std_basis (i j : ι) : (proj i).comp (std_basis R φ j) = diag j i := by rw [std_basis, proj_pi] lemma proj_std_basis_same (i : ι) : (proj i).comp (std_basis R φ i) = id := by ext b; simp lemma proj_std_basis_ne (i j : ι) (h : i ≠ j) : (proj i).comp (std_basis R φ j) = 0 := by ext b; simp [std_basis_ne R φ _ _ h] lemma supr_range_std_basis_le_infi_ker_proj (I J : set ι) (h : disjoint I J) : (⨆i∈I, range (std_basis R φ i)) ≤ (⨅i∈J, ker (proj i)) := begin refine (supr_le $ assume i, supr_le $ assume hi, range_le_iff_comap.2 _), simp only [(ker_comp _ _).symm, eq_top_iff, le_def', mem_ker, comap_infi, mem_infi], assume b hb j hj, have : i ≠ j := assume eq, h ⟨hi, eq.symm ▸ hj⟩, rw [proj_std_basis_ne R φ j i this.symm, zero_apply] end lemma infi_ker_proj_le_supr_range_std_basis {I : finset ι} {J : set ι} (hu : set.univ ⊆ ↑I ∪ J) : (⨅ i∈J, ker (proj i)) ≤ (⨆i∈I, range (std_basis R φ i)) := submodule.le_def'.2 begin assume b hb, simp only [mem_infi, mem_ker, proj_apply] at hb, rw ← show ∑ i in I, std_basis R φ i (b i) = b, { ext i, rw [pi.finset_sum_apply, ← std_basis_same R φ i (b i)], refine finset.sum_eq_single i (assume j hjI ne, std_basis_ne _ _ _ _ ne.symm _) _, assume hiI, rw [std_basis_same], exact hb _ ((hu trivial).resolve_left hiI) }, exact sum_mem _ (assume i hiI, mem_supr_of_mem _ i $ mem_supr_of_mem _ hiI $ (std_basis R φ i).mem_range_self (b i)) end lemma supr_range_std_basis_eq_infi_ker_proj {I J : set ι} (hd : disjoint I J) (hu : set.univ ⊆ I ∪ J) (hI : set.finite I) : (⨆i∈I, range (std_basis R φ i)) = (⨅i∈J, ker (proj i)) := begin refine le_antisymm (supr_range_std_basis_le_infi_ker_proj _ _ _ _ hd) _, have : set.univ ⊆ ↑hI.to_finset ∪ J, { rwa [hI.coe_to_finset] }, refine le_trans (infi_ker_proj_le_supr_range_std_basis R φ this) (supr_le_supr $ assume i, _), rw [set.finite.mem_to_finset], exact le_refl _ end lemma supr_range_std_basis [fintype ι] : (⨆i:ι, range (std_basis R φ i)) = ⊤ := have (set.univ : set ι) ⊆ ↑(finset.univ : finset ι) ∪ ∅ := by rw [finset.coe_univ, set.union_empty], begin apply top_unique, convert (infi_ker_proj_le_supr_range_std_basis R φ this), exact infi_emptyset.symm, exact (funext $ λi, (@supr_pos _ _ _ (λh, range (std_basis R φ i)) $ finset.mem_univ i).symm) end lemma disjoint_std_basis_std_basis (I J : set ι) (h : disjoint I J) : disjoint (⨆i∈I, range (std_basis R φ i)) (⨆i∈J, range (std_basis R φ i)) := begin refine disjoint.mono (supr_range_std_basis_le_infi_ker_proj _ _ _ _ $ set.disjoint_compl I) (supr_range_std_basis_le_infi_ker_proj _ _ _ _ $ set.disjoint_compl J) _, simp only [disjoint, submodule.le_def', mem_infi, mem_inf, mem_ker, mem_bot, proj_apply, funext_iff], rintros b ⟨hI, hJ⟩ i, classical, by_cases hiI : i ∈ I, { by_cases hiJ : i ∈ J, { exact (h ⟨hiI, hiJ⟩).elim }, { exact hJ i hiJ } }, { exact hI i hiI } end lemma std_basis_eq_single {a : R} : (λ (i : ι), (std_basis R (λ _ : ι, R) i) a) = λ (i : ι), (finsupp.single i a) := begin ext i j, rw [std_basis_apply, finsupp.single_apply], split_ifs, { rw [h, function.update_same] }, { rw [function.update_noteq (ne.symm h)], refl }, end end end pi section fun_left variables (R M) [semiring R] [add_comm_monoid M] [semimodule R M] variables {m n p : Type*} /-- Given an `R`-module `M` and a function `m → n` between arbitrary types, construct a linear map `(n → M) →ₗ[R] (m → M)` -/ def fun_left (f : m → n) : (n → M) →ₗ[R] (m → M) := mk (∘f) (λ _ _, rfl) (λ _ _, rfl) @[simp] theorem fun_left_apply (f : m → n) (g : n → M) (i : m) : fun_left R M f g i = g (f i) := rfl @[simp] theorem fun_left_id (g : n → M) : fun_left R M _root_.id g = g := rfl theorem fun_left_comp (f₁ : n → p) (f₂ : m → n) : fun_left R M (f₁ ∘ f₂) = (fun_left R M f₂).comp (fun_left R M f₁) := rfl /-- Given an `R`-module `M` and an equivalence `m ≃ n` between arbitrary types, construct a linear equivalence `(n → M) ≃ₗ[R] (m → M)` -/ def fun_congr_left (e : m ≃ n) : (n → M) ≃ₗ[R] (m → M) := linear_equiv.of_linear (fun_left R M e) (fun_left R M e.symm) (ext $ λ x, funext $ λ i, by rw [id_apply, ← fun_left_comp, equiv.symm_comp_self, fun_left_id]) (ext $ λ x, funext $ λ i, by rw [id_apply, ← fun_left_comp, equiv.self_comp_symm, fun_left_id]) @[simp] theorem fun_congr_left_apply (e : m ≃ n) (x : n → M) : fun_congr_left R M e x = fun_left R M e x := rfl @[simp] theorem fun_congr_left_id : fun_congr_left R M (equiv.refl n) = linear_equiv.refl R (n → M) := rfl @[simp] theorem fun_congr_left_comp (e₁ : m ≃ n) (e₂ : n ≃ p) : fun_congr_left R M (equiv.trans e₁ e₂) = linear_equiv.trans (fun_congr_left R M e₂) (fun_congr_left R M e₁) := rfl @[simp] lemma fun_congr_left_symm (e : m ≃ n) : (fun_congr_left R M e).symm = fun_congr_left R M e.symm := rfl end fun_left universe i variables [semiring R] [add_comm_monoid M] [semimodule R M] variables (R M) instance automorphism_group : group (M ≃ₗ[R] M) := { mul := λ f g, g.trans f, one := linear_equiv.refl R M, inv := λ f, f.symm, mul_assoc := λ f g h, by {ext, refl}, mul_one := λ f, by {ext, refl}, one_mul := λ f, by {ext, refl}, mul_left_inv := λ f, by {ext, exact f.left_inv x} } instance automorphism_group.to_linear_map_is_monoid_hom : is_monoid_hom (linear_equiv.to_linear_map : (M ≃ₗ[R] M) → (M →ₗ[R] M)) := { map_one := rfl, map_mul := λ f g, rfl } /-- The group of invertible linear maps from `M` to itself -/ @[reducible] def general_linear_group := units (M →ₗ[R] M) namespace general_linear_group variables {R M} instance : has_coe_to_fun (general_linear_group R M) := by apply_instance /-- An invertible linear map `f` determines an equivalence from `M` to itself. -/ def to_linear_equiv (f : general_linear_group R M) : (M ≃ₗ[R] M) := { inv_fun := f.inv.to_fun, left_inv := λ m, show (f.inv * f.val) m = m, by erw f.inv_val; simp, right_inv := λ m, show (f.val * f.inv) m = m, by erw f.val_inv; simp, ..f.val } /-- An equivalence from `M` to itself determines an invertible linear map. -/ def of_linear_equiv (f : (M ≃ₗ[R] M)) : general_linear_group R M := { val := f, inv := f.symm, val_inv := linear_map.ext $ λ _, f.apply_symm_apply _, inv_val := linear_map.ext $ λ _, f.symm_apply_apply _ } variables (R M) /-- The general linear group on `R` and `M` is multiplicatively equivalent to the type of linear equivalences between `M` and itself. -/ def general_linear_equiv : general_linear_group R M ≃* (M ≃ₗ[R] M) := { to_fun := to_linear_equiv, inv_fun := of_linear_equiv, left_inv := λ f, by { ext, refl }, right_inv := λ f, by { ext, refl }, map_mul' := λ x y, by {ext, refl} } @[simp] lemma general_linear_equiv_to_linear_map (f : general_linear_group R M) : (general_linear_equiv R M f : M →ₗ[R] M) = f := by {ext, refl} end general_linear_group end linear_map
9ee3d3178576e308ccedf7f384f3604ebdce5e3d
f3a5af2927397cf346ec0e24312bfff077f00425
/src/game/world6/level9.lean
ad720e40a06ba631a49ec40358b1aaa4948c1dce
[ "Apache-2.0" ]
permissive
ImperialCollegeLondon/natural_number_game
05c39e1586408cfb563d1a12e1085a90726ab655
f29b6c2884299fc63fdfc81ae5d7daaa3219f9fd
refs/heads/master
1,688,570,964,990
1,636,908,242,000
1,636,908,242,000
195,403,790
277
84
Apache-2.0
1,694,547,955,000
1,562,328,792,000
Lean
UTF-8
Lean
false
false
1,316
lean
/- # Proposition world. ## Level 9: a big maze. Lean's "congruence closure" tactic `cc` is good at mazes. You might want to try it now. Perhaps I should have mentioned it earlier. -/ /- Lemma : no-side-bar There is a way through the following maze. -/ example (A B C D E F G H I J K L : Prop) (f1 : A → B) (f2 : B → E) (f3 : E → D) (f4 : D → A) (f5 : E → F) (f6 : F → C) (f7 : B → C) (f8 : F → G) (f9 : G → J) (f10 : I → J) (f11 : J → I) (f12 : I → H) (f13 : E → H) (f14 : H → K) (f15 : I → L) : A → L := begin cc, end /- Now move onto advanced proposition world, where you will see how to prove goals such as `P ∧ Q` ($P$ and $Q$), `P ∨ Q` ($P$ or $Q$), `P ↔ Q` ($P\iff Q$). You will need to learn five more tactics: `split`, `cases`, `left`, `right`, and `exfalso`, but they are all straightforward, and furthermore they are essentially the last tactics you need to learn in order to complete all the levels of the Natural Number Game, including all the 17 levels of Inequality World. -/ /- Tactic : cc ## Summary: `cc` will solve certain "logic" goals. ## Details `cc` is a "congruence closure tactic". In practice this means that it is good at solving certain logic goals. It's worth trying if you think that the goal could be solved using truth tables. -/
9aedd3c4aab3d853ce56577b174edec17622caae
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/abelian/functor_category.lean
572d3f420b557ef214e899e89f5fedf6c46e67ff
[ "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,604
lean
/- Copyright (c) 2022 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.abelian.basic import category_theory.preadditive.functor_category import category_theory.limits.shapes.functor_category import category_theory.limits.preserves.shapes.kernels /-! # If `D` is abelian, then the functor category `C ⥤ D` is also abelian. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ noncomputable theory namespace category_theory open category_theory.limits namespace abelian section universes z w v u variables {C : Type (max v u)} [category.{v} C] variables {D : Type w} [category.{max z v u} D] [abelian D] namespace functor_category variables {F G : C ⥤ D} (α : F ⟶ G) (X : C) /-- The abelian coimage in a functor category can be calculated componentwise. -/ @[simps] def coimage_obj_iso : (abelian.coimage α).obj X ≅ abelian.coimage (α.app X) := preserves_cokernel.iso ((evaluation C D).obj X) _ ≪≫ cokernel.map_iso _ _ (preserves_kernel.iso ((evaluation C D).obj X) _) (iso.refl _) begin dsimp, simp only [category.comp_id], exact (kernel_comparison_comp_ι _ ((evaluation C D).obj X)).symm, end /-- The abelian image in a functor category can be calculated componentwise. -/ @[simps] def image_obj_iso : (abelian.image α).obj X ≅ abelian.image (α.app X) := preserves_kernel.iso ((evaluation C D).obj X) _ ≪≫ kernel.map_iso _ _ (iso.refl _) (preserves_cokernel.iso ((evaluation C D).obj X) _) begin apply (cancel_mono (preserves_cokernel.iso ((evaluation C D).obj X) α).inv).1, simp only [category.assoc, iso.hom_inv_id], dsimp, simp only [category.id_comp, category.comp_id], exact (π_comp_cokernel_comparison _ ((evaluation C D).obj X)).symm, end lemma coimage_image_comparison_app : coimage_image_comparison (α.app X) = (coimage_obj_iso α X).inv ≫ (coimage_image_comparison α).app X ≫ (image_obj_iso α X).hom := begin ext, dsimp, simp only [category.comp_id, category.id_comp, category.assoc, coimage_image_factorisation, limits.cokernel.π_desc_assoc, limits.kernel.lift_ι], simp only [←evaluation_obj_map C D X], erw kernel_comparison_comp_ι _ ((evaluation C D).obj X), erw π_comp_cokernel_comparison_assoc _ ((evaluation C D).obj X), simp only [←functor.map_comp], simp only [coimage_image_factorisation, evaluation_obj_map], end lemma coimage_image_comparison_app' : (coimage_image_comparison α).app X = (coimage_obj_iso α X).hom ≫ coimage_image_comparison (α.app X) ≫ (image_obj_iso α X).inv := by simp only [coimage_image_comparison_app, iso.hom_inv_id_assoc, iso.hom_inv_id, category.assoc, category.comp_id] instance functor_category_is_iso_coimage_image_comparison : is_iso (abelian.coimage_image_comparison α) := begin haveI : ∀ X : C, is_iso ((abelian.coimage_image_comparison α).app X), { intros, rw coimage_image_comparison_app', apply_instance, }, apply nat_iso.is_iso_of_is_iso_app, end end functor_category noncomputable instance functor_category_abelian : abelian (C ⥤ D) := abelian.of_coimage_image_comparison_is_iso end section universes u variables {C : Type u} [small_category C] variables {D : Type (u+1)} [large_category D] [abelian D] /-- A variant with specialized universes for a common case. -/ noncomputable instance functor_category_abelian' : abelian (C ⥤ D) := abelian.functor_category_abelian.{u u+1 u u} end end abelian end category_theory
36a3527f96ca94c143757dc5063d657654e843b8
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/src/tests/shell/file2.lean
26434a4a91520ede10ac632e84c4fce1c74f2f50
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
213
lean
import data.nat check nat check nat.add_zero check nat.zero_add -- check finset open nat example (a b : nat) : a = 0 → b = 0 → a = b := assume h1 h2, eq.subst (eq.symm h1) (eq.subst (eq.symm h2) (eq.refl 0))
789033ff08f0278ec60663ce0e4ec5f95687a0d2
c45b34bfd44d8607a2e8762c926e3cfaa7436201
/uexp/src/uexp/rules/pushSemiJoinPastJoinRuleLeft.lean
75c2c6135ddc72f04a2e9b32badc690c6e12e39f
[ "BSD-2-Clause" ]
permissive
Shamrock-Frost/Cosette
b477c442c07e45082348a145f19ebb35a7f29392
24cbc4adebf627f13f5eac878f04ffa20d1209af
refs/heads/master
1,619,721,304,969
1,526,082,841,000
1,526,082,841,000
121,695,605
1
0
null
1,518,737,210,000
1,518,737,210,000
null
UTF-8
Lean
false
false
1,869
lean
import ..sql import ..tactics import ..u_semiring import ..extra_constants import ..ucongr import ..TDP open Expr open Proj open Pred open SQL open tree notation `int` := datatypes.int definition rule: forall ( Γ scm_dept scm_emp: Schema) (rel_dept: relation scm_dept) (rel_emp: relation scm_emp) (dept_deptno : Column int scm_dept) (dept_name : Column int scm_dept) (emp_empno : Column int scm_emp) (emp_ename : Column int scm_emp) (emp_job : Column int scm_emp) (emp_mgr : Column int scm_emp) (emp_hiredate : Column int scm_emp) (emp_comm : Column int scm_emp) (emp_sal : Column int scm_emp) (emp_deptno : Column int scm_emp) (emp_slacker : Column int scm_emp) (ik1: isKey emp_empno rel_emp) (ik2: isKey dept_deptno rel_dept), denoteSQL ((SELECT1 (right⋅left⋅emp_ename) (FROM1 (product (table rel_emp) (product (table rel_dept) (table rel_emp))) WHERE (and (equal (uvariable (right⋅left⋅emp_deptno)) (uvariable (right⋅right⋅left⋅dept_deptno))) (equal (uvariable (right⋅left⋅emp_empno)) (uvariable (right⋅right⋅right⋅emp_empno)))))) : SQL Γ _ ) = denoteSQL ((SELECT1 (right⋅left⋅emp_ename) (FROM1 (product (table rel_emp) (product (table rel_dept) (product (table rel_emp) (product (table rel_dept) (table rel_emp))))) WHERE (and (and (and (equal (uvariable (right⋅left⋅emp_deptno)) (uvariable (right⋅right⋅left⋅dept_deptno))) (equal (uvariable (right⋅left⋅emp_empno)) (uvariable (right⋅right⋅right⋅left⋅emp_empno)))) (equal (uvariable (right⋅left⋅emp_deptno)) (uvariable (right⋅right⋅right⋅right⋅left⋅dept_deptno)))) (equal (uvariable (right⋅left⋅emp_empno)) (uvariable (right⋅right⋅right⋅right⋅right⋅emp_empno)))))): SQL Γ _ ) := begin intros, unfold_all_denotations, funext, simp, try {ac_refl}, sorry end
cba7805c7dfe74547b1a0439ba61f2e138129f93
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/data/set/pairwise.lean
23da1bf6d3fa9d18d57aa80840f62d004f17272f
[ "Apache-2.0" ]
permissive
ayush1801/mathlib
78949b9f789f488148142221606bf15c02b960d2
ce164e28f262acbb3de6281b3b03660a9f744e3c
refs/heads/master
1,692,886,907,941
1,635,270,866,000
1,635,270,866,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,787
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import data.set.lattice import tactic.wlog /-! # Relations holding pairwise This file defines pairwise relations and pairwise disjoint sets. ## Main declarations * `pairwise p`: States that `p i j` for all `i ≠ j`. * `pairwise_disjoint`: `pairwise_disjoint s` states that all elements in `s` are either equal or `disjoint`. -/ open set universes u v variables {α : Type u} {β : Type v} {s t u : set α} /-- A relation `p` holds pairwise if `p i j` for all `i ≠ j`. -/ def pairwise {α : Type*} (p : α → α → Prop) := ∀ i j, i ≠ j → p i j theorem set.pairwise_on_univ {r : α → α → Prop} : (univ : set α).pairwise_on r ↔ pairwise r := by simp only [pairwise_on, pairwise, mem_univ, forall_const] theorem set.pairwise_on.on_injective {s : set α} {r : α → α → Prop} (hs : pairwise_on s r) {f : β → α} (hf : function.injective f) (hfs : ∀ x, f x ∈ s) : pairwise (r on f) := λ i j hij, hs _ (hfs i) _ (hfs j) (hf.ne hij) theorem pairwise.mono {p q : α → α → Prop} (hp : pairwise p) (h : ∀ ⦃i j⦄, p i j → q i j) : pairwise q := λ i j hij, h (hp i j hij) theorem pairwise_on_bool {r} (hr : symmetric r) {a b : α} : pairwise (r on (λ c, cond c a b)) ↔ r a b := by simpa [pairwise, function.on_fun] using @hr a b theorem pairwise_disjoint_on_bool [semilattice_inf_bot α] {a b : α} : pairwise (disjoint on (λ c, cond c a b)) ↔ disjoint a b := pairwise_on_bool disjoint.symm lemma symmetric.pairwise_on [linear_order β] {r} (hr : symmetric r) (f : β → α) : pairwise (r on f) ↔ ∀ m n, m < n → r (f m) (f n) := ⟨λ h m n hmn, h m n hmn.ne, λ h m n hmn, begin obtain hmn' | hmn' := hmn.lt_or_lt, { exact h _ _ hmn' }, { exact hr (h _ _ hmn') } end⟩ theorem pairwise_disjoint_on [semilattice_inf_bot α] [linear_order β] (f : β → α) : pairwise (disjoint on f) ↔ ∀ m n, m < n → disjoint (f m) (f n) := symmetric.pairwise_on disjoint.symm f theorem pairwise.pairwise_on {p : α → α → Prop} (h : pairwise p) (s : set α) : s.pairwise_on p := λ x hx y hy, h x y theorem pairwise_disjoint_fiber (f : α → β) : pairwise (disjoint on (λ y : β, f ⁻¹' {y})) := set.pairwise_on_univ.1 $ pairwise_on_disjoint_fiber f univ namespace set section semilattice_inf_bot variables [semilattice_inf_bot α] /-- Elements of a set is `pairwise_disjoint`, if any distinct two are disjoint. -/ def pairwise_disjoint (s : set α) : Prop := pairwise_on s disjoint lemma pairwise_disjoint.subset (ht : pairwise_disjoint t) (h : s ⊆ t) : pairwise_disjoint s := pairwise_on.mono h ht lemma pairwise_disjoint_empty : (∅ : set α).pairwise_disjoint := pairwise_on_empty _ lemma pairwise_disjoint_singleton (a : α) : ({a} : set α).pairwise_disjoint := pairwise_on_singleton a _ lemma pairwise_disjoint_insert {a : α} : (insert a s).pairwise_disjoint ↔ s.pairwise_disjoint ∧ ∀ b ∈ s, a ≠ b → disjoint a b := set.pairwise_on_insert_of_symmetric symmetric_disjoint lemma pairwise_disjoint.insert (hs : s.pairwise_disjoint) {a : α} (hx : ∀ b ∈ s, a ≠ b → disjoint a b) : (insert a s).pairwise_disjoint := set.pairwise_disjoint_insert.2 ⟨hs, hx⟩ lemma pairwise_disjoint.image_of_le (hs : s.pairwise_disjoint) {f : α → α} (hf : ∀ a, f a ≤ a) : (f '' s).pairwise_disjoint := begin rintro _ ⟨a, ha, rfl⟩ _ ⟨b, hb, rfl⟩ h, exact (hs a ha b hb $ ne_of_apply_ne _ h).mono (hf a) (hf b), end lemma pairwise_disjoint.range (f : s → α) (hf : ∀ (x : s), f x ≤ x) (ht : pairwise_disjoint s) : pairwise_disjoint (range f) := begin rintro _ ⟨x, rfl⟩ _ ⟨y, rfl⟩ hxy, exact (ht _ x.2 _ y.2 $ λ h, hxy $ congr_arg f $ subtype.ext h).mono (hf x) (hf y), end -- classical lemma pairwise_disjoint.elim (hs : pairwise_disjoint s) {x y : α} (hx : x ∈ s) (hy : y ∈ s) (h : ¬ disjoint x y) : x = y := of_not_not $ λ hxy, h $ hs _ hx _ hy hxy -- classical lemma pairwise_disjoint.elim' (hs : pairwise_disjoint s) {x y : α} (hx : x ∈ s) (hy : y ∈ s) (h : x ⊓ y ≠ ⊥) : x = y := hs.elim hx hy $ λ hxy, h hxy.eq_bot end semilattice_inf_bot /-! ### Pairwise disjoint set of sets -/ lemma pairwise_disjoint_range_singleton : (set.range (singleton : α → set α)).pairwise_disjoint := begin rintro _ ⟨a, rfl⟩ _ ⟨b, rfl⟩ h, exact disjoint_singleton.2 (ne_of_apply_ne _ h), end -- classical lemma pairwise_disjoint.elim_set {s : set (set α)} (hs : pairwise_disjoint s) {x y : set α} (hx : x ∈ s) (hy : y ∈ s) (z : α) (hzx : z ∈ x) (hzy : z ∈ y) : x = y := hs.elim hx hy (not_disjoint_iff.2 ⟨z, hzx, hzy⟩) end set
e2f04d5b7ab929d7760c4e882e80deb8faebc54a
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/order/boolean_algebra.lean
5799ca91c3a9b6ff27f51b6bf9c60beb5a275c7e
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
37,834
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, Bryan Gin-ge Chen -/ import order.bounded_order /-! # (Generalized) Boolean algebras A Boolean algebra is a bounded distributive lattice with a complement operator. Boolean algebras generalize the (classical) logic of propositions and the lattice of subsets of a set. Generalized Boolean algebras may be less familiar, but they are essentially Boolean algebras which do not necessarily have a top element (`⊤`) (and hence not all elements may have complements). One example in mathlib is `finset α`, the type of all finite subsets of an arbitrary (not-necessarily-finite) type `α`. `generalized_boolean_algebra α` is defined to be a distributive lattice with bottom (`⊥`) admitting a *relative* complement operator, written using "set difference" notation as `x \ y` (`sdiff x y`). For convenience, the `boolean_algebra` type class is defined to extend `generalized_boolean_algebra` so that it is also bundled with a `\` operator. (A terminological point: `x \ y` is the complement of `y` relative to the interval `[⊥, x]`. We do not yet have relative complements for arbitrary intervals, as we do not even have lattice intervals.) ## Main declarations * `has_compl`: a type class for the complement operator * `generalized_boolean_algebra`: a type class for generalized Boolean algebras * `boolean_algebra.core`: a type class with the minimal assumptions for a Boolean algebras * `boolean_algebra`: the main type class for Boolean algebras; it extends both `generalized_boolean_algebra` and `boolean_algebra.core`. An instance of `boolean_algebra` can be obtained from one of `boolean_algebra.core` using `boolean_algebra.of_core`. * `Prop.boolean_algebra`: the Boolean algebra instance on `Prop` ## Implementation notes The `sup_inf_sdiff` and `inf_inf_sdiff` axioms for the relative complement operator in `generalized_boolean_algebra` are taken from [Wikipedia](https://en.wikipedia.org/wiki/Boolean_algebra_(structure)#Generalizations). [Stone's paper introducing generalized Boolean algebras][Stone1935] does not define a relative complement operator `a \ b` for all `a`, `b`. Instead, the postulates there amount to an assumption that for all `a, b : α` where `a ≤ b`, the equations `x ⊔ a = b` and `x ⊓ a = ⊥` have a solution `x`. `disjoint.sdiff_unique` proves that this `x` is in fact `b \ a`. ## Notations * `xᶜ` is notation for `compl x` * `x \ y` is notation for `sdiff x y`. ## References * <https://en.wikipedia.org/wiki/Boolean_algebra_(structure)#Generalizations> * [*Postulates for Boolean Algebras and Generalized Boolean Algebras*, M.H. Stone][Stone1935] * [*Lattice Theory: Foundation*, George Grätzer][Gratzer2011] ## Tags generalized Boolean algebras, Boolean algebras, lattices, sdiff, compl -/ set_option old_structure_cmd true universes u v variables {α : Type u} {w x y z : α} /-! ### Generalized Boolean algebras Some of the lemmas in this section are from: * [*Lattice Theory: Foundation*, George Grätzer][Gratzer2011] * <https://ncatlab.org/nlab/show/relative+complement> * <https://people.math.gatech.edu/~mccuan/courses/4317/symmetricdifference.pdf> -/ export has_sdiff (sdiff) /-- A generalized Boolean algebra is a distributive lattice with `⊥` and a relative complement operation `\` (called `sdiff`, after "set difference") satisfying `(a ⊓ b) ⊔ (a \ b) = a` and `(a ⊓ b) ⊓ (a \ b) = b`, i.e. `a \ b` is the complement of `b` in `a`. This is a generalization of Boolean algebras which applies to `finset α` for arbitrary (not-necessarily-`fintype`) `α`. -/ class generalized_boolean_algebra (α : Type u) extends distrib_lattice α, has_sdiff α, has_bot α := (sup_inf_sdiff : ∀a b:α, (a ⊓ b) ⊔ (a \ b) = a) (inf_inf_sdiff : ∀a b:α, (a ⊓ b) ⊓ (a \ b) = ⊥) -- We might want a `is_compl_of` predicate (for relative complements) generalizing `is_compl`, -- however we'd need another type class for lattices with bot, and all the API for that. section generalized_boolean_algebra variables [generalized_boolean_algebra α] @[simp] theorem sup_inf_sdiff (x y : α) : (x ⊓ y) ⊔ (x \ y) = x := generalized_boolean_algebra.sup_inf_sdiff _ _ @[simp] theorem inf_inf_sdiff (x y : α) : (x ⊓ y) ⊓ (x \ y) = ⊥ := generalized_boolean_algebra.inf_inf_sdiff _ _ @[simp] theorem sup_sdiff_inf (x y : α) : (x \ y) ⊔ (x ⊓ y) = x := by rw [sup_comm, sup_inf_sdiff] @[simp] theorem inf_sdiff_inf (x y : α) : (x \ y) ⊓ (x ⊓ y) = ⊥ := by rw [inf_comm, inf_inf_sdiff] @[priority 100] -- see Note [lower instance priority] instance generalized_boolean_algebra.to_order_bot : order_bot α := { bot_le := λ a, by { rw [←inf_inf_sdiff a a, inf_assoc], exact inf_le_left }, ..generalized_boolean_algebra.to_has_bot α } theorem disjoint_inf_sdiff : disjoint (x ⊓ y) (x \ y) := (inf_inf_sdiff x y).le -- TODO: in distributive lattices, relative complements are unique when they exist theorem sdiff_unique (s : (x ⊓ y) ⊔ z = x) (i : (x ⊓ y) ⊓ z = ⊥) : x \ y = z := begin conv_rhs at s { rw [←sup_inf_sdiff x y, sup_comm] }, rw sup_comm at s, conv_rhs at i { rw [←inf_inf_sdiff x y, inf_comm] }, rw inf_comm at i, exact (eq_of_inf_eq_sup_eq i s).symm, end theorem sdiff_symm (hy : y ≤ x) (hz : z ≤ x) (H : x \ y = z) : x \ z = y := have hyi : x ⊓ y = y := inf_eq_right.2 hy, have hzi : x ⊓ z = z := inf_eq_right.2 hz, eq_of_inf_eq_sup_eq (begin have ixy := inf_inf_sdiff x y, rw [H, hyi] at ixy, have ixz := inf_inf_sdiff x z, rwa [hzi, inf_comm, ←ixy] at ixz, end) (begin have sxz := sup_inf_sdiff x z, rw [hzi, sup_comm] at sxz, rw sxz, symmetry, have sxy := sup_inf_sdiff x y, rwa [H, hyi] at sxy, end) lemma sdiff_le : x \ y ≤ x := calc x \ y ≤ (x ⊓ y) ⊔ (x \ y) : le_sup_right ... = x : sup_inf_sdiff x y @[simp] lemma bot_sdiff : ⊥ \ x = ⊥ := le_bot_iff.1 sdiff_le lemma inf_sdiff_right : x ⊓ (x \ y) = x \ y := by rw [inf_of_le_right (@sdiff_le _ x y _)] lemma inf_sdiff_left : (x \ y) ⊓ x = x \ y := by rw [inf_comm, inf_sdiff_right] -- cf. `is_compl_top_bot` @[simp] lemma sdiff_self : x \ x = ⊥ := by rw [←inf_inf_sdiff, inf_idem, inf_of_le_right (@sdiff_le _ x x _)] @[simp] theorem sup_sdiff_self_right : x ⊔ (y \ x) = x ⊔ y := calc x ⊔ (y \ x) = (x ⊔ (x ⊓ y)) ⊔ (y \ x) : by rw sup_inf_self ... = x ⊔ ((y ⊓ x) ⊔ (y \ x)) : by ac_refl ... = x ⊔ y : by rw sup_inf_sdiff @[simp] theorem sup_sdiff_self_left : (y \ x) ⊔ x = y ⊔ x := by rw [sup_comm, sup_sdiff_self_right, sup_comm] lemma sup_sdiff_symm : x ⊔ (y \ x) = y ⊔ (x \ y) := by rw [sup_sdiff_self_right, sup_sdiff_self_right, sup_comm] lemma sup_sdiff_cancel_right (h : x ≤ y) : x ⊔ (y \ x) = y := by conv_rhs { rw [←sup_inf_sdiff y x, inf_eq_right.2 h] } lemma sdiff_sup_cancel (h : y ≤ x) : x \ y ⊔ y = x := by rw [sup_comm, sup_sdiff_cancel_right h] lemma sup_le_of_le_sdiff_left (h : y ≤ z \ x) (hxz : x ≤ z) : x ⊔ y ≤ z := (sup_le_sup_left h x).trans (sup_sdiff_cancel_right hxz).le lemma sup_le_of_le_sdiff_right (h : x ≤ z \ y) (hyz : y ≤ z) : x ⊔ y ≤ z := (sup_le_sup_right h y).trans (sdiff_sup_cancel hyz).le @[simp] lemma sup_sdiff_left : x ⊔ (x \ y) = x := by { rw sup_eq_left, exact sdiff_le } lemma sup_sdiff_right : (x \ y) ⊔ x = x := by rw [sup_comm, sup_sdiff_left] @[simp] lemma sdiff_inf_sdiff : x \ y ⊓ (y \ x) = ⊥ := eq.symm $ calc ⊥ = (x ⊓ y) ⊓ (x \ y) : by rw inf_inf_sdiff ... = (x ⊓ (y ⊓ x ⊔ y \ x)) ⊓ (x \ y) : by rw sup_inf_sdiff ... = (x ⊓ (y ⊓ x) ⊔ x ⊓ (y \ x)) ⊓ (x \ y) : by rw inf_sup_left ... = (y ⊓ (x ⊓ x) ⊔ x ⊓ (y \ x)) ⊓ (x \ y) : by ac_refl ... = (y ⊓ x ⊔ x ⊓ (y \ x)) ⊓ (x \ y) : by rw inf_idem ... = (x ⊓ y ⊓ (x \ y)) ⊔ (x ⊓ (y \ x) ⊓ (x \ y)) : by rw [inf_sup_right, @inf_comm _ _ x y] ... = x ⊓ (y \ x) ⊓ (x \ y) : by rw [inf_inf_sdiff, bot_sup_eq] ... = x ⊓ (x \ y) ⊓ (y \ x) : by ac_refl ... = (x \ y) ⊓ (y \ x) : by rw inf_sdiff_right lemma disjoint_sdiff_sdiff : disjoint (x \ y) (y \ x) := sdiff_inf_sdiff.le theorem le_sup_sdiff : y ≤ x ⊔ (y \ x) := by { rw [sup_sdiff_self_right], exact le_sup_right } theorem le_sdiff_sup : y ≤ (y \ x) ⊔ x := by { rw [sup_comm], exact le_sup_sdiff } @[simp] theorem inf_sdiff_self_right : x ⊓ (y \ x) = ⊥ := calc x ⊓ (y \ x) = ((x ⊓ y) ⊔ (x \ y)) ⊓ (y \ x) : by rw sup_inf_sdiff ... = (x ⊓ y) ⊓ (y \ x) ⊔ (x \ y) ⊓ (y \ x) : by rw inf_sup_right ... = ⊥ : by rw [@inf_comm _ _ x y, inf_inf_sdiff, sdiff_inf_sdiff, bot_sup_eq] @[simp] theorem inf_sdiff_self_left : (y \ x) ⊓ x = ⊥ := by rw [inf_comm, inf_sdiff_self_right] theorem disjoint_sdiff_self_left : disjoint (y \ x) x := inf_sdiff_self_left.le theorem disjoint_sdiff_self_right : disjoint x (y \ x) := inf_sdiff_self_right.le lemma disjoint.disjoint_sdiff_left (h : disjoint x y) : disjoint (x \ z) y := h.mono_left sdiff_le lemma disjoint.disjoint_sdiff_right (h : disjoint x y) : disjoint x (y \ z) := h.mono_right sdiff_le /- TODO: we could make an alternative constructor for `generalized_boolean_algebra` using `disjoint x (y \ x)` and `x ⊔ (y \ x) = y` as axioms. -/ theorem disjoint.sdiff_eq_of_sup_eq (hi : disjoint x z) (hs : x ⊔ z = y) : y \ x = z := have h : y ⊓ x = x := inf_eq_right.2 $ le_sup_left.trans hs.le, sdiff_unique (by rw [h, hs]) (by rw [h, hi.eq_bot]) lemma disjoint.sup_sdiff_cancel_left (h : disjoint x y) : (x ⊔ y) \ x = y := h.sdiff_eq_of_sup_eq rfl lemma disjoint.sup_sdiff_cancel_right (h : disjoint x y) : (x ⊔ y) \ y = x := h.symm.sdiff_eq_of_sup_eq sup_comm protected theorem disjoint.sdiff_unique (hd : disjoint x z) (hz : z ≤ y) (hs : y ≤ x ⊔ z) : y \ x = z := sdiff_unique (begin rw ←inf_eq_right at hs, rwa [sup_inf_right, inf_sup_right, @sup_comm _ _ x, inf_sup_self, inf_comm, @sup_comm _ _ z, hs, sup_eq_left], end) (by rw [inf_assoc, hd.eq_bot, inf_bot_eq]) -- cf. `is_compl.disjoint_left_iff` and `is_compl.disjoint_right_iff` lemma disjoint_sdiff_iff_le (hz : z ≤ y) (hx : x ≤ y) : disjoint z (y \ x) ↔ z ≤ x := ⟨λ H, le_of_inf_le_sup_le (le_trans H bot_le) (begin rw sup_sdiff_cancel_right hx, refine le_trans (sup_le_sup_left sdiff_le z) _, rw sup_eq_right.2 hz, end), λ H, disjoint_sdiff_self_right.mono_left H⟩ -- cf. `is_compl.le_left_iff` and `is_compl.le_right_iff` lemma le_iff_disjoint_sdiff (hz : z ≤ y) (hx : x ≤ y) : z ≤ x ↔ disjoint z (y \ x) := (disjoint_sdiff_iff_le hz hx).symm -- cf. `is_compl.inf_left_eq_bot_iff` and `is_compl.inf_right_eq_bot_iff` lemma inf_sdiff_eq_bot_iff (hz : z ≤ y) (hx : x ≤ y) : z ⊓ (y \ x) = ⊥ ↔ z ≤ x := by { rw ←disjoint_iff, exact disjoint_sdiff_iff_le hz hx } -- cf. `is_compl.left_le_iff` and `is_compl.right_le_iff` lemma le_iff_eq_sup_sdiff (hz : z ≤ y) (hx : x ≤ y) : x ≤ z ↔ y = z ⊔ (y \ x) := ⟨λ H, begin apply le_antisymm, { conv_lhs { rw ←sup_inf_sdiff y x, }, apply sup_le_sup_right, rwa inf_eq_right.2 hx, }, { apply le_trans, { apply sup_le_sup_right hz, }, { rw sup_sdiff_left, } } end, λ H, begin conv_lhs at H { rw ←sup_sdiff_cancel_right hx, }, refine le_of_inf_le_sup_le _ H.le, rw inf_sdiff_self_right, exact bot_le, end⟩ -- cf. `set.union_diff_cancel'` lemma sup_sdiff_cancel' (hx : x ≤ z) (hz : z ≤ y) : z ⊔ (y \ x) = y := ((le_iff_eq_sup_sdiff hz (hx.trans hz)).1 hx).symm -- cf. `is_compl.sup_inf` lemma sdiff_sup : y \ (x ⊔ z) = (y \ x) ⊓ (y \ z) := sdiff_unique (calc y ⊓ (x ⊔ z) ⊔ y \ x ⊓ (y \ z) = (y ⊓ (x ⊔ z) ⊔ y \ x) ⊓ (y ⊓ (x ⊔ z) ⊔ (y \ z)) : by rw sup_inf_left ... = (y ⊓ x ⊔ y ⊓ z ⊔ y \ x) ⊓ (y ⊓ x ⊔ y ⊓ z ⊔ (y \ z)) : by rw @inf_sup_left _ _ y ... = (y ⊓ z ⊔ (y ⊓ x ⊔ y \ x)) ⊓ (y ⊓ x ⊔ (y ⊓ z ⊔ (y \ z))) : by ac_refl ... = (y ⊓ z ⊔ y) ⊓ (y ⊓ x ⊔ y) : by rw [sup_inf_sdiff, sup_inf_sdiff] ... = (y ⊔ y ⊓ z) ⊓ (y ⊔ y ⊓ x) : by ac_refl ... = y : by rw [sup_inf_self, sup_inf_self, inf_idem]) (calc y ⊓ (x ⊔ z) ⊓ ((y \ x) ⊓ (y \ z)) = (y ⊓ x ⊔ y ⊓ z) ⊓ ((y \ x) ⊓ (y \ z)) : by rw inf_sup_left ... = ((y ⊓ x) ⊓ ((y \ x) ⊓ (y \ z))) ⊔ ((y ⊓ z) ⊓ ((y \ x) ⊓ (y \ z))) : by rw inf_sup_right ... = ((y ⊓ x) ⊓ (y \ x) ⊓ (y \ z)) ⊔ ((y \ x) ⊓ ((y \ z) ⊓ (y ⊓ z))) : by ac_refl ... = ⊥ : by rw [inf_inf_sdiff, bot_inf_eq, bot_sup_eq, @inf_comm _ _ (y \ z), inf_inf_sdiff, inf_bot_eq]) -- cf. `is_compl.inf_sup` lemma sdiff_inf : y \ (x ⊓ z) = y \ x ⊔ y \ z := sdiff_unique (calc y ⊓ (x ⊓ z) ⊔ (y \ x ⊔ y \ z) = (z ⊓ (y ⊓ x)) ⊔ (y \ x ⊔ y \ z) : by ac_refl ... = (z ⊔ (y \ x ⊔ y \ z)) ⊓ ((y ⊓ x) ⊔ (y \ x ⊔ y \ z)) : by rw sup_inf_right ... = (y \ x ⊔ (y \ z ⊔ z)) ⊓ (y ⊓ x ⊔ (y \ x ⊔ y \ z)) : by ac_refl ... = (y ⊔ z) ⊓ ((y ⊓ x) ⊔ (y \ x ⊔ y \ z)) : by rw [sup_sdiff_self_left, ←sup_assoc, sup_sdiff_right] ... = (y ⊔ z) ⊓ y : by rw [←sup_assoc, sup_inf_sdiff, sup_sdiff_left] ... = y : by rw [inf_comm, inf_sup_self]) (calc y ⊓ (x ⊓ z) ⊓ ((y \ x) ⊔ (y \ z)) = (y ⊓ (x ⊓ z) ⊓ (y \ x)) ⊔ (y ⊓ (x ⊓ z) ⊓ (y \ z)) : by rw inf_sup_left ... = z ⊓ (y ⊓ x ⊓ (y \ x)) ⊔ z ⊓ (y ⊓ x) ⊓ (y \ z) : by ac_refl ... = z ⊓ (y ⊓ x) ⊓ (y \ z) : by rw [inf_inf_sdiff, inf_bot_eq, bot_sup_eq] ... = x ⊓ ((y ⊓ z) ⊓ (y \ z)) : by ac_refl ... = ⊥ : by rw [inf_inf_sdiff, inf_bot_eq]) @[simp] lemma sdiff_inf_self_right : y \ (x ⊓ y) = y \ x := by rw [sdiff_inf, sdiff_self, sup_bot_eq] @[simp] lemma sdiff_inf_self_left : y \ (y ⊓ x) = y \ x := by rw [inf_comm, sdiff_inf_self_right] lemma sdiff_eq_sdiff_iff_inf_eq_inf : y \ x = y \ z ↔ y ⊓ x = y ⊓ z := ⟨λ h, eq_of_inf_eq_sup_eq (by rw [inf_inf_sdiff, h, inf_inf_sdiff]) (by rw [sup_inf_sdiff, h, sup_inf_sdiff]), λ h, by rw [←sdiff_inf_self_right, ←@sdiff_inf_self_right _ z y, inf_comm, h, inf_comm]⟩ theorem disjoint.sdiff_eq_left (h : disjoint x y) : x \ y = x := by conv_rhs { rw [←sup_inf_sdiff x y, h.eq_bot, bot_sup_eq] } theorem disjoint.sdiff_eq_right (h : disjoint x y) : y \ x = y := h.symm.sdiff_eq_left -- cf. `is_compl_bot_top` @[simp] theorem sdiff_bot : x \ ⊥ = x := disjoint_bot_right.sdiff_eq_left theorem sdiff_eq_self_iff_disjoint : x \ y = x ↔ disjoint y x := calc x \ y = x ↔ x \ y = x \ ⊥ : by rw sdiff_bot ... ↔ x ⊓ y = x ⊓ ⊥ : sdiff_eq_sdiff_iff_inf_eq_inf ... ↔ disjoint y x : by rw [inf_bot_eq, inf_comm, disjoint_iff] theorem sdiff_eq_self_iff_disjoint' : x \ y = x ↔ disjoint x y := by rw [sdiff_eq_self_iff_disjoint, disjoint.comm] lemma sdiff_lt (hx : y ≤ x) (hy : y ≠ ⊥) : x \ y < x := begin refine sdiff_le.lt_of_ne (λ h, hy _), rw [sdiff_eq_self_iff_disjoint', disjoint_iff] at h, rw [←h, inf_eq_right.mpr hx], end -- cf. `is_compl.antitone` lemma sdiff_le_sdiff_left (h : z ≤ x) : w \ x ≤ w \ z := le_of_inf_le_sup_le (calc (w \ x) ⊓ (w ⊓ z) ≤ (w \ x) ⊓ (w ⊓ x) : inf_le_inf le_rfl (inf_le_inf le_rfl h) ... = ⊥ : by rw [inf_comm, inf_inf_sdiff] ... ≤ (w \ z) ⊓ (w ⊓ z) : bot_le) (calc w \ x ⊔ (w ⊓ z) ≤ w \ x ⊔ (w ⊓ x) : sup_le_sup le_rfl (inf_le_inf le_rfl h) ... ≤ w : by rw [sup_comm, sup_inf_sdiff] ... = (w \ z) ⊔ (w ⊓ z) : by rw [sup_comm, sup_inf_sdiff]) lemma sdiff_le_iff : y \ x ≤ z ↔ y ≤ x ⊔ z := ⟨λ h, le_of_inf_le_sup_le (le_of_eq (calc y ⊓ (y \ x) = y \ x : inf_sdiff_right ... = (x ⊓ (y \ x)) ⊔ (z ⊓ (y \ x)) : by rw [inf_eq_right.2 h, inf_sdiff_self_right, bot_sup_eq] ... = (x ⊔ z) ⊓ (y \ x) : inf_sup_right.symm)) (calc y ⊔ y \ x = y : sup_sdiff_left ... ≤ y ⊔ (x ⊔ z) : le_sup_left ... = ((y \ x) ⊔ x) ⊔ z : by rw [←sup_assoc, ←@sup_sdiff_self_left _ x y] ... = x ⊔ z ⊔ y \ x : by ac_refl), λ h, le_of_inf_le_sup_le (calc y \ x ⊓ x = ⊥ : inf_sdiff_self_left ... ≤ z ⊓ x : bot_le) (calc y \ x ⊔ x = y ⊔ x : sup_sdiff_self_left ... ≤ (x ⊔ z) ⊔ x : sup_le_sup_right h x ... ≤ z ⊔ x : by rw [sup_assoc, sup_comm, sup_assoc, sup_idem])⟩ @[simp] lemma le_sdiff_iff : x ≤ y \ x ↔ x = ⊥ := ⟨λ h, disjoint_self.1 (disjoint_sdiff_self_right.mono_right h), λ h, h.le.trans bot_le⟩ @[simp] lemma sdiff_eq_bot_iff : y \ x = ⊥ ↔ y ≤ x := by rw [←le_bot_iff, sdiff_le_iff, sup_bot_eq] lemma sdiff_le_comm : x \ y ≤ z ↔ x \ z ≤ y := by rw [sdiff_le_iff, sup_comm, sdiff_le_iff] lemma sdiff_le_sdiff_right (h : w ≤ y) : w \ x ≤ y \ x := le_of_inf_le_sup_le (calc (w \ x) ⊓ (w ⊓ x) = ⊥ : by rw [inf_comm, inf_inf_sdiff] ... ≤ (y \ x) ⊓ (w ⊓ x) : bot_le) (calc w \ x ⊔ (w ⊓ x) = w : by rw [sup_comm, sup_inf_sdiff] ... ≤ (y ⊓ (y \ x)) ⊔ w : le_sup_right ... = (y ⊓ (y \ x)) ⊔ (y ⊓ w) : by rw inf_eq_right.2 h ... = y ⊓ ((y \ x) ⊔ w) : by rw inf_sup_left ... = ((y \ x) ⊔ (y ⊓ x)) ⊓ ((y \ x) ⊔ w) : by rw [@sup_comm _ _ (y \ x) (y ⊓ x), sup_inf_sdiff] ... = (y \ x) ⊔ ((y ⊓ x) ⊓ w) : by rw ←sup_inf_left ... = (y \ x) ⊔ ((w ⊓ y) ⊓ x) : by ac_refl ... = (y \ x) ⊔ (w ⊓ x) : by rw inf_eq_left.2 h) theorem sdiff_le_sdiff (h₁ : w ≤ y) (h₂ : z ≤ x) : w \ x ≤ y \ z := calc w \ x ≤ w \ z : sdiff_le_sdiff_left h₂ ... ≤ y \ z : sdiff_le_sdiff_right h₁ lemma sdiff_lt_sdiff_right (h : x < y) (hz : z ≤ x) : x \ z < y \ z := (sdiff_le_sdiff_right h.le).lt_of_not_le $ λ h', h.not_le $ le_sdiff_sup.trans $ sup_le_of_le_sdiff_right h' hz lemma sup_inf_inf_sdiff : (x ⊓ y) ⊓ z ⊔ (y \ z) = (x ⊓ y) ⊔ (y \ z) := calc (x ⊓ y) ⊓ z ⊔ (y \ z) = x ⊓ (y ⊓ z) ⊔ (y \ z) : by rw inf_assoc ... = (x ⊔ (y \ z)) ⊓ y : by rw [sup_inf_right, sup_inf_sdiff] ... = (x ⊓ y) ⊔ (y \ z) : by rw [inf_sup_right, inf_sdiff_left] @[simp] lemma inf_sdiff_sup_left : (x \ z) ⊓ (x ⊔ y) = x \ z := by rw [inf_sup_left, inf_sdiff_left, sup_inf_self] @[simp] lemma inf_sdiff_sup_right : (x \ z) ⊓ (y ⊔ x) = x \ z := by rw [sup_comm, inf_sdiff_sup_left] lemma sdiff_sdiff_right : x \ (y \ z) = (x \ y) ⊔ (x ⊓ y ⊓ z) := begin rw [sup_comm, inf_comm, ←inf_assoc, sup_inf_inf_sdiff], apply sdiff_unique, { calc x ⊓ (y \ z) ⊔ (z ⊓ x ⊔ x \ y) = (x ⊔ (z ⊓ x ⊔ x \ y)) ⊓ (y \ z ⊔ (z ⊓ x ⊔ x \ y)) : by rw sup_inf_right ... = (x ⊔ x ⊓ z ⊔ x \ y) ⊓ (y \ z ⊔ (x ⊓ z ⊔ x \ y)) : by ac_refl ... = x ⊓ (y \ z ⊔ x ⊓ z ⊔ x \ y) : by rw [sup_inf_self, sup_sdiff_left, ←sup_assoc] ... = x ⊓ (y \ z ⊓ (z ⊔ y) ⊔ x ⊓ (z ⊔ y) ⊔ x \ y) : by rw [sup_inf_left, sup_sdiff_self_left, inf_sup_right, @sup_comm _ _ y] ... = x ⊓ (y \ z ⊔ (x ⊓ z ⊔ x ⊓ y) ⊔ x \ y) : by rw [inf_sdiff_sup_right, @inf_sup_left _ _ x z y] ... = x ⊓ (y \ z ⊔ (x ⊓ z ⊔ (x ⊓ y ⊔ x \ y))) : by ac_refl ... = x ⊓ (y \ z ⊔ (x ⊔ x ⊓ z)) : by rw [sup_inf_sdiff, @sup_comm _ _ (x ⊓ z)] ... = x : by rw [sup_inf_self, sup_comm, inf_sup_self] }, { calc x ⊓ (y \ z) ⊓ (z ⊓ x ⊔ x \ y) = x ⊓ (y \ z) ⊓ (z ⊓ x) ⊔ x ⊓ (y \ z) ⊓ (x \ y) : by rw inf_sup_left ... = x ⊓ (y \ z ⊓ z ⊓ x) ⊔ x ⊓ (y \ z) ⊓ (x \ y) : by ac_refl ... = x ⊓ (y \ z) ⊓ (x \ y) : by rw [inf_sdiff_self_left, bot_inf_eq, inf_bot_eq, bot_sup_eq] ... = x ⊓ (y \ z ⊓ y) ⊓ (x \ y) : by conv_lhs { rw ←inf_sdiff_left } ... = x ⊓ (y \ z ⊓ (y ⊓ (x \ y))) : by ac_refl ... = ⊥ : by rw [inf_sdiff_self_right, inf_bot_eq, inf_bot_eq] } end lemma sdiff_sdiff_right' : x \ (y \ z) = (x \ y) ⊔ (x ⊓ z) := calc x \ (y \ z) = (x \ y) ⊔ (x ⊓ y ⊓ z) : sdiff_sdiff_right ... = z ⊓ x ⊓ y ⊔ (x \ y) : by ac_refl ... = (x \ y) ⊔ (x ⊓ z) : by rw [sup_inf_inf_sdiff, sup_comm, inf_comm] @[simp] lemma sdiff_sdiff_right_self : x \ (x \ y) = x ⊓ y := by rw [sdiff_sdiff_right, inf_idem, sdiff_self, bot_sup_eq] lemma sdiff_sdiff_eq_self (h : y ≤ x) : x \ (x \ y) = y := by rw [sdiff_sdiff_right_self, inf_of_le_right h] lemma sdiff_sdiff_left : (x \ y) \ z = x \ (y ⊔ z) := begin rw sdiff_sup, apply sdiff_unique, { rw [←inf_sup_left, sup_sdiff_self_right, inf_sdiff_sup_right] }, { rw [inf_assoc, @inf_comm _ _ z, inf_assoc, inf_sdiff_self_left, inf_bot_eq, inf_bot_eq] } end lemma sdiff_sdiff_left' : (x \ y) \ z = (x \ y) ⊓ (x \ z) := by rw [sdiff_sdiff_left, sdiff_sup] lemma sdiff_sdiff_comm : (x \ y) \ z = (x \ z) \ y := by rw [sdiff_sdiff_left, sup_comm, sdiff_sdiff_left] @[simp] lemma sdiff_idem : x \ y \ y = x \ y := by rw [sdiff_sdiff_left, sup_idem] @[simp] lemma sdiff_sdiff_self : x \ y \ x = ⊥ := by rw [sdiff_sdiff_comm, sdiff_self, bot_sdiff] lemma sdiff_sdiff_sup_sdiff : z \ (x \ y ⊔ y \ x) = z ⊓ (z \ x ⊔ y) ⊓ (z \ y ⊔ x) := calc z \ (x \ y ⊔ y \ x) = (z \ x ⊔ z ⊓ x ⊓ y) ⊓ (z \ y ⊔ z ⊓ y ⊓ x) : by rw [sdiff_sup, sdiff_sdiff_right, sdiff_sdiff_right] ... = z ⊓ (z \ x ⊔ y) ⊓ (z \ y ⊔ z ⊓ y ⊓ x) : by rw [sup_inf_left, sup_comm, sup_inf_sdiff] ... = z ⊓ (z \ x ⊔ y) ⊓ (z ⊓ (z \ y ⊔ x)) : by rw [sup_inf_left, @sup_comm _ _ (z \ y), sup_inf_sdiff] ... = z ⊓ z ⊓ (z \ x ⊔ y) ⊓ (z \ y ⊔ x) : by ac_refl ... = z ⊓ (z \ x ⊔ y) ⊓ (z \ y ⊔ x) : by rw inf_idem lemma sdiff_sdiff_sup_sdiff' : z \ (x \ y ⊔ y \ x) = z ⊓ x ⊓ y ⊔ ((z \ x) ⊓ (z \ y)) := calc z \ (x \ y ⊔ y \ x) = z \ (x \ y) ⊓ (z \ (y \ x)) : sdiff_sup ... = (z \ x ⊔ z ⊓ x ⊓ y) ⊓ (z \ y ⊔ z ⊓ y ⊓ x) : by rw [sdiff_sdiff_right, sdiff_sdiff_right] ... = (z \ x ⊔ z ⊓ y ⊓ x) ⊓ (z \ y ⊔ z ⊓ y ⊓ x) : by ac_refl ... = (z \ x) ⊓ (z \ y) ⊔ z ⊓ y ⊓ x : sup_inf_right.symm ... = z ⊓ x ⊓ y ⊔ ((z \ x) ⊓ (z \ y)) : by ac_refl lemma sup_sdiff : (x ⊔ y) \ z = (x \ z) ⊔ (y \ z) := sdiff_unique (calc (x ⊔ y) ⊓ z ⊔ (x \ z ⊔ y \ z) = (x ⊓ z ⊔ y ⊓ z) ⊔ (x \ z ⊔ y \ z) : by rw inf_sup_right ... = x ⊓ z ⊔ x \ z ⊔ y \ z ⊔ y ⊓ z : by ac_refl ... = x ⊔ (y ⊓ z ⊔ y \ z) : by rw [sup_inf_sdiff, sup_assoc, @sup_comm _ _ (y \ z)] ... = x ⊔ y : by rw sup_inf_sdiff) (calc (x ⊔ y) ⊓ z ⊓ (x \ z ⊔ y \ z) = (x ⊓ z ⊔ y ⊓ z) ⊓ (x \ z ⊔ y \ z) : by rw inf_sup_right ... = (x ⊓ z ⊔ y ⊓ z) ⊓ (x \ z) ⊔ ((x ⊓ z ⊔ y ⊓ z) ⊓ (y \ z)) : by rw [@inf_sup_left _ _ (x ⊓ z ⊔ y ⊓ z)] ... = (y ⊓ z ⊓ (x \ z)) ⊔ ((x ⊓ z ⊔ y ⊓ z) ⊓ (y \ z)) : by rw [inf_sup_right, inf_inf_sdiff, bot_sup_eq] ... = (x ⊓ z ⊔ y ⊓ z) ⊓ (y \ z) : by rw [inf_assoc, inf_sdiff_self_right, inf_bot_eq, bot_sup_eq] ... = x ⊓ z ⊓ (y \ z) : by rw [inf_sup_right, inf_inf_sdiff, sup_bot_eq] ... = ⊥ : by rw [inf_assoc, inf_sdiff_self_right, inf_bot_eq]) lemma sup_sdiff_right_self : (x ⊔ y) \ y = x \ y := by rw [sup_sdiff, sdiff_self, sup_bot_eq] lemma sup_sdiff_left_self : (x ⊔ y) \ x = y \ x := by rw [sup_comm, sup_sdiff_right_self] lemma inf_sdiff : (x ⊓ y) \ z = (x \ z) ⊓ (y \ z) := sdiff_unique (calc (x ⊓ y) ⊓ z ⊔ ((x \ z) ⊓ (y \ z)) = ((x ⊓ y) ⊓ z ⊔ (x \ z)) ⊓ ((x ⊓ y) ⊓ z ⊔ (y \ z)) : by rw [sup_inf_left] ... = (x ⊓ y ⊓ (z ⊔ x) ⊔ x \ z) ⊓ (x ⊓ y ⊓ z ⊔ y \ z) : by rw [sup_inf_right, sup_sdiff_self_right, inf_sup_right, inf_sdiff_sup_right] ... = (y ⊓ (x ⊓ (x ⊔ z)) ⊔ x \ z) ⊓ (x ⊓ y ⊓ z ⊔ y \ z) : by ac_refl ... = ((y ⊓ x) ⊔ (x \ z)) ⊓ ((x ⊓ y) ⊔ (y \ z)) : by rw [inf_sup_self, sup_inf_inf_sdiff] ... = (x ⊓ y) ⊔ ((x \ z) ⊓ (y \ z)) : by rw [@inf_comm _ _ y, sup_inf_left] ... = x ⊓ y : sup_eq_left.2 (inf_le_inf sdiff_le sdiff_le)) (calc (x ⊓ y) ⊓ z ⊓ ((x \ z) ⊓ (y \ z)) = x ⊓ y ⊓ (z ⊓ (x \ z)) ⊓ (y \ z) : by ac_refl ... = ⊥ : by rw [inf_sdiff_self_right, inf_bot_eq, bot_inf_eq]) lemma inf_sdiff_assoc : (x ⊓ y) \ z = x ⊓ (y \ z) := sdiff_unique (calc x ⊓ y ⊓ z ⊔ x ⊓ (y \ z) = x ⊓ (y ⊓ z) ⊔ x ⊓ (y \ z) : by rw inf_assoc ... = x ⊓ ((y ⊓ z) ⊔ y \ z) : inf_sup_left.symm ... = x ⊓ y : by rw sup_inf_sdiff) (calc x ⊓ y ⊓ z ⊓ (x ⊓ (y \ z)) = x ⊓ x ⊓ ((y ⊓ z) ⊓ (y \ z)) : by ac_refl ... = ⊥ : by rw [inf_inf_sdiff, inf_bot_eq]) lemma sup_eq_sdiff_sup_sdiff_sup_inf : x ⊔ y = (x \ y) ⊔ (y \ x) ⊔ (x ⊓ y) := eq.symm $ calc (x \ y) ⊔ (y \ x) ⊔ (x ⊓ y) = ((x \ y) ⊔ (y \ x) ⊔ x) ⊓ ((x \ y) ⊔ (y \ x) ⊔ y) : by rw sup_inf_left ... = ((x \ y) ⊔ x ⊔ (y \ x)) ⊓ ((x \ y) ⊔ ((y \ x) ⊔ y)) : by ac_refl ... = (x ⊔ (y \ x)) ⊓ ((x \ y) ⊔ y) : by rw [sup_sdiff_right, sup_sdiff_right] ... = x ⊔ y : by rw [sup_sdiff_self_right, sup_sdiff_self_left, inf_idem] lemma sdiff_le_sdiff_of_sup_le_sup_left (h : z ⊔ x ≤ z ⊔ y) : x \ z ≤ y \ z := begin rw [←sup_sdiff_left_self, ←@sup_sdiff_left_self _ _ y], exact sdiff_le_sdiff_right h, end lemma sdiff_le_sdiff_of_sup_le_sup_right (h : x ⊔ z ≤ y ⊔ z) : x \ z ≤ y \ z := begin rw [←sup_sdiff_right_self, ←@sup_sdiff_right_self _ y], exact sdiff_le_sdiff_right h, end lemma sup_lt_of_lt_sdiff_left (h : y < z \ x) (hxz : x ≤ z) : x ⊔ y < z := begin rw ←sup_sdiff_cancel_right hxz, refine (sup_le_sup_left h.le _).lt_of_not_le (λ h', h.not_le _), rw ←sdiff_idem, exact (sdiff_le_sdiff_of_sup_le_sup_left h').trans sdiff_le, end lemma sup_lt_of_lt_sdiff_right (h : x < z \ y) (hyz : y ≤ z) : x ⊔ y < z := begin rw ←sdiff_sup_cancel hyz, refine (sup_le_sup_right h.le _).lt_of_not_le (λ h', h.not_le _), rw ←sdiff_idem, exact (sdiff_le_sdiff_of_sup_le_sup_right h').trans sdiff_le, end instance pi.generalized_boolean_algebra {α : Type u} {β : Type v} [generalized_boolean_algebra β] : generalized_boolean_algebra (α → β) := by pi_instance end generalized_boolean_algebra /-! ### Boolean algebras -/ /-- Set / lattice complement -/ @[notation_class] class has_compl (α : Type*) := (compl : α → α) export has_compl (compl) postfix `ᶜ`:(max+1) := compl /-- This class contains the core axioms of a Boolean algebra. The `boolean_algebra` class extends both this class and `generalized_boolean_algebra`, see Note [forgetful inheritance]. Since `bounded_order`, `order_bot`, and `order_top` are mixins that require `has_le` to be present at define-time, the `extends` mechanism does not work with them. Instead, we extend using the underlying `has_bot` and `has_top` data typeclasses, and replicate the order axioms of those classes here. A "forgetful" instance back to `bounded_order` is provided. -/ class boolean_algebra.core (α : Type u) extends distrib_lattice α, has_compl α, has_top α, has_bot α := (inf_compl_le_bot : ∀x:α, x ⊓ xᶜ ≤ ⊥) (top_le_sup_compl : ∀x:α, ⊤ ≤ x ⊔ xᶜ) (le_top : ∀ a : α, a ≤ ⊤) (bot_le : ∀ a : α, ⊥ ≤ a) @[priority 100] -- see Note [lower instance priority] instance boolean_algebra.core.to_bounded_order [h : boolean_algebra.core α] : bounded_order α := { ..h } section boolean_algebra_core variables [boolean_algebra.core α] @[simp] theorem inf_compl_eq_bot : x ⊓ xᶜ = ⊥ := bot_unique $ boolean_algebra.core.inf_compl_le_bot x @[simp] theorem compl_inf_eq_bot : xᶜ ⊓ x = ⊥ := eq.trans inf_comm inf_compl_eq_bot @[simp] theorem sup_compl_eq_top : x ⊔ xᶜ = ⊤ := top_unique $ boolean_algebra.core.top_le_sup_compl x @[simp] theorem compl_sup_eq_top : xᶜ ⊔ x = ⊤ := eq.trans sup_comm sup_compl_eq_top theorem is_compl_compl : is_compl x xᶜ := is_compl.of_eq inf_compl_eq_bot sup_compl_eq_top theorem is_compl.eq_compl (h : is_compl x y) : x = yᶜ := h.left_unique is_compl_compl.symm theorem is_compl.compl_eq (h : is_compl x y) : xᶜ = y := (h.right_unique is_compl_compl).symm theorem eq_compl_iff_is_compl : x = yᶜ ↔ is_compl x y := ⟨λ h, by { rw h, exact is_compl_compl.symm }, is_compl.eq_compl⟩ theorem compl_eq_iff_is_compl : xᶜ = y ↔ is_compl x y := ⟨λ h, by { rw ←h, exact is_compl_compl }, is_compl.compl_eq⟩ theorem disjoint_compl_right : disjoint x xᶜ := is_compl_compl.disjoint theorem disjoint_compl_left : disjoint xᶜ x := disjoint_compl_right.symm theorem compl_unique (i : x ⊓ y = ⊥) (s : x ⊔ y = ⊤) : xᶜ = y := (is_compl.of_eq i s).compl_eq @[simp] theorem compl_top : ⊤ᶜ = (⊥:α) := is_compl_top_bot.compl_eq @[simp] theorem compl_bot : ⊥ᶜ = (⊤:α) := is_compl_bot_top.compl_eq @[simp] theorem compl_compl (x : α) : xᶜᶜ = x := is_compl_compl.symm.compl_eq @[simp] theorem compl_involutive : function.involutive (compl : α → α) := compl_compl theorem compl_bijective : function.bijective (compl : α → α) := compl_involutive.bijective theorem compl_surjective : function.surjective (compl : α → α) := compl_involutive.surjective theorem compl_injective : function.injective (compl : α → α) := compl_involutive.injective @[simp] theorem compl_inj_iff : xᶜ = yᶜ ↔ x = y := compl_injective.eq_iff theorem is_compl.compl_eq_iff (h : is_compl x y) : zᶜ = y ↔ z = x := h.compl_eq ▸ compl_inj_iff @[simp] theorem compl_eq_top : xᶜ = ⊤ ↔ x = ⊥ := is_compl_bot_top.compl_eq_iff @[simp] theorem compl_eq_bot : xᶜ = ⊥ ↔ x = ⊤ := is_compl_top_bot.compl_eq_iff @[simp] theorem compl_inf : (x ⊓ y)ᶜ = xᶜ ⊔ yᶜ := (is_compl_compl.inf_sup is_compl_compl).compl_eq @[simp] theorem compl_sup : (x ⊔ y)ᶜ = xᶜ ⊓ yᶜ := (is_compl_compl.sup_inf is_compl_compl).compl_eq theorem compl_le_compl (h : y ≤ x) : xᶜ ≤ yᶜ := is_compl_compl.antitone is_compl_compl h @[simp] theorem compl_le_compl_iff_le : yᶜ ≤ xᶜ ↔ x ≤ y := ⟨assume h, by have h := compl_le_compl h; simp at h; assumption, compl_le_compl⟩ theorem le_compl_of_le_compl (h : y ≤ xᶜ) : x ≤ yᶜ := by simpa only [compl_compl] using compl_le_compl h theorem compl_le_of_compl_le (h : yᶜ ≤ x) : xᶜ ≤ y := by simpa only [compl_compl] using compl_le_compl h theorem le_compl_iff_le_compl : y ≤ xᶜ ↔ x ≤ yᶜ := ⟨le_compl_of_le_compl, le_compl_of_le_compl⟩ theorem compl_le_iff_compl_le : xᶜ ≤ y ↔ yᶜ ≤ x := ⟨compl_le_of_compl_le, compl_le_of_compl_le⟩ namespace boolean_algebra @[priority 100] instance : is_complemented α := ⟨λ x, ⟨xᶜ, is_compl_compl⟩⟩ end boolean_algebra end boolean_algebra_core /-- A Boolean algebra is a bounded distributive lattice with a complement operator `ᶜ` such that `x ⊓ xᶜ = ⊥` and `x ⊔ xᶜ = ⊤`. For convenience, it must also provide a set difference operation `\` satisfying `x \ y = x ⊓ yᶜ`. This is a generalization of (classical) logic of propositions, or the powerset lattice. -/ -- Lean complains about metavariables in the type if the universe is not specified class boolean_algebra (α : Type u) extends generalized_boolean_algebra α, boolean_algebra.core α := (sdiff_eq : ∀x y:α, x \ y = x ⊓ yᶜ) -- TODO: is there a way to automatically fill in the proofs of sup_inf_sdiff and inf_inf_sdiff given -- everything in `boolean_algebra.core` and `sdiff_eq`? The following doesn't work: -- (sup_inf_sdiff := λ a b, by rw [sdiff_eq, ←inf_sup_left, sup_compl_eq_top, inf_top_eq]) section of_core /-- Create a `has_sdiff` instance from a `boolean_algebra.core` instance, defining `x \ y` to be `x ⊓ yᶜ`. For some types, it may be more convenient to create the `boolean_algebra` instance by hand in order to have a simpler `sdiff` operation. See note [reducible non-instances]. -/ @[reducible] def boolean_algebra.core.sdiff [boolean_algebra.core α] : has_sdiff α := ⟨λ x y, x ⊓ yᶜ⟩ local attribute [instance] boolean_algebra.core.sdiff lemma boolean_algebra.core.sdiff_eq [boolean_algebra.core α] (a b : α) : a \ b = a ⊓ bᶜ := rfl /-- Create a `boolean_algebra` instance from a `boolean_algebra.core` instance, defining `x \ y` to be `x ⊓ yᶜ`. For some types, it may be more convenient to create the `boolean_algebra` instance by hand in order to have a simpler `sdiff` operation. -/ def boolean_algebra.of_core (B : boolean_algebra.core α) : boolean_algebra α := { sdiff := λ x y, x ⊓ yᶜ, sdiff_eq := λ _ _, rfl, sup_inf_sdiff := λ a b, by rw [←inf_sup_left, sup_compl_eq_top, inf_top_eq], inf_inf_sdiff := λ a b, by { rw [inf_left_right_swap, boolean_algebra.core.sdiff_eq, @inf_assoc _ _ _ _ b, compl_inf_eq_bot, inf_bot_eq, bot_inf_eq], congr }, ..B } end of_core section boolean_algebra variables [boolean_algebra α] theorem sdiff_eq : x \ y = x ⊓ yᶜ := boolean_algebra.sdiff_eq x y @[simp] theorem sdiff_compl : x \ yᶜ = x ⊓ y := by rw [sdiff_eq, compl_compl] @[simp] theorem top_sdiff : ⊤ \ x = xᶜ := by rw [sdiff_eq, top_inf_eq] @[simp] theorem sdiff_top : x \ ⊤ = ⊥ := by rw [sdiff_eq, compl_top, inf_bot_eq] @[simp] lemma sup_inf_inf_compl : (x ⊓ y) ⊔ (x ⊓ yᶜ) = x := by rw [← sdiff_eq, sup_inf_sdiff _ _] @[simp] lemma compl_sdiff : (x \ y)ᶜ = xᶜ ⊔ y := by rw [sdiff_eq, compl_inf, compl_compl] end boolean_algebra instance Prop.boolean_algebra : boolean_algebra Prop := boolean_algebra.of_core { compl := not, inf_compl_le_bot := λ p ⟨Hp, Hpc⟩, Hpc Hp, top_le_sup_compl := λ p H, classical.em p, .. Prop.distrib_lattice, .. Prop.bounded_order } instance pi.has_sdiff {ι : Type u} {α : ι → Type v} [∀ i, has_sdiff (α i)] : has_sdiff (Π i, α i) := ⟨λ x y i, x i \ y i⟩ lemma pi.sdiff_def {ι : Type u} {α : ι → Type v} [∀ i, has_sdiff (α i)] (x y : Π i, α i) : (x \ y) = λ i, x i \ y i := rfl @[simp] lemma pi.sdiff_apply {ι : Type u} {α : ι → Type v} [∀ i, has_sdiff (α i)] (x y : Π i, α i) (i : ι) : (x \ y) i = x i \ y i := rfl instance pi.has_compl {ι : Type u} {α : ι → Type v} [∀ i, has_compl (α i)] : has_compl (Π i, α i) := ⟨λ x i, (x i)ᶜ⟩ lemma pi.compl_def {ι : Type u} {α : ι → Type v} [∀ i, has_compl (α i)] (x : Π i, α i) : xᶜ = λ i, (x i)ᶜ := rfl @[simp] lemma pi.compl_apply {ι : Type u} {α : ι → Type v} [∀ i, has_compl (α i)] (x : Π i, α i) (i : ι) : xᶜ i = (x i)ᶜ := rfl instance pi.boolean_algebra {ι : Type u} {α : ι → Type v} [∀ i, boolean_algebra (α i)] : boolean_algebra (Π i, α i) := { sdiff_eq := λ x y, funext $ λ i, sdiff_eq, sup_inf_sdiff := λ x y, funext $ λ i, sup_inf_sdiff (x i) (y i), inf_inf_sdiff := λ x y, funext $ λ i, inf_inf_sdiff (x i) (y i), inf_compl_le_bot := λ _ _, boolean_algebra.inf_compl_le_bot _, top_le_sup_compl := λ _ _, boolean_algebra.top_le_sup_compl _, .. pi.has_sdiff, .. pi.has_compl, .. pi.bounded_order, .. pi.distrib_lattice } instance : boolean_algebra bool := boolean_algebra.of_core { sup := bor, le_sup_left := bool.left_le_bor, le_sup_right := bool.right_le_bor, sup_le := λ _ _ _, bool.bor_le, inf := band, inf_le_left := bool.band_le_left, inf_le_right := bool.band_le_right, le_inf := λ _ _ _, bool.le_band, le_sup_inf := dec_trivial, compl := bnot, inf_compl_le_bot := λ a, a.band_bnot_self.le, top_le_sup_compl := λ a, a.bor_bnot_self.ge, ..bool.linear_order, ..bool.bounded_order }
adfccffc82c29af0b428ee406a1e1eeaecf522ef
f7315930643edc12e76c229a742d5446dad77097
/library/data/int/basic.lean
c393a6095cb7e40f3d787aedca94decbf6ff5f1f
[ "Apache-2.0" ]
permissive
bmalehorn/lean
8f77b762a76c59afff7b7403f9eb5fc2c3ce70c1
53653c352643751c4b62ff63ec5e555f11dae8eb
refs/heads/master
1,610,945,684,489
1,429,681,220,000
1,429,681,449,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
35,357
lean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: int.basic Authors: Floris van Doorn, Jeremy Avigad The integers, with addition, multiplication, and subtraction. The representation of the integers is chosen to compute efficiently. To faciliate proving things about these operations, we show that the integers are a quotient of ℕ × ℕ with the usual equivalence relation, ≡, and functions abstr : ℕ × ℕ → ℤ repr : ℤ → ℕ × ℕ satisfying: abstr_repr (a : ℤ) : abstr (repr a) = a repr_abstr (p : ℕ × ℕ) : repr (abstr p) ≡ p abstr_eq (p q : ℕ × ℕ) : p ≡ q → abstr p = abstr q For example, to "lift" statements about add to statements about padd, we need to prove the following: repr_add (a b : ℤ) : repr (a + b) = padd (repr a) (repr b) padd_congr (p p' q q' : ℕ × ℕ) (H1 : p ≡ p') (H2 : q ≡ q') : padd p q ≡ p' q' -/ import data.nat.basic data.nat.order data.nat.sub data.prod import algebra.relation algebra.binary algebra.ordered_ring import tools.fake_simplifier open eq.ops open prod relation nat open decidable binary fake_simplifier /- the type of integers -/ inductive int : Type := | of_nat : nat → int | neg_succ_of_nat : nat → int notation `ℤ` := int attribute int.of_nat [coercion] definition int.of_num [coercion] [reducible] (n : num) : ℤ := int.of_nat (nat.of_num n) namespace int /- definitions of basic functions -/ definition neg_of_nat (m : ℕ) : ℤ := nat.cases_on m 0 (take m', neg_succ_of_nat m') definition sub_nat_nat (m n : ℕ) : ℤ := nat.cases_on (n - m) (of_nat (m - n)) -- m ≥ n (take k, neg_succ_of_nat k) -- m < n, and n - m = succ k definition neg (a : ℤ) : ℤ := int.cases_on a (take m, -- a = of_nat m nat.cases_on m 0 (take m', neg_succ_of_nat m')) (take m, of_nat (succ m)) -- a = neg_succ_of_nat m definition add (a b : ℤ) : ℤ := int.cases_on a (take m, -- a = of_nat m int.cases_on b (take n, of_nat (m + n)) -- b = of_nat n (take n, sub_nat_nat m (succ n))) -- b = neg_succ_of_nat n (take m, -- a = neg_succ_of_nat m int.cases_on b (take n, sub_nat_nat n (succ m)) -- b = of_nat n (take n, neg_of_nat (succ m + succ n))) -- b = neg_succ_of_nat n definition mul (a b : ℤ) : ℤ := int.cases_on a (take m, -- a = of_nat m int.cases_on b (take n, of_nat (m * n)) -- b = of_nat n (take n, neg_of_nat (m * succ n))) -- b = neg_succ_of_nat n (take m, -- a = neg_succ_of_nat m int.cases_on b (take n, neg_of_nat (succ m * n)) -- b = of_nat n (take n, of_nat (succ m * succ n))) -- b = neg_succ_of_nat n /- notation -/ notation `-[` n `+1]` := int.neg_succ_of_nat n -- for pretty-printing output prefix - := int.neg infix + := int.add infix * := int.mul /- some basic functions and properties -/ theorem of_nat.inj {m n : ℕ} (H : of_nat m = of_nat n) : m = n := int.no_confusion H (λe, e) theorem neg_succ_of_nat.inj {m n : ℕ} (H : neg_succ_of_nat m = neg_succ_of_nat n) : m = n := int.no_confusion H (λe, e) theorem neg_succ_of_nat_eq (n : ℕ) : -[n +1] = -(n + 1) := rfl definition has_decidable_eq [instance] : decidable_eq ℤ := take a b, int.cases_on a (take m, int.cases_on b (take n, if H : m = n then inl (congr_arg of_nat H) else inr (take H1, H (of_nat.inj H1))) (take n', inr (assume H, int.no_confusion H))) (take m', int.cases_on b (take n, inr (assume H, int.no_confusion H)) (take n', (if H : m' = n' then inl (congr_arg neg_succ_of_nat H) else inr (take H1, H (neg_succ_of_nat.inj H1))))) theorem of_nat_add_of_nat (n m : nat) : of_nat n + of_nat m = #nat n + m := rfl theorem of_nat_succ (n : ℕ) : of_nat (succ n) = of_nat n + 1 := rfl theorem of_nat_mul_of_nat (n m : ℕ) : of_nat n * of_nat m = n * m := rfl theorem sub_nat_nat_of_ge {m n : ℕ} (H : m ≥ n) : sub_nat_nat m n = of_nat (m - n) := have H1 : n - m = 0, from sub_eq_zero_of_le H, calc sub_nat_nat m n = nat.cases_on 0 (of_nat (m - n)) _ : H1 ▸ rfl ... = of_nat (m - n) : rfl section local attribute sub_nat_nat [reducible] theorem sub_nat_nat_of_lt {m n : ℕ} (H : m < n) : sub_nat_nat m n = neg_succ_of_nat (pred (n - m)) := have H1 : n - m = succ (pred (n - m)), from (succ_pred_of_pos (sub_pos_of_lt H))⁻¹, calc sub_nat_nat m n = nat.cases_on (succ (pred (n - m))) (of_nat (m - n)) (take k, neg_succ_of_nat k) : H1 ▸ rfl ... = neg_succ_of_nat (pred (n - m)) : rfl end definition nat_abs (a : ℤ) : ℕ := int.cases_on a (take n, n) (take n', succ n') theorem nat_abs_of_nat (n : ℕ) : nat_abs (of_nat n) = n := rfl theorem nat_abs_eq_zero {a : ℤ} : nat_abs a = 0 → a = 0 := int.cases_on a (take m, assume H : nat_abs (of_nat m) = 0, congr_arg of_nat H) (take m', assume H : nat_abs (neg_succ_of_nat m') = 0, absurd H (succ_ne_zero _)) /- int is a quotient of ordered pairs of natural numbers -/ protected definition equiv (p q : ℕ × ℕ) : Prop := pr1 p + pr2 q = pr2 p + pr1 q local notation p `≡` q := equiv p q protected theorem equiv.refl {p : ℕ × ℕ} : p ≡ p := !add.comm protected theorem equiv.symm {p q : ℕ × ℕ} (H : p ≡ q) : q ≡ p := calc pr1 q + pr2 p = pr2 p + pr1 q : !add.comm ... = pr1 p + pr2 q : H⁻¹ ... = pr2 q + pr1 p : !add.comm protected theorem equiv.trans {p q r : ℕ × ℕ} (H1 : p ≡ q) (H2 : q ≡ r) : p ≡ r := have H3 : pr1 p + pr2 r + pr2 q = pr2 p + pr1 r + pr2 q, from calc pr1 p + pr2 r + pr2 q = pr1 p + pr2 q + pr2 r : by simp ... = pr2 p + pr1 q + pr2 r : {H1} ... = pr2 p + (pr1 q + pr2 r) : by simp ... = pr2 p + (pr2 q + pr1 r) : {H2} ... = pr2 p + pr1 r + pr2 q : by simp, show pr1 p + pr2 r = pr2 p + pr1 r, from add.cancel_right H3 protected theorem equiv_equiv : is_equivalence equiv := is_equivalence.mk @equiv.refl @equiv.symm @equiv.trans protected theorem equiv_cases {p q : ℕ × ℕ} (H : equiv p q) : (pr1 p ≥ pr2 p ∧ pr1 q ≥ pr2 q) ∨ (pr1 p < pr2 p ∧ pr1 q < pr2 q) := or.elim (@le_or_gt (pr2 p) (pr1 p)) (assume H1: pr1 p ≥ pr2 p, have H2 : pr2 p + pr1 q ≥ pr2 p + pr2 q, from H ▸ add_le_add_right H1 (pr2 q), or.inl (and.intro H1 (le_of_add_le_add_left H2))) (assume H1: pr1 p < pr2 p, have H2 : pr2 p + pr1 q < pr2 p + pr2 q, from H ▸ add_lt_add_right H1 (pr2 q), or.inr (and.intro H1 (lt_of_add_lt_add_left H2))) protected theorem equiv_of_eq {p q : ℕ × ℕ} (H : p = q) : p ≡ q := H ▸ equiv.refl calc_trans equiv.trans calc_refl equiv.refl calc_symm equiv.symm /- the representation and abstraction functions -/ definition abstr (a : ℕ × ℕ) : ℤ := sub_nat_nat (pr1 a) (pr2 a) theorem abstr_of_ge {p : ℕ × ℕ} (H : pr1 p ≥ pr2 p) : abstr p = of_nat (pr1 p - pr2 p) := sub_nat_nat_of_ge H theorem abstr_of_lt {p : ℕ × ℕ} (H : pr1 p < pr2 p) : abstr p = neg_succ_of_nat (pred (pr2 p - pr1 p)) := sub_nat_nat_of_lt H definition repr (a : ℤ) : ℕ × ℕ := int.cases_on a (take m, (m, 0)) (take m, (0, succ m)) theorem abstr_repr (a : ℤ) : abstr (repr a) = a := int.cases_on a (take m, (sub_nat_nat_of_ge (zero_le m))) (take m, rfl) theorem repr_sub_nat_nat (m n : ℕ) : repr (sub_nat_nat m n) ≡ (m, n) := or.elim (@le_or_gt n m) (take H : m ≥ n, have H1 : repr (sub_nat_nat m n) = (m - n, 0), from sub_nat_nat_of_ge H ▸ rfl, H1⁻¹ ▸ (calc m - n + n = m : sub_add_cancel H ... = 0 + m : zero_add)) (take H : m < n, have H1 : repr (sub_nat_nat m n) = (0, succ (pred (n - m))), from sub_nat_nat_of_lt H ▸ rfl, H1⁻¹ ▸ (calc 0 + n = n : zero_add ... = n - m + m : sub_add_cancel (le_of_lt H) ... = succ (pred (n - m)) + m : (succ_pred_of_pos (sub_pos_of_lt H))⁻¹)) theorem repr_abstr (p : ℕ × ℕ) : repr (abstr p) ≡ p := !prod.eta ▸ !repr_sub_nat_nat theorem abstr_eq {p q : ℕ × ℕ} (Hequiv : p ≡ q) : abstr p = abstr q := or.elim (equiv_cases Hequiv) (assume H2, have H3 : pr1 p ≥ pr2 p, from and.elim_left H2, have H4 : pr1 q ≥ pr2 q, from and.elim_right H2, have H5 : pr1 p = pr1 q - pr2 q + pr2 p, from calc pr1 p = pr1 p + pr2 q - pr2 q : add_sub_cancel ... = pr2 p + pr1 q - pr2 q : Hequiv ... = pr2 p + (pr1 q - pr2 q) : add_sub_assoc H4 ... = pr1 q - pr2 q + pr2 p : add.comm, have H6 : pr1 p - pr2 p = pr1 q - pr2 q, from calc pr1 p - pr2 p = pr1 q - pr2 q + pr2 p - pr2 p : H5 ... = pr1 q - pr2 q : add_sub_cancel, abstr_of_ge H3 ⬝ congr_arg of_nat H6 ⬝ (abstr_of_ge H4)⁻¹) (assume H2, have H3 : pr1 p < pr2 p, from and.elim_left H2, have H4 : pr1 q < pr2 q, from and.elim_right H2, have H5 : pr2 p = pr2 q - pr1 q + pr1 p, from calc pr2 p = pr2 p + pr1 q - pr1 q : add_sub_cancel ... = pr1 p + pr2 q - pr1 q : Hequiv ... = pr1 p + (pr2 q - pr1 q) : add_sub_assoc (le_of_lt H4) ... = pr2 q - pr1 q + pr1 p : add.comm, have H6 : pr2 p - pr1 p = pr2 q - pr1 q, from calc pr2 p - pr1 p = pr2 q - pr1 q + pr1 p - pr1 p : H5 ... = pr2 q - pr1 q : add_sub_cancel, abstr_of_lt H3 ⬝ congr_arg neg_succ_of_nat (congr_arg pred H6)⬝ (abstr_of_lt H4)⁻¹) theorem equiv_iff (p q : ℕ × ℕ) : (p ≡ q) ↔ ((p ≡ p) ∧ (q ≡ q) ∧ (abstr p = abstr q)) := iff.intro (assume H : equiv p q, and.intro !equiv.refl (and.intro !equiv.refl (abstr_eq H))) (assume H : equiv p p ∧ equiv q q ∧ abstr p = abstr q, have H1 : abstr p = abstr q, from and.elim_right (and.elim_right H), equiv.trans (H1 ▸ equiv.symm (repr_abstr p)) (repr_abstr q)) theorem eq_abstr_of_equiv_repr {a : ℤ} {p : ℕ × ℕ} (Hequiv : repr a ≡ p) : a = abstr p := calc a = abstr (repr a) : abstr_repr ... = abstr p : abstr_eq Hequiv theorem eq_of_repr_equiv_repr {a b : ℤ} (H : repr a ≡ repr b) : a = b := calc a = abstr (repr a) : abstr_repr ... = abstr (repr b) : abstr_eq H ... = b : abstr_repr section local attribute abstr [reducible] local attribute dist [reducible] theorem nat_abs_abstr (p : ℕ × ℕ) : nat_abs (abstr p) = dist (pr1 p) (pr2 p) := let m := pr1 p, n := pr2 p in or.elim (@le_or_gt n m) (assume H : m ≥ n, calc nat_abs (abstr (m, n)) = nat_abs (of_nat (m - n)) : int.abstr_of_ge H ... = dist m n : dist_eq_sub_of_ge H) (assume H : m < n, calc nat_abs (abstr (m, n)) = nat_abs (neg_succ_of_nat (pred (n - m))) : int.abstr_of_lt H ... = succ (pred (n - m)) : rfl ... = n - m : succ_pred_of_pos (sub_pos_of_lt H) ... = dist m n : dist_eq_sub_of_le (le_of_lt H)) end theorem cases_of_nat (a : ℤ) : (∃n : ℕ, a = of_nat n) ∨ (∃n : ℕ, a = - of_nat n) := int.cases_on a (take n, or.inl (exists.intro n rfl)) (take n', or.inr (exists.intro (succ n') rfl)) theorem cases_of_nat_succ (a : ℤ) : (∃n : ℕ, a = of_nat n) ∨ (∃n : ℕ, a = - (of_nat (succ n))) := int.cases_on a (take m, or.inl (exists.intro _ rfl)) (take m, or.inr (exists.intro _ rfl)) theorem by_cases_of_nat {P : ℤ → Prop} (a : ℤ) (H1 : ∀n : ℕ, P (of_nat n)) (H2 : ∀n : ℕ, P (- of_nat n)) : P a := or.elim (cases_of_nat a) (assume H, obtain (n : ℕ) (H3 : a = n), from H, H3⁻¹ ▸ H1 n) (assume H, obtain (n : ℕ) (H3 : a = -n), from H, H3⁻¹ ▸ H2 n) theorem by_cases_of_nat_succ {P : ℤ → Prop} (a : ℤ) (H1 : ∀n : ℕ, P (of_nat n)) (H2 : ∀n : ℕ, P (- of_nat (succ n))) : P a := or.elim (cases_of_nat_succ a) (assume H, obtain (n : ℕ) (H3 : a = n), from H, H3⁻¹ ▸ H1 n) (assume H, obtain (n : ℕ) (H3 : a = -(succ n)), from H, H3⁻¹ ▸ H2 n) /- int is a ring -/ /- addition -/ definition padd (p q : ℕ × ℕ) : ℕ × ℕ := (pr1 p + pr1 q, pr2 p + pr2 q) theorem repr_add (a b : ℤ) : repr (add a b) ≡ padd (repr a) (repr b) := int.cases_on a (take m, int.cases_on b (take n, !equiv.refl) (take n', have H1 : equiv (repr (add (of_nat m) (neg_succ_of_nat n'))) (m, succ n'), from !repr_sub_nat_nat, have H2 : padd (repr (of_nat m)) (repr (neg_succ_of_nat n')) = (m, 0 + succ n'), from rfl, (!zero_add ▸ H2)⁻¹ ▸ H1)) (take m', int.cases_on b (take n, have H1 : equiv (repr (add (neg_succ_of_nat m') (of_nat n))) (n, succ m'), from !repr_sub_nat_nat, have H2 : padd (repr (neg_succ_of_nat m')) (repr (of_nat n)) = (0 + n, succ m'), from rfl, (!zero_add ▸ H2)⁻¹ ▸ H1) (take n',!repr_sub_nat_nat)) theorem padd_congr {p p' q q' : ℕ × ℕ} (Ha : p ≡ p') (Hb : q ≡ q') : padd p q ≡ padd p' q' := calc pr1 (padd p q) + pr2 (padd p' q') = pr1 p + pr2 p' + (pr1 q + pr2 q') : by simp ... = pr2 p + pr1 p' + (pr1 q + pr2 q') : {Ha} ... = pr2 p + pr1 p' + (pr2 q + pr1 q') : {Hb} ... = pr2 (padd p q) + pr1 (padd p' q') : by simp theorem padd_comm (p q : ℕ × ℕ) : padd p q = padd q p := calc padd p q = (pr1 p + pr1 q, pr2 p + pr2 q) : rfl ... = (pr1 q + pr1 p, pr2 p + pr2 q) : add.comm ... = (pr1 q + pr1 p, pr2 q + pr2 p) : add.comm ... = padd q p : rfl theorem padd_assoc (p q r : ℕ × ℕ) : padd (padd p q) r = padd p (padd q r) := calc padd (padd p q) r = (pr1 p + pr1 q + pr1 r, pr2 p + pr2 q + pr2 r) : rfl ... = (pr1 p + (pr1 q + pr1 r), pr2 p + pr2 q + pr2 r) : add.assoc ... = (pr1 p + (pr1 q + pr1 r), pr2 p + (pr2 q + pr2 r)) : add.assoc ... = padd p (padd q r) : rfl theorem add.comm (a b : ℤ) : a + b = b + a := begin apply eq_of_repr_equiv_repr, apply equiv.trans, apply repr_add, apply equiv.symm, apply (eq.subst (padd_comm (repr b) (repr a))), apply repr_add end theorem add.assoc (a b c : ℤ) : a + b + c = a + (b + c) := assert H1 : repr (a + b + c) ≡ padd (padd (repr a) (repr b)) (repr c), from equiv.trans (repr_add (a + b) c) (padd_congr !repr_add !equiv.refl), assert H2 : repr (a + (b + c)) ≡ padd (repr a) (padd (repr b) (repr c)), from equiv.trans (repr_add a (b + c)) (padd_congr !equiv.refl !repr_add), begin apply eq_of_repr_equiv_repr, apply equiv.trans, apply H1, apply (eq.subst ((padd_assoc _ _ _)⁻¹)), apply equiv.symm, apply H2 end theorem add_zero (a : ℤ) : a + 0 = a := int.cases_on a (take m, rfl) (take m', rfl) theorem zero_add (a : ℤ) : 0 + a = a := add.comm a 0 ▸ add_zero a /- negation -/ definition pneg (p : ℕ × ℕ) : ℕ × ℕ := (pr2 p, pr1 p) -- note: this is =, not just ≡ theorem repr_neg (a : ℤ) : repr (- a) = pneg (repr a) := int.cases_on a (take m, nat.cases_on m rfl (take m', rfl)) (take m', rfl) theorem pneg_congr {p p' : ℕ × ℕ} (H : p ≡ p') : pneg p ≡ pneg p' := eq.symm H theorem pneg_pneg (p : ℕ × ℕ) : pneg (pneg p) = p := !prod.eta theorem nat_abs_neg (a : ℤ) : nat_abs (-a) = nat_abs a := calc nat_abs (-a) = nat_abs (abstr (repr (-a))) : abstr_repr ... = nat_abs (abstr (pneg (repr a))) : repr_neg ... = dist (pr1 (pneg (repr a))) (pr2 (pneg (repr a))) : nat_abs_abstr ... = dist (pr2 (pneg (repr a))) (pr1 (pneg (repr a))) : dist.comm ... = nat_abs (abstr (repr a)) : nat_abs_abstr ... = nat_abs a : abstr_repr theorem padd_pneg (p : ℕ × ℕ) : padd p (pneg p) ≡ (0, 0) := show pr1 p + pr2 p + 0 = pr2 p + pr1 p + 0, from !nat.add.comm ▸ rfl theorem padd_padd_pneg (p q : ℕ × ℕ) : padd (padd p q) (pneg q) ≡ p := show pr1 p + pr1 q + pr2 q + pr2 p = pr2 p + pr2 q + pr1 q + pr1 p, from by simp theorem add.left_inv (a : ℤ) : -a + a = 0 := have H : repr (-a + a) ≡ repr 0, from calc repr (-a + a) ≡ padd (repr (neg a)) (repr a) : repr_add ... = padd (pneg (repr a)) (repr a) : repr_neg ... ≡ repr 0 : padd_pneg, eq_of_repr_equiv_repr H /- nat abs -/ definition pabs (p : ℕ × ℕ) : ℕ := dist (pr1 p) (pr2 p) theorem pabs_congr {p q : ℕ × ℕ} (H : p ≡ q) : pabs p = pabs q := calc pabs p = nat_abs (abstr p) : nat_abs_abstr ... = nat_abs (abstr q) : abstr_eq H ... = pabs q : nat_abs_abstr theorem nat_abs_eq_pabs_repr (a : ℤ) : nat_abs a = pabs (repr a) := calc nat_abs a = nat_abs (abstr (repr a)) : abstr_repr ... = pabs (repr a) : nat_abs_abstr theorem nat_abs_add_le (a b : ℤ) : nat_abs (a + b) ≤ nat_abs a + nat_abs b := have H : nat_abs (a + b) = pabs (padd (repr a) (repr b)), from calc nat_abs (a + b) = pabs (repr (a + b)) : nat_abs_eq_pabs_repr ... = pabs (padd (repr a) (repr b)) : pabs_congr !repr_add, have H1 : nat_abs a = pabs (repr a), from !nat_abs_eq_pabs_repr, have H2 : nat_abs b = pabs (repr b), from !nat_abs_eq_pabs_repr, have H3 : pabs (padd (repr a) (repr b)) ≤ pabs (repr a) + pabs (repr b), from !dist_add_add_le_add_dist_dist, H⁻¹ ▸ H1⁻¹ ▸ H2⁻¹ ▸ H3 section local attribute nat_abs [reducible] theorem mul_nat_abs (a b : ℤ) : nat_abs (a * b) = #nat (nat_abs a) * (nat_abs b) := int.cases_on a (take m, int.cases_on b (take n, rfl) (take n', !nat_abs_neg ▸ rfl)) (take m', int.cases_on b (take n, !nat_abs_neg ▸ rfl) (take n', rfl)) end /- multiplication -/ definition pmul (p q : ℕ × ℕ) : ℕ × ℕ := (pr1 p * pr1 q + pr2 p * pr2 q, pr1 p * pr2 q + pr2 p * pr1 q) theorem repr_neg_of_nat (m : ℕ) : repr (neg_of_nat m) = (0, m) := nat.cases_on m rfl (take m', rfl) -- note: we have =, not just ≡ theorem repr_mul (a b : ℤ) : repr (mul a b) = pmul (repr a) (repr b) := int.cases_on a (take m, int.cases_on b (take n, (calc pmul (repr m) (repr n) = (m * n + 0 * 0, m * 0 + 0 * n) : rfl ... = (m * n + 0 * 0, m * 0 + 0) : zero_mul)⁻¹) (take n', (calc pmul (repr m) (repr (neg_succ_of_nat n')) = (m * 0 + 0 * succ n', m * succ n' + 0 * 0) : rfl ... = (m * 0 + 0, m * succ n' + 0 * 0) : zero_mul ... = repr (mul m (neg_succ_of_nat n')) : repr_neg_of_nat)⁻¹)) (take m', int.cases_on b (take n, (calc pmul (repr (neg_succ_of_nat m')) (repr n) = (0 * n + succ m' * 0, 0 * 0 + succ m' * n) : rfl ... = (0 + succ m' * 0, 0 * 0 + succ m' * n) : zero_mul ... = (0 + succ m' * 0, succ m' * n) : {!nat.zero_add} ... = repr (mul (neg_succ_of_nat m') n) : repr_neg_of_nat)⁻¹) (take n', (calc pmul (repr (neg_succ_of_nat m')) (repr (neg_succ_of_nat n')) = (0 + succ m' * succ n', 0 * succ n') : rfl ... = (succ m' * succ n', 0 * succ n') : nat.zero_add ... = (succ m' * succ n', 0) : zero_mul ... = repr (mul (neg_succ_of_nat m') (neg_succ_of_nat n')) : rfl)⁻¹)) theorem equiv_mul_prep {xa ya xb yb xn yn xm ym : ℕ} (H1 : xa + yb = ya + xb) (H2 : xn + ym = yn + xm) : xa * xn + ya * yn + (xb * ym + yb * xm) = xa * yn + ya * xn + (xb * xm + yb * ym) := have H3 : xa * xn + ya * yn + (xb * ym + yb * xm) + (yb * xn + xb * yn + (xb * xn + yb * yn)) = xa * yn + ya * xn + (xb * xm + yb * ym) + (yb * xn + xb * yn + (xb * xn + yb * yn)), from calc xa * xn + ya * yn + (xb * ym + yb * xm) + (yb * xn + xb * yn + (xb * xn + yb * yn)) = xa * xn + yb * xn + (ya * yn + xb * yn) + (xb * xn + xb * ym + (yb * yn + yb * xm)) : by simp ... = (xa + yb) * xn + (ya + xb) * yn + (xb * (xn + ym) + yb * (yn + xm)) : by simp ... = (ya + xb) * xn + (xa + yb) * yn + (xb * (yn + xm) + yb * (xn + ym)) : by simp ... = ya * xn + xb * xn + (xa * yn + yb * yn) + (xb * yn + xb * xm + (yb*xn + yb*ym)) : by simp ... = xa * yn + ya * xn + (xb * xm + yb * ym) + (yb * xn + xb * yn + (xb * xn + yb * yn)) : by simp, nat.add.cancel_right H3 theorem pmul_congr {p p' q q' : ℕ × ℕ} (H1 : p ≡ p') (H2 : q ≡ q') : pmul p q ≡ pmul p' q' := equiv_mul_prep H1 H2 theorem pmul_comm (p q : ℕ × ℕ) : pmul p q = pmul q p := calc (pr1 p * pr1 q + pr2 p * pr2 q, pr1 p * pr2 q + pr2 p * pr1 q) = (pr1 q * pr1 p + pr2 p * pr2 q, pr1 p * pr2 q + pr2 p * pr1 q) : mul.comm ... = (pr1 q * pr1 p + pr2 q * pr2 p, pr1 p * pr2 q + pr2 p * pr1 q) : mul.comm ... = (pr1 q * pr1 p + pr2 q * pr2 p, pr2 q * pr1 p + pr2 p * pr1 q) : mul.comm ... = (pr1 q * pr1 p + pr2 q * pr2 p, pr2 q * pr1 p + pr1 q * pr2 p) : mul.comm ... = (pr1 q * pr1 p + pr2 q * pr2 p, pr1 q * pr2 p + pr2 q * pr1 p) : nat.add.comm theorem mul.comm (a b : ℤ) : a * b = b * a := eq_of_repr_equiv_repr ((calc repr (a * b) = pmul (repr a) (repr b) : repr_mul ... = pmul (repr b) (repr a) : pmul_comm ... = repr (b * a) : repr_mul) ▸ !equiv.refl) theorem pmul_assoc (p q r: ℕ × ℕ) : pmul (pmul p q) r = pmul p (pmul q r) := by simp theorem mul.assoc (a b c : ℤ) : (a * b) * c = a * (b * c) := eq_of_repr_equiv_repr ((calc repr (a * b * c) = pmul (repr (a * b)) (repr c) : repr_mul ... = pmul (pmul (repr a) (repr b)) (repr c) : repr_mul ... = pmul (repr a) (pmul (repr b) (repr c)) : pmul_assoc ... = pmul (repr a) (repr (b * c)) : repr_mul ... = repr (a * (b * c)) : repr_mul) ▸ !equiv.refl) theorem mul_one (a : ℤ) : a * 1 = a := eq_of_repr_equiv_repr (equiv_of_eq ((calc repr (a * 1) = pmul (repr a) (repr 1) : repr_mul ... = (pr1 (repr a), pr2 (repr a)) : by simp ... = repr a : prod.eta))) theorem one_mul (a : ℤ) : 1 * a = a := mul.comm a 1 ▸ mul_one a theorem mul.right_distrib (a b c : ℤ) : (a + b) * c = a * c + b * c := eq_of_repr_equiv_repr (calc repr ((a + b) * c) = pmul (repr (a + b)) (repr c) : repr_mul ... ≡ pmul (padd (repr a) (repr b)) (repr c) : pmul_congr !repr_add equiv.refl ... = padd (pmul (repr a) (repr c)) (pmul (repr b) (repr c)) : by simp ... = padd (repr (a * c)) (pmul (repr b) (repr c)) : {(repr_mul a c)⁻¹} ... = padd (repr (a * c)) (repr (b * c)) : repr_mul ... ≡ repr (a * c + b * c) : equiv.symm !repr_add) theorem mul.left_distrib (a b c : ℤ) : a * (b + c) = a * b + a * c := calc a * (b + c) = (b + c) * a : mul.comm a (b + c) ... = b * a + c * a : mul.right_distrib b c a ... = a * b + c * a : {mul.comm b a} ... = a * b + a * c : {mul.comm c a} theorem zero_ne_one : (typeof 0 : int) ≠ 1 := assume H : 0 = 1, show false, from succ_ne_zero 0 ((of_nat.inj H)⁻¹) theorem eq_zero_or_eq_zero_of_mul_eq_zero {a b : ℤ} (H : a * b = 0) : a = 0 ∨ b = 0 := have H2 : (nat_abs a) * (nat_abs b) = nat.zero, from calc (nat_abs a) * (nat_abs b) = (nat_abs (a * b)) : (mul_nat_abs a b)⁻¹ ... = (nat_abs 0) : {H} ... = nat.zero : nat_abs_of_nat nat.zero, have H3 : (nat_abs a) = nat.zero ∨ (nat_abs b) = nat.zero, from eq_zero_or_eq_zero_of_mul_eq_zero H2, or_of_or_of_imp_of_imp H3 (assume H : (nat_abs a) = nat.zero, nat_abs_eq_zero H) (assume H : (nat_abs b) = nat.zero, nat_abs_eq_zero H) section open [classes] algebra protected definition integral_domain [instance] [reducible] : algebra.integral_domain int := ⦃algebra.integral_domain, add := add, add_assoc := add.assoc, zero := zero, zero_add := zero_add, add_zero := add_zero, neg := neg, add_left_inv := add.left_inv, add_comm := add.comm, mul := mul, mul_assoc := mul.assoc, one := (of_num 1), one_mul := one_mul, mul_one := mul_one, left_distrib := mul.left_distrib, right_distrib := mul.right_distrib, mul_comm := mul.comm, eq_zero_or_eq_zero_of_mul_eq_zero := @eq_zero_or_eq_zero_of_mul_eq_zero⦄ end /- instantiate ring theorems to int -/ section port_algebra open [classes] algebra theorem mul.left_comm : ∀a b c : ℤ, a * (b * c) = b * (a * c) := algebra.mul.left_comm theorem mul.right_comm : ∀a b c : ℤ, (a * b) * c = (a * c) * b := algebra.mul.right_comm theorem add.left_comm : ∀a b c : ℤ, a + (b + c) = b + (a + c) := algebra.add.left_comm theorem add.right_comm : ∀a b c : ℤ, (a + b) + c = (a + c) + b := algebra.add.right_comm theorem add.left_cancel : ∀{a b c : ℤ}, a + b = a + c → b = c := @algebra.add.left_cancel _ _ theorem add.right_cancel : ∀{a b c : ℤ}, a + b = c + b → a = c := @algebra.add.right_cancel _ _ theorem neg_add_cancel_left : ∀a b : ℤ, -a + (a + b) = b := algebra.neg_add_cancel_left theorem neg_add_cancel_right : ∀a b : ℤ, a + -b + b = a := algebra.neg_add_cancel_right theorem neg_eq_of_add_eq_zero : ∀{a b : ℤ}, a + b = 0 → -a = b := @algebra.neg_eq_of_add_eq_zero _ _ theorem neg_zero : -0 = 0 := algebra.neg_zero theorem neg_neg : ∀a : ℤ, -(-a) = a := algebra.neg_neg theorem neg.inj : ∀{a b : ℤ}, -a = -b → a = b := @algebra.neg.inj _ _ theorem neg_eq_neg_iff_eq : ∀a b : ℤ, -a = -b ↔ a = b := algebra.neg_eq_neg_iff_eq theorem neg_eq_zero_iff_eq_zero : ∀a : ℤ, -a = 0 ↔ a = 0 := algebra.neg_eq_zero_iff_eq_zero theorem eq_neg_of_eq_neg : ∀{a b : ℤ}, a = -b → b = -a := @algebra.eq_neg_of_eq_neg _ _ theorem eq_neg_iff_eq_neg : ∀{a b : ℤ}, a = -b ↔ b = -a := @algebra.eq_neg_iff_eq_neg _ _ theorem add.right_inv : ∀a : ℤ, a + -a = 0 := algebra.add.right_inv theorem add_neg_cancel_left : ∀a b : ℤ, a + (-a + b) = b := algebra.add_neg_cancel_left theorem add_neg_cancel_right : ∀a b : ℤ, a + b + -b = a := algebra.add_neg_cancel_right theorem neg_add_rev : ∀a b : ℤ, -(a + b) = -b + -a := algebra.neg_add_rev theorem eq_add_neg_of_add_eq : ∀{a b c : ℤ}, a + c = b → a = b + -c := @algebra.eq_add_neg_of_add_eq _ _ theorem eq_neg_add_of_add_eq : ∀{a b c : ℤ}, b + a = c → a = -b + c := @algebra.eq_neg_add_of_add_eq _ _ theorem neg_add_eq_of_eq_add : ∀{a b c : ℤ}, b = a + c → -a + b = c := @algebra.neg_add_eq_of_eq_add _ _ theorem add_neg_eq_of_eq_add : ∀{a b c : ℤ}, a = c + b → a + -b = c := @algebra.add_neg_eq_of_eq_add _ _ theorem eq_add_of_add_neg_eq : ∀{a b c : ℤ}, a + -c = b → a = b + c := @algebra.eq_add_of_add_neg_eq _ _ theorem eq_add_of_neg_add_eq : ∀{a b c : ℤ}, -b + a = c → a = b + c := @algebra.eq_add_of_neg_add_eq _ _ theorem add_eq_of_eq_neg_add : ∀{a b c : ℤ}, b = -a + c → a + b = c := @algebra.add_eq_of_eq_neg_add _ _ theorem add_eq_of_eq_add_neg : ∀{a b c : ℤ}, a = c + -b → a + b = c := @algebra.add_eq_of_eq_add_neg _ _ theorem add_eq_iff_eq_neg_add : ∀a b c : ℤ, a + b = c ↔ b = -a + c := @algebra.add_eq_iff_eq_neg_add _ _ theorem add_eq_iff_eq_add_neg : ∀a b c : ℤ, a + b = c ↔ a = c + -b := @algebra.add_eq_iff_eq_add_neg _ _ definition sub (a b : ℤ) : ℤ := algebra.sub a b infix - := int.sub theorem sub_eq_add_neg : ∀a b : ℤ, a - b = a + -b := algebra.sub_eq_add_neg theorem sub_self : ∀a : ℤ, a - a = 0 := algebra.sub_self theorem sub_add_cancel : ∀a b : ℤ, a - b + b = a := algebra.sub_add_cancel theorem add_sub_cancel : ∀a b : ℤ, a + b - b = a := algebra.add_sub_cancel theorem eq_of_sub_eq_zero : ∀{a b : ℤ}, a - b = 0 → a = b := @algebra.eq_of_sub_eq_zero _ _ theorem eq_iff_sub_eq_zero : ∀a b : ℤ, a = b ↔ a - b = 0 := algebra.eq_iff_sub_eq_zero theorem zero_sub : ∀a : ℤ, 0 - a = -a := algebra.zero_sub theorem sub_zero : ∀a : ℤ, a - 0 = a := algebra.sub_zero theorem sub_neg_eq_add : ∀a b : ℤ, a - (-b) = a + b := algebra.sub_neg_eq_add theorem neg_sub : ∀a b : ℤ, -(a - b) = b - a := algebra.neg_sub theorem add_sub : ∀a b c : ℤ, a + (b - c) = a + b - c := algebra.add_sub theorem sub_add_eq_sub_sub_swap : ∀a b c : ℤ, a - (b + c) = a - c - b := algebra.sub_add_eq_sub_sub_swap theorem sub_eq_iff_eq_add : ∀a b c : ℤ, a - b = c ↔ a = c + b := algebra.sub_eq_iff_eq_add theorem eq_sub_iff_add_eq : ∀a b c : ℤ, a = b - c ↔ a + c = b := algebra.eq_sub_iff_add_eq theorem eq_iff_eq_of_sub_eq_sub : ∀{a b c d : ℤ}, a - b = c - d → a = b ↔ c = d := @algebra.eq_iff_eq_of_sub_eq_sub _ _ theorem eq_sub_of_add_eq : ∀{a b c : ℤ}, a + c = b → a = b - c := @algebra.eq_sub_of_add_eq _ _ theorem sub_eq_of_eq_add : ∀{a b c : ℤ}, a = c + b → a - b = c := @algebra.sub_eq_of_eq_add _ _ theorem eq_add_of_sub_eq : ∀{a b c : ℤ}, a - c = b → a = b + c := @algebra.eq_add_of_sub_eq _ _ theorem add_eq_of_eq_sub : ∀{a b c : ℤ}, a = c - b → a + b = c := @algebra.add_eq_of_eq_sub _ _ theorem sub_add_eq_sub_sub : ∀a b c : ℤ, a - (b + c) = a - b - c := algebra.sub_add_eq_sub_sub theorem neg_add_eq_sub : ∀a b : ℤ, -a + b = b - a := algebra.neg_add_eq_sub theorem neg_add : ∀a b : ℤ, -(a + b) = -a + -b := algebra.neg_add theorem sub_add_eq_add_sub : ∀a b c : ℤ, a - b + c = a + c - b := algebra.sub_add_eq_add_sub theorem sub_sub_ : ∀a b c : ℤ, a - b - c = a - (b + c) := algebra.sub_sub theorem add_sub_add_left_eq_sub : ∀a b c : ℤ, (c + a) - (c + b) = a - b := algebra.add_sub_add_left_eq_sub theorem eq_sub_of_add_eq' : ∀{a b c : ℤ}, c + a = b → a = b - c := @algebra.eq_sub_of_add_eq' _ _ theorem sub_eq_of_eq_add' : ∀{a b c : ℤ}, a = b + c → a - b = c := @algebra.sub_eq_of_eq_add' _ _ theorem eq_add_of_sub_eq' : ∀{a b c : ℤ}, a - b = c → a = b + c := @algebra.eq_add_of_sub_eq' _ _ theorem add_eq_of_eq_sub' : ∀{a b c : ℤ}, b = c - a → a + b = c := @algebra.add_eq_of_eq_sub' _ _ theorem ne_zero_of_mul_ne_zero_right : ∀{a b : ℤ}, a * b ≠ 0 → a ≠ 0 := @algebra.ne_zero_of_mul_ne_zero_right _ _ theorem ne_zero_of_mul_ne_zero_left : ∀{a b : ℤ}, a * b ≠ 0 → b ≠ 0 := @algebra.ne_zero_of_mul_ne_zero_left _ _ definition dvd (a b : ℤ) : Prop := algebra.dvd a b notation a ∣ b := dvd a b theorem dvd.intro : ∀{a b c : ℤ} (H : a * c = b), a ∣ b := @algebra.dvd.intro _ _ theorem dvd.intro_left : ∀{a b c : ℤ} (H : c * a = b), a ∣ b := @algebra.dvd.intro_left _ _ theorem exists_eq_mul_right_of_dvd : ∀{a b : ℤ} (H : a ∣ b), ∃c, b = a * c := @algebra.exists_eq_mul_right_of_dvd _ _ theorem dvd.elim : ∀{P : Prop} {a b : ℤ} (H₁ : a ∣ b) (H₂ : ∀c, b = a * c → P), P := @algebra.dvd.elim _ _ theorem exists_eq_mul_left_of_dvd : ∀{a b : ℤ} (H : a ∣ b), ∃c, b = c * a := @algebra.exists_eq_mul_left_of_dvd _ _ theorem dvd.elim_left : ∀{P : Prop} {a b : ℤ} (H₁ : a ∣ b) (H₂ : ∀c, b = c * a → P), P := @algebra.dvd.elim_left _ _ theorem dvd.refl : ∀a : ℤ, (a ∣ a) := algebra.dvd.refl theorem dvd.trans : ∀{a b c : ℤ} (H₁ : a ∣ b) (H₂ : b ∣ c), a ∣ c := @algebra.dvd.trans _ _ theorem eq_zero_of_zero_dvd : ∀{a : ℤ} (H : 0 ∣ a), a = 0 := @algebra.eq_zero_of_zero_dvd _ _ theorem dvd_zero : ∀a : ℤ, a ∣ 0 := algebra.dvd_zero theorem one_dvd : ∀a : ℤ, 1 ∣ a := algebra.one_dvd theorem dvd_mul_right : ∀a b : ℤ, a ∣ a * b := algebra.dvd_mul_right theorem dvd_mul_left : ∀a b : ℤ, a ∣ b * a := algebra.dvd_mul_left theorem dvd_mul_of_dvd_left : ∀{a b : ℤ} (H : a ∣ b) (c : ℤ), a ∣ b * c := @algebra.dvd_mul_of_dvd_left _ _ theorem dvd_mul_of_dvd_right : ∀{a b : ℤ} (H : a ∣ b) (c : ℤ), a ∣ c * b := @algebra.dvd_mul_of_dvd_right _ _ theorem mul_dvd_mul : ∀{a b c d : ℤ}, a ∣ b → c ∣ d → a * c ∣ b * d := @algebra.mul_dvd_mul _ _ theorem dvd_of_mul_right_dvd : ∀{a b c : ℤ}, a * b ∣ c → a ∣ c := @algebra.dvd_of_mul_right_dvd _ _ theorem dvd_of_mul_left_dvd : ∀{a b c : ℤ}, a * b ∣ c → b ∣ c := @algebra.dvd_of_mul_left_dvd _ _ theorem dvd_add : ∀{a b c : ℤ}, a ∣ b → a ∣ c → a ∣ b + c := @algebra.dvd_add _ _ theorem zero_mul : ∀a : ℤ, 0 * a = 0 := algebra.zero_mul theorem mul_zero : ∀a : ℤ, a * 0 = 0 := algebra.mul_zero theorem neg_mul_eq_neg_mul : ∀a b : ℤ, -(a * b) = -a * b := algebra.neg_mul_eq_neg_mul theorem neg_mul_eq_mul_neg : ∀a b : ℤ, -(a * b) = a * -b := algebra.neg_mul_eq_mul_neg theorem neg_mul_neg : ∀a b : ℤ, -a * -b = a * b := algebra.neg_mul_neg theorem neg_mul_comm : ∀a b : ℤ, -a * b = a * -b := algebra.neg_mul_comm theorem neg_eq_neg_one_mul : ∀a : ℤ, -a = -1 * a := algebra.neg_eq_neg_one_mul theorem mul_sub_left_distrib : ∀a b c : ℤ, a * (b - c) = a * b - a * c := algebra.mul_sub_left_distrib theorem mul_sub_right_distrib : ∀a b c : ℤ, (a - b) * c = a * c - b * c := algebra.mul_sub_right_distrib theorem mul_add_eq_mul_add_iff_sub_mul_add_eq : ∀a b c d e : ℤ, a * e + c = b * e + d ↔ (a - b) * e + c = d := algebra.mul_add_eq_mul_add_iff_sub_mul_add_eq theorem mul_self_sub_mul_self_eq : ∀a b : ℤ, a * a - b * b = (a + b) * (a - b) := algebra.mul_self_sub_mul_self_eq theorem mul_self_sub_one_eq : ∀a : ℤ, a * a - 1 = (a + 1) * (a - 1) := algebra.mul_self_sub_one_eq theorem dvd_neg_iff_dvd : ∀a b : ℤ, a ∣ -b ↔ a ∣ b := algebra.dvd_neg_iff_dvd theorem neg_dvd_iff_dvd : ∀a b : ℤ, -a ∣ b ↔ a ∣ b := algebra.neg_dvd_iff_dvd theorem dvd_sub : ∀a b c : ℤ, a ∣ b → a ∣ c → a ∣ b - c := algebra.dvd_sub theorem mul_ne_zero : ∀{a b : ℤ}, a ≠ 0 → b ≠ 0 → a * b ≠ 0 := @algebra.mul_ne_zero _ _ theorem mul.cancel_right : ∀{a b c : ℤ}, a ≠ 0 → b * a = c * a → b = c := @algebra.mul.cancel_right _ _ theorem mul.cancel_left : ∀{a b c : ℤ}, a ≠ 0 → a * b = a * c → b = c := @algebra.mul.cancel_left _ _ theorem mul_self_eq_mul_self_iff : ∀a b : ℤ, a * a = b * b ↔ a = b ∨ a = -b := algebra.mul_self_eq_mul_self_iff theorem mul_self_eq_one_iff : ∀a : ℤ, a * a = 1 ↔ a = 1 ∨ a = -1 := algebra.mul_self_eq_one_iff theorem dvd_of_mul_dvd_mul_left : ∀{a b c : ℤ}, a ≠ 0 → a*b ∣ a*c → b ∣ c := @algebra.dvd_of_mul_dvd_mul_left _ _ theorem dvd_of_mul_dvd_mul_right : ∀{a b c : ℤ}, a ≠ 0 → b*a ∣ c*a → b ∣ c := @algebra.dvd_of_mul_dvd_mul_right _ _ end port_algebra /- additional properties -/ theorem of_nat_sub_of_nat {m n : ℕ} (H : #nat m ≥ n) : of_nat m - of_nat n = of_nat (#nat m - n) := have H1 : m = (#nat m - n + n), from (nat.sub_add_cancel H)⁻¹, have H2 : m = (#nat m - n) + n, from congr_arg of_nat H1, sub_eq_of_eq_add H2 theorem neg_succ_of_nat_eq' (m : ℕ) : -[m +1] = -m - 1 := by rewrite [neg_succ_of_nat_eq, -of_nat_add_of_nat, neg_add] end int
ac789ac0d366a5e3fdcfeb9db39ee95b8ef3a907
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/ring_theory/ore_localization/basic.lean
0a968d6ae647e1410b2055ea2d12df1c862e6895
[ "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
33,711
lean
/- Copyright (c) 2022 Jakob von Raumer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jakob von Raumer, Kevin Klinge -/ import group_theory.monoid_localization import ring_theory.non_zero_divisors import ring_theory.ore_localization.ore_set import tactic.noncomm_ring /-! # Localization over right Ore sets. This file defines the localization of a monoid over a right Ore set and proves its universal mapping property. It then extends the definition and its properties first to semirings and then to rings. We show that in the case of a commutative monoid this definition coincides with the common monoid localization. Finally we show that in a ring without zero divisors, taking the Ore localization at `R - {0}` results in a division ring. ## Notations Introduces the notation `R[S⁻¹]` for the Ore localization of a monoid `R` at a right Ore subset `S`. Also defines a new heterogeneos division notation `r /ₒ s` for a numerator `r : R` and a denominator `s : S`. ## References * <https://ncatlab.org/nlab/show/Ore+localization> * [Zoran Škoda, *Noncommutative localization in noncommutative geometry*][skoda2006] ## Tags localization, Ore, non-commutative -/ universe u open ore_localization namespace ore_localization variables (R : Type*) [monoid R] (S : submonoid R) [ore_set S] /-- The setoid on `R × S` used for the Ore localization. -/ def ore_eqv : setoid (R × S) := { r := λ rs rs', ∃ (u : S) (v : R), rs'.1 * u = rs.1 * v ∧ (rs'.2 : R) * u = rs.2 * v, iseqv := begin refine ⟨_, _, _⟩, { rintro ⟨r,s⟩, use 1, use 1, simp [submonoid.one_mem] }, { rintros ⟨r, s⟩ ⟨r', s'⟩ ⟨u, v, hru, hsu⟩, rcases ore_condition (s : R) s' with ⟨r₂, s₂, h₁⟩, rcases ore_condition r₂ u with ⟨r₃, s₃, h₂⟩, have : (s : R) * ((v : R) * r₃) = (s : R) * (s₂ * s₃), { assoc_rw [h₁, h₂, hsu], symmetry, apply mul_assoc }, rcases ore_left_cancel (v * r₃) (s₂ * s₃) s this with ⟨w, hw⟩, use s₂ * s₃ * w, use u * r₃ * w, split; simp only [submonoid.coe_mul], { assoc_rw [hru, ←hw], simp [mul_assoc] }, { assoc_rw [hsu, ←hw], simp [mul_assoc] } }, { rintros ⟨r₁, s₁⟩ ⟨r₂, s₂⟩ ⟨r₃, s₃⟩ ⟨u, v, hur₁, hs₁u⟩ ⟨u', v', hur₂, hs₂u⟩, rcases ore_condition v' u with ⟨r', s', h⟩, use u' * s', use v * r', split; simp only [submonoid.coe_mul], { assoc_rw [hur₂, h, hur₁, mul_assoc] }, { assoc_rw [hs₂u, h, hs₁u, mul_assoc] } } end } end ore_localization /-- The ore localization of a monoid and a submonoid fulfilling the ore condition. -/ def ore_localization (R : Type*) [monoid R] (S : submonoid R) [ore_set S] := quotient (ore_localization.ore_eqv R S) namespace ore_localization section monoid variables {R : Type*} [monoid R] {S : submonoid R} variables (R S) [ore_set S] notation R `[`:1075 S `⁻¹]`:1075 := ore_localization R S local attribute [instance] ore_eqv variables {R S} /-- The division in the ore localization `R[S⁻¹]`, as a fraction of an element of `R` and `S`. -/ def ore_div (r : R) (s : S) : R[S⁻¹] := quotient.mk (r, s) infixl ` /ₒ `:70 := ore_div @[elab_as_eliminator] protected lemma ind {β : R [S ⁻¹] → Prop} (c : ∀ (r : R) (s : S), β (r /ₒ s)) : ∀ q, β q := by { apply quotient.ind, rintro ⟨r, s⟩, exact c r s } lemma ore_div_eq_iff {r₁ r₂ : R} {s₁ s₂ : S} : r₁ /ₒ s₁ = r₂ /ₒ s₂ ↔ (∃ (u : S) (v : R), r₂ * u = r₁ * v ∧ (s₂ : R) * u = s₁ * v) := quotient.eq' /-- A fraction `r /ₒ s` is equal to its expansion by an arbitrary factor `t` if `s * t ∈ S`. -/ protected lemma expand (r : R) (s : S) (t : R) (hst : (s : R) * t ∈ S) : r /ₒ s = (r * t) /ₒ (⟨s * t, hst⟩) := by { apply quotient.sound, refine ⟨s, t * s, _, _⟩; dsimp; rw [mul_assoc]; refl } /-- A fraction is equal to its expansion by an factor from s. -/ protected lemma expand' (r : R) (s s' : S) : r /ₒ s = (r * s') /ₒ (s * s') := ore_localization.expand r s s' (by norm_cast; apply set_like.coe_mem) /-- Fractions which differ by a factor of the numerator can be proven equal if those factors expand to equal elements of `R`. -/ protected lemma eq_of_num_factor_eq {r r' r₁ r₂ : R} {s t : S} (h : r * t = r' * t) : (r₁ * r * r₂) /ₒ s = (r₁ * r' * r₂) /ₒ s := begin rcases ore_condition r₂ t with ⟨r₂',t', hr₂⟩, calc (r₁ * r * r₂) /ₒ s = (r₁ * r * r₂ * t') /ₒ (s * t') : ore_localization.expand _ _ t' _ ... = ((r₁ * r) * (r₂ * t')) /ₒ (s * t') : by simp [←mul_assoc] ... = ((r₁ * r) * (t * r₂')) /ₒ (s * t') : by rw hr₂ ... = (r₁ * (r * t) * r₂') /ₒ (s * t') : by simp [←mul_assoc] ... = (r₁ * (r' * t) * r₂') /ₒ (s * t') : by rw h ... = (r₁ * r' * (t * r₂')) /ₒ (s * t') : by simp [←mul_assoc] ... = (r₁ * r' * (r₂ * t')) /ₒ (s * t') : by rw hr₂ ... = (r₁ * r' * r₂ * t') /ₒ (s * t') : by simp [←mul_assoc] ... = (r₁ * r' * r₂) /ₒ s : by symmetry; apply ore_localization.expand end /-- A function or predicate over `R` and `S` can be lifted to `R[S⁻¹]` if it is invariant under expansion on the right. -/ def lift_expand {C : Sort*} (P : R → S → C) (hP : ∀ (r t : R) (s : S) (ht : ((s : R) * t) ∈ S), P r s = P (r * t) ⟨s * t, ht⟩) : R[S⁻¹] → C := quotient.lift (λ (p : R × S), P p.1 p.2) $ λ p q pq, begin cases p with r₁ s₁, cases q with r₂ s₂, rcases pq with ⟨u, v, hr₂, hs₂⟩, dsimp at *, have s₁vS : (s₁ : R) * v ∈ S, { rw [←hs₂, ←S.coe_mul], exact set_like.coe_mem (s₂ * u) }, replace hs₂ : s₂ * u = ⟨(s₁ : R) * v, s₁vS⟩, { ext, simp [hs₂] }, rw [hP r₁ v s₁ s₁vS, hP r₂ u s₂ (by { norm_cast, rw hs₂, assumption }), hr₂], simpa [← hs₂] end @[simp] lemma lift_expand_of {C : Sort*} {P : R → S → C} {hP : ∀ (r t : R) (s : S) (ht : ((s : R) * t) ∈ S), P r s = P (r * t) ⟨s * t, ht⟩} (r : R) (s : S) : lift_expand P hP (r /ₒ s) = P r s := rfl /-- A version of `lift_expand` used to simultaneously lift functions with two arguments in ``R[S⁻¹]`.-/ def lift₂_expand {C : Sort*} (P : R → S → R → S → C) (hP : ∀ (r₁ t₁ : R) (s₁ : S) (ht₁ : (s₁ : R) * t₁ ∈ S) (r₂ t₂ : R) (s₂ : S) (ht₂ : (s₂ : R) * t₂ ∈ S), P r₁ s₁ r₂ s₂ = P (r₁ * t₁) ⟨s₁ * t₁, ht₁⟩ (r₂ * t₂) ⟨s₂ * t₂, ht₂⟩) : R[S⁻¹] → R[S⁻¹] → C := lift_expand (λ r₁ s₁, lift_expand (P r₁ s₁) $ λ r₂ t₂ s₂ ht₂, by simp [hP r₁ 1 s₁ (by simp) r₂ t₂ s₂ ht₂]) $ λ r₁ t₁ s₁ ht₁, begin ext x, induction x using ore_localization.ind with r₂ s₂, rw [lift_expand_of, lift_expand_of, hP r₁ t₁ s₁ ht₁ r₂ 1 s₂ (by simp)], simp, end @[simp] lemma lift₂_expand_of {C : Sort*} {P : R → S → R → S → C} {hP : ∀ (r₁ t₁ : R) (s₁ : S) (ht₁ : (s₁ : R) * t₁ ∈ S) (r₂ t₂ : R) (s₂ : S) (ht₂ : (s₂ : R) * t₂ ∈ S), P r₁ s₁ r₂ s₂ = P (r₁ * t₁) ⟨s₁ * t₁, ht₁⟩ (r₂ * t₂) ⟨s₂ * t₂, ht₂⟩} (r₁ : R) (s₁ : S) (r₂ : R) (s₂ : S) : lift₂_expand P hP (r₁ /ₒ s₁) (r₂ /ₒ s₂) = P r₁ s₁ r₂ s₂ := rfl private def mul' (r₁ : R) (s₁ : S) (r₂ : R) (s₂ : S) : R[S⁻¹] := (r₁ * ore_num r₂ s₁) /ₒ (s₂ * ore_denom r₂ s₁) private lemma mul'_char (r₁ r₂ : R) (s₁ s₂ : S) (u : S) (v : R) (huv : r₂ * (u : R) = s₁ * v) : mul' r₁ s₁ r₂ s₂ = (r₁ * v) /ₒ (s₂ * u) := begin simp only [mul'], have h₀ := ore_eq r₂ s₁, set v₀ := ore_num r₂ s₁, set u₀ := ore_denom r₂ s₁, rcases ore_condition (u₀ : R) u with ⟨r₃, s₃, h₃⟩, have := calc (s₁ : R) * (v * r₃) = r₂ * u * r₃ : by assoc_rw ←huv; symmetry; apply mul_assoc ... = r₂ * u₀ * s₃ : by assoc_rw ←h₃; refl ... = s₁ * (v₀ * s₃) : by assoc_rw h₀; apply mul_assoc, rcases ore_left_cancel _ _ _ this with ⟨s₄, hs₄⟩, symmetry, rw ore_div_eq_iff, use s₃ * s₄, use r₃ * s₄, simp only [submonoid.coe_mul], split, { assoc_rw ←hs₄, simp only [mul_assoc] }, { assoc_rw h₃, simp only [mul_assoc] } end /-- The multiplication on the Ore localization of monoids. -/ protected def mul : R[S⁻¹] → R[S⁻¹] → R[S⁻¹] := lift₂_expand mul' $ λ r₂ p s₂ hp r₁ r s₁ hr, begin have h₁ := ore_eq r₁ s₂, set r₁' := ore_num r₁ s₂, set s₂' := ore_denom r₁ s₂, rcases ore_condition (↑s₂ * r₁') ⟨s₂ * p, hp⟩ with ⟨p', s_star, h₂⟩, dsimp at h₂, rcases ore_condition r (s₂' * s_star) with ⟨p_flat, s_flat, h₃⟩, simp only [S.coe_mul] at h₃, have : r₁ * r * s_flat = s₂ * p * (p' * p_flat), { rw [←mul_assoc, ←h₂, ←h₁, mul_assoc, h₃], simp only [mul_assoc] }, rw mul'_char (r₂ * p) (r₁ * r) ⟨↑s₂ * p, hp⟩ ⟨↑s₁ * r, hr⟩ _ _ this, clear this, have hsssp : ↑s₁ * ↑s₂' * ↑s_star * p_flat ∈ S, { rw [mul_assoc, mul_assoc, ←mul_assoc ↑s₂', ←h₃, ←mul_assoc], exact S.mul_mem hr (set_like.coe_mem s_flat) }, have : (⟨↑s₁ * r, hr⟩ : S) * s_flat = ⟨s₁ * s₂' * s_star * p_flat, hsssp⟩, { ext, simp only [set_like.coe_mk, submonoid.coe_mul], rw [mul_assoc, h₃, ←mul_assoc, ←mul_assoc] }, rw this, clear this, rcases ore_left_cancel (p * p') (r₁' * ↑s_star) s₂ (by simp [←mul_assoc, h₂]) with ⟨s₂'', h₂''⟩, rw [←mul_assoc, mul_assoc r₂, ore_localization.eq_of_num_factor_eq h₂''], norm_cast at ⊢ hsssp, rw [←ore_localization.expand _ _ _ hsssp, ←mul_assoc], apply ore_localization.expand end instance : has_mul R[S⁻¹] := ⟨ore_localization.mul⟩ lemma ore_div_mul_ore_div {r₁ r₂ : R} {s₁ s₂ : S} : (r₁ /ₒ s₁) * (r₂ /ₒ s₂) = (r₁ * ore_num r₂ s₁) /ₒ (s₂ * ore_denom r₂ s₁) := rfl /-- A characterization lemma for the multiplication on the Ore localization, allowing for a choice of Ore numerator and Ore denominator. -/ lemma ore_div_mul_char (r₁ r₂ : R) (s₁ s₂ : S) (r' : R) (s' : S) (huv : r₂ * (s' : R) = s₁ * r') : (r₁ /ₒ s₁) * (r₂ /ₒ s₂) = (r₁ * r') /ₒ (s₂ * s') := mul'_char r₁ r₂ s₁ s₂ s' r' huv /-- Another characterization lemma for the multiplication on the Ore localizaion delivering Ore witnesses and conditions bundled in a sigma type. -/ def ore_div_mul_char' (r₁ r₂ : R) (s₁ s₂ : S) : Σ' r' : R, Σ' s' : S, r₂ * (s' : R) = s₁ * r' ∧ (r₁ /ₒ s₁) * (r₂ /ₒ s₂) = (r₁ * r') /ₒ (s₂ * s') := ⟨ore_num r₂ s₁, ore_denom r₂ s₁, ore_eq r₂ s₁, ore_div_mul_ore_div⟩ instance : has_one R[S⁻¹] := ⟨1 /ₒ 1⟩ protected lemma one_def : (1 : R[S⁻¹]) = 1 /ₒ 1 := rfl instance : inhabited R[S⁻¹] := ⟨1⟩ @[simp] protected lemma div_eq_one' {r : R} (hr : r ∈ S) : r /ₒ ⟨r, hr⟩ = 1 := by { rw [ore_localization.one_def, ore_div_eq_iff], exact ⟨⟨r, hr⟩, 1, by simp, by simp⟩ } @[simp] protected lemma div_eq_one {s : S} : (s : R) /ₒ s = 1 := by { cases s; apply ore_localization.div_eq_one' } protected lemma one_mul (x : R[S⁻¹]) : 1 * x = x := begin induction x using ore_localization.ind with r s, simp [ore_localization.one_def, ore_div_mul_char (1 : R) r (1 : S) s r 1 (by simp)] end protected lemma mul_one (x : R[S⁻¹]) : x * 1 = x := begin induction x using ore_localization.ind with r s, simp [ore_localization.one_def, ore_div_mul_char r 1 s 1 1 s (by simp)] end protected lemma mul_assoc (x y z : R[S⁻¹]) : x * y * z = x * (y * z) := begin induction x using ore_localization.ind with r₁ s₁, induction y using ore_localization.ind with r₂ s₂, induction z using ore_localization.ind with r₃ s₃, rcases ore_div_mul_char' r₁ r₂ s₁ s₂ with ⟨ra, sa, ha, ha'⟩, rw ha', clear ha', rcases ore_div_mul_char' r₂ r₃ s₂ s₃ with ⟨rb, sb, hb, hb'⟩, rw hb', clear hb', rcases ore_condition rb sa with ⟨rc, sc, hc⟩, rw ore_div_mul_char (r₁ * ra) r₃ (s₂ * sa) s₃ rc (sb * sc) (by { simp only [submonoid.coe_mul], assoc_rw [hb, hc] }), rw [mul_assoc, ←mul_assoc s₃], symmetry, apply ore_div_mul_char, assoc_rw [hc, ←ha], apply mul_assoc end instance : monoid R[S⁻¹] := { one_mul := ore_localization.one_mul, mul_one := ore_localization.mul_one, mul_assoc := ore_localization.mul_assoc, .. ore_localization.has_mul, .. ore_localization.has_one } protected lemma mul_inv (s s' : S) : ((s : R) /ₒ s') * (s' /ₒ s) = 1 := by simp [ore_div_mul_char (s :R) s' s' s 1 1 (by simp)] @[simp] protected lemma mul_one_div {r : R} {s t : S} : (r /ₒ s) * (1 /ₒ t) = r /ₒ (t * s) := by simp [ore_div_mul_char r 1 s t 1 s (by simp)] @[simp] protected lemma mul_cancel {r : R} {s t : S} : (r /ₒ s) * (s /ₒ t) = r /ₒ t := by simp [ore_div_mul_char r s s t 1 1 (by simp)] @[simp] protected lemma mul_cancel' {r₁ r₂ : R} {s t : S} : (r₁ /ₒ s) * ((s * r₂) /ₒ t) = (r₁ * r₂) /ₒ t := by simp [ore_div_mul_char r₁ (s * r₂) s t r₂ 1 (by simp)] @[simp] lemma div_one_mul {p r : R} {s : S} : (r /ₒ 1) * (p /ₒ s) = (r * p) /ₒ s := --TODO use coercion r ↦ r /ₒ 1 by simp [ore_div_mul_char r p 1 s p 1 (by simp)] /-- The fraction `s /ₒ 1` as a unit in `R[S⁻¹]`, where `s : S`. -/ def numerator_unit (s : S) : units R[S⁻¹] := { val := (s : R) /ₒ 1, inv := (1 : R) /ₒ s, val_inv := ore_localization.mul_inv s 1, inv_val := ore_localization.mul_inv 1 s } /-- The multiplicative homomorphism from `R` to `R[S⁻¹]`, mapping `r : R` to the fraction `r /ₒ 1`. -/ def numerator_hom : R →* R[S⁻¹] := { to_fun := λ r, r /ₒ 1, map_one' := rfl, map_mul' := λ r₁ r₂, div_one_mul.symm } lemma numerator_hom_apply {r : R} : numerator_hom r = r /ₒ (1 : S) := rfl lemma numerator_is_unit (s : S) : is_unit ((numerator_hom (s : R)) : R[S⁻¹]) := ⟨numerator_unit s, rfl⟩ section UMP variables {T : Type*} [monoid T] variables (f : R →* T) (fS : S →* units T) variables (hf : ∀ (s : S), f s = fS s) include f fS hf /-- The universal lift from a morphism `R →* T`, which maps elements of `S` to units of `T`, to a morphism `R[S⁻¹] →* T`. -/ def universal_mul_hom : R[S⁻¹] →* T := { to_fun := λ x, x.lift_expand (λ r s, (f r) * ((fS s)⁻¹ : units T)) $ λ r t s ht, begin have : ((fS ⟨s * t, ht⟩) : T) = fS s * f t, { simp only [←hf, set_like.coe_mk, monoid_hom.map_mul] }, conv_rhs { rw [monoid_hom.map_mul, ←mul_one (f r), ←units.coe_one, ←mul_left_inv (fS s)], rw [units.coe_mul, ←mul_assoc, mul_assoc _ ↑(fS s), ←this, mul_assoc] }, simp only [mul_one, units.mul_inv] end, map_one' := by rw [ore_localization.one_def, lift_expand_of]; simp, map_mul' := λ x y, begin induction x using ore_localization.ind with r₁ s₁, induction y using ore_localization.ind with r₂ s₂, rcases ore_div_mul_char' r₁ r₂ s₁ s₂ with ⟨ra, sa, ha, ha'⟩, rw ha', clear ha', rw [lift_expand_of, lift_expand_of, lift_expand_of], conv_rhs { congr, skip, congr, rw [←mul_one (f r₂), ←(fS sa).mul_inv, ←mul_assoc, ←hf, ←f.map_mul, ha, f.map_mul] }, rw [mul_assoc, mul_assoc, mul_assoc, ←mul_assoc _ (f s₁), hf s₁, (fS s₁).inv_mul, one_mul, f.map_mul, mul_assoc, fS.map_mul, ←units.coe_mul], refl end } lemma universal_mul_hom_apply {r : R} {s : S} : universal_mul_hom f fS hf (r /ₒ s) = (f r) * ((fS s)⁻¹ : units T) := rfl lemma universal_mul_hom_commutes {r : R} : universal_mul_hom f fS hf (numerator_hom r) = f r := by simp [numerator_hom_apply, universal_mul_hom_apply] /-- The universal morphism `universal_mul_hom` is unique. -/ lemma universal_mul_hom_unique (φ : R[S⁻¹] →* T) (huniv : ∀ (r : R), φ (numerator_hom r) = f r) : φ = universal_mul_hom f fS hf := begin ext, induction x using ore_localization.ind with r s, rw [universal_mul_hom_apply, ←huniv r, numerator_hom_apply, ←mul_one (φ (r /ₒ s)), ←units.coe_one, ←mul_right_inv (fS s), units.coe_mul, ←mul_assoc, ←hf, ←huniv, ←φ.map_mul, numerator_hom_apply, ore_localization.mul_cancel], end end UMP end monoid section comm_monoid variables {R : Type*} [comm_monoid R] {S : submonoid R} [ore_set S] lemma ore_div_mul_ore_div_comm {r₁ r₂ : R} {s₁ s₂ : S} : (r₁ /ₒ s₁) * (r₂ /ₒ s₂) = (r₁ * r₂) /ₒ (s₁ * s₂) := by rw [ore_div_mul_char r₁ r₂ s₁ s₂ r₂ s₁ (by simp [mul_comm]), mul_comm s₂] instance : comm_monoid R[S⁻¹] := { mul_comm := λ x y, begin induction x using ore_localization.ind with r₁ s₁, induction y using ore_localization.ind with r₂ s₂, rw [ore_div_mul_ore_div_comm, ore_div_mul_ore_div_comm, mul_comm r₁, mul_comm s₁], end, ..ore_localization.monoid } variables (R S) /-- The morphism `numerator_hom` is a monoid localization map in the case of commutative `R`. -/ protected def localization_map : S.localization_map R[S⁻¹] := { to_fun := numerator_hom, map_one' := rfl, map_mul' := λ r₁ r₂, by simp, map_units' := numerator_is_unit, surj' := λ z, begin induction z using ore_localization.ind with r s, use (r, s), dsimp, rw [numerator_hom_apply, numerator_hom_apply], simp end, eq_iff_exists' := λ r₁ r₂, begin dsimp, split, { intro h, rw [numerator_hom_apply, numerator_hom_apply, ore_div_eq_iff] at h, rcases h with ⟨u, v, h₁, h₂⟩, dsimp at h₂, rw [one_mul, one_mul] at h₂, subst h₂, use u, exact h₁.symm }, { rintro ⟨s, h⟩, rw [numerator_hom_apply, numerator_hom_apply, ore_div_eq_iff], use s, use s, simp [h, one_mul] } end } /-- If `R` is commutative, Ore localization and monoid localization are isomorphic. -/ protected noncomputable def equiv_monoid_localization : localization S ≃* R[S⁻¹] := localization.mul_equiv_of_quotient (ore_localization.localization_map R S) end comm_monoid section semiring variables {R : Type*} [semiring R] {S : submonoid R} [ore_set S] private def add'' (r₁ : R) (s₁ : S) (r₂ : R) (s₂ : S) : R[S⁻¹] := (r₁ * ore_denom (s₁ : R) s₂ + r₂ * ore_num s₁ s₂) /ₒ (s₁ * ore_denom s₁ s₂) private lemma add''_char (r₁ : R) (s₁ : S) (r₂ : R) (s₂ : S) (rb : R) (sb : S) (hb : (s₁ : R) * sb = (s₂ : R) * rb) : add'' r₁ s₁ r₂ s₂ = (r₁ * sb + r₂ * rb) /ₒ (s₁ * sb) := begin simp only [add''], have ha := ore_eq (s₁ : R) s₂, set! ra := ore_num (s₁ : R) s₂ with h, rw ←h at *, clear h, -- r tilde set! sa := ore_denom (s₁ : R) s₂ with h, rw ←h at *, clear h, -- s tilde rcases ore_condition (sa : R) sb with ⟨rc, sc, hc⟩, -- s*, r* have : (s₂ : R) * (rb * rc) = s₂ * (ra * sc), { rw [←mul_assoc, ←hb, mul_assoc, ←hc, ←mul_assoc, ←mul_assoc, ha] }, rcases ore_left_cancel _ _ s₂ this with ⟨sd, hd⟩, -- s# symmetry, rw ore_div_eq_iff, use sc * sd, use rc * sd, split; simp only [submonoid.coe_mul], { noncomm_ring, assoc_rw [hd, hc], noncomm_ring }, { assoc_rewrite [hc], noncomm_ring } end local attribute [instance] ore_localization.ore_eqv private def add' (r₂ : R) (s₂ : S) : R[S⁻¹] → R[S⁻¹] := --plus tilde quotient.lift (λ (r₁s₁ : R × S), add'' r₁s₁.1 r₁s₁.2 r₂ s₂) $ begin rintros ⟨r₁', s₁'⟩ ⟨r₁, s₁⟩ ⟨sb, rb, hb, hb'⟩, -- s*, r* rcases ore_condition (s₁' : R) s₂ with ⟨rc, sc, hc⟩, --s~~, r~~ rcases ore_condition rb sc with ⟨rd, sd, hd⟩, -- s#, r# dsimp at *, rw add''_char _ _ _ _ rc sc hc, have : ↑s₁ * ↑(sb * sd) = ↑s₂ * (rc * rd), { simp only [submonoid.coe_mul], assoc_rewrite [hb', hd, hc], noncomm_ring }, rw add''_char _ _ _ _ (rc * rd : R) (sb * sd : S) this, simp only [submonoid.coe_mul], assoc_rw [hb, hd], rw [←mul_assoc, ←add_mul, ore_div_eq_iff], use 1, use rd, split, { simp }, { simp only [mul_one, submonoid.coe_one, submonoid.coe_mul] at ⊢ this, assoc_rw [hc, this] }, end private lemma add'_comm (r₁ r₂ : R) (s₁ s₂ : S) : add' r₁ s₁ (r₂ /ₒ s₂) = add' r₂ s₂ (r₁ /ₒ s₁) := begin simp only [add', ore_div, add'', quotient.lift_mk, quotient.eq], have hb := ore_eq ↑s₂ s₁, set rb := ore_num ↑s₂ s₁ with h, -- r~~ rw ←h, clear h, set sb := ore_denom ↑s₂ s₁ with h, rw ←h, clear h, -- s~~ have ha := ore_eq ↑s₁ s₂, set ra := ore_num ↑s₁ s₂ with h, -- r~ rw ←h, clear h, set sa := ore_denom ↑s₁ s₂ with h, rw ←h, clear h, -- s~ rcases ore_condition ra sb with ⟨rc, sc, hc⟩, -- r#, s# have : (s₁ : R) * (rb * rc) = s₁ * (sa * sc), { rw [←mul_assoc, ←hb, mul_assoc, ←hc, ←mul_assoc, ←ha, mul_assoc] }, rcases ore_left_cancel _ _ s₁ this with ⟨sd, hd⟩, -- s+ use sc * sd, use rc * sd, dsimp, split, { rw [add_mul, add_mul, add_comm], assoc_rw [←hd, hc], noncomm_ring }, { rw [mul_assoc, ←mul_assoc ↑sa, ←hd, hb], noncomm_ring } end /-- The addition on the Ore localization. -/ private def add : R[S⁻¹] → R[S⁻¹] → R[S⁻¹] := λ x, quotient.lift (λ rs : R × S, add' rs.1 rs.2 x) begin rintros ⟨r₁, s₁⟩ ⟨r₂, s₂⟩ hyz, induction x using ore_localization.ind with r₃ s₃, dsimp, rw [add'_comm, add'_comm r₂], simp [(/ₒ), quotient.sound hyz], end instance : has_add R[S⁻¹] := ⟨add⟩ lemma ore_div_add_ore_div {r r' : R} {s s' : S} : r /ₒ s + r' /ₒ s' = (r * ore_denom (s : R) s' + r' * ore_num s s') /ₒ (s * ore_denom s s') := rfl /-- A characterization of the addition on the Ore localizaion, allowing for arbitrary Ore numerator and Ore denominator. -/ lemma ore_div_add_char {r r' : R} (s s' : S) (rb : R) (sb : S) (h : (s : R) * sb = s' * rb) : r /ₒ s + r' /ₒ s' = (r * sb + r' * rb) /ₒ (s * sb) := add''_char r s r' s' rb sb h /-- Another characterization of the addition on the Ore localization, bundling up all witnesses and conditions into a sigma type. -/ def ore_div_add_char' (r r' : R) (s s' : S) : Σ' r'' : R, Σ' s'' : S, (s : R) * s'' = s' * r'' ∧ r /ₒ s + r' /ₒs' = (r * s'' + r' * r'') /ₒ (s * s'') := ⟨ore_num s s', ore_denom s s', ore_eq s s', ore_div_add_ore_div⟩ @[simp] lemma add_ore_div {r r' : R} {s : S} : (r /ₒ s) + (r' /ₒ s) = (r + r') /ₒ s := by simp [ore_div_add_char s s 1 1 (by simp)] protected lemma add_assoc (x y z : R[S⁻¹]) : (x + y) + z = x + (y + z) := begin induction x using ore_localization.ind with r₁ s₁, induction y using ore_localization.ind with r₂ s₂, induction z using ore_localization.ind with r₃ s₃, rcases ore_div_add_char' r₁ r₂ s₁ s₂ with ⟨ra, sa, ha, ha'⟩, rw ha', clear ha', rcases ore_div_add_char' r₂ r₃ s₂ s₃ with ⟨rb, sb, hb, hb'⟩, rw hb', clear hb', rcases ore_div_add_char' (r₁ * sa + r₂ * ra) r₃ (s₁ * sa) s₃ with ⟨rc, sc, hc, q⟩, rw q, clear q, rcases ore_div_add_char' r₁ (r₂ * sb + r₃ * rb) s₁ (s₂ * sb) with ⟨rd, sd, hd, q⟩, rw q, clear q, noncomm_ring, rw add_comm (r₂ * _), repeat { rw ←add_ore_div }, congr' 1, { rcases ore_condition (sd : R) (sa * sc) with ⟨re, se, he⟩, { simp_rw ←submonoid.coe_mul at hb hc hd, assoc_rw [subtype.coe_eq_of_eq_mk hc], rw [←ore_localization.expand, subtype.coe_eq_of_eq_mk hd, ←mul_assoc, ←ore_localization.expand, subtype.coe_eq_of_eq_mk hb], apply ore_localization.expand } }, congr' 1, { rw [←ore_localization.expand', ←mul_assoc, ←mul_assoc, ←ore_localization.expand', ←ore_localization.expand'] }, { simp_rw [←submonoid.coe_mul] at ha hd, rw [subtype.coe_eq_of_eq_mk hd, ←mul_assoc, ←mul_assoc, ←mul_assoc, ←ore_localization.expand, ←ore_localization.expand', subtype.coe_eq_of_eq_mk ha, ←ore_localization.expand], apply ore_localization.expand' } end private def zero : R[S⁻¹] := 0 /ₒ 1 instance : has_zero R[S⁻¹] := ⟨zero⟩ protected lemma zero_def : (0 : R[S⁻¹]) = 0 /ₒ 1 := rfl @[simp] lemma zero_div_eq_zero (s : S) : 0 /ₒ s = 0 := by { rw [ore_localization.zero_def, ore_div_eq_iff], exact ⟨s, 1, by simp⟩ } protected lemma zero_add (x : R[S⁻¹]) : 0 + x = x := begin induction x using ore_localization.ind, rw [←zero_div_eq_zero, add_ore_div], simp end protected lemma add_comm (x y : R[S⁻¹]) : x + y = y + x := begin induction x using ore_localization.ind, induction y using ore_localization.ind, change add' _ _ (_ /ₒ _) = _, apply add'_comm end instance : add_comm_monoid R[S⁻¹] := { add_comm := ore_localization.add_comm, add_assoc := ore_localization.add_assoc, zero := zero, zero_add := ore_localization.zero_add, add_zero := λ x, by rw [ore_localization.add_comm, ore_localization.zero_add], .. ore_localization.has_add } protected lemma zero_mul (x : R[S⁻¹]) : 0 * x = 0 := begin induction x using ore_localization.ind with r s, rw [ore_localization.zero_def, ore_div_mul_char 0 r 1 s r 1 (by simp)], simp end protected lemma mul_zero (x : R[S⁻¹]) : x * 0 = 0 := begin induction x using ore_localization.ind with r s, rw [ore_localization.zero_def, ore_div_mul_char r 0 s 1 0 1 (by simp)], simp end protected lemma left_distrib (x y z : R[S⁻¹]) : x * (y + z) = x * y + x * z := begin induction x using ore_localization.ind with r₁ s₁, induction y using ore_localization.ind with r₂ s₂, induction z using ore_localization.ind with r₃ s₃, rcases ore_div_add_char' r₂ r₃ s₂ s₃ with ⟨ra, sa, ha, q⟩, rw q, clear q, rw ore_localization.expand' r₂ s₂ sa, rcases ore_div_mul_char' r₁ (r₂ * sa) s₁ (s₂ * sa) with ⟨rb, sb, hb, q⟩, rw q, clear q, have hs₃rasb : ↑s₃ * (ra * sb) ∈ S, { rw [←mul_assoc, ←ha], norm_cast, apply set_like.coe_mem }, rw ore_localization.expand _ _ _ hs₃rasb, have ha' : (↑(s₂ * sa * sb)) = ↑s₃ * (ra * sb), { simp [ha, ←mul_assoc] }, rw ←subtype.coe_eq_of_eq_mk ha', rcases ore_div_mul_char' r₁ (r₃ * (ra * sb)) s₁ (s₂ * sa * sb) with ⟨rc, sc, hc, hc'⟩, rw hc', rw ore_div_add_char (s₂ * sa * sb) (s₂ * sa * sb * sc) 1 sc (by simp), rw ore_localization.expand' (r₂ * ↑sa + r₃ * ra) (s₂ * sa) (sb * sc), conv_lhs { congr, skip, congr, rw [add_mul, S.coe_mul, ←mul_assoc, hb, ←mul_assoc, mul_assoc r₃, hc, mul_assoc, ←mul_add] }, rw ore_localization.mul_cancel', simp only [mul_one, submonoid.coe_mul, mul_add, ←mul_assoc], end lemma right_distrib (x y z : R[S⁻¹]) : (x + y) * z = x * z + y * z := begin induction x using ore_localization.ind with r₁ s₁, induction y using ore_localization.ind with r₂ s₂, induction z using ore_localization.ind with r₃ s₃, rcases ore_div_add_char' r₁ r₂ s₁ s₂ with ⟨ra, sa, ha, ha'⟩, rw ha', clear ha', norm_cast at ha, rw ore_localization.expand' r₁ s₁ sa, rw ore_localization.expand r₂ s₂ ra (by rw ←ha; apply set_like.coe_mem), rw ←subtype.coe_eq_of_eq_mk ha, repeat { rw ore_div_mul_ore_div }, simp only [add_mul, add_ore_div] end instance : semiring R[S⁻¹] := { zero_mul := ore_localization.zero_mul, mul_zero := ore_localization.mul_zero, left_distrib := ore_localization.left_distrib, right_distrib := right_distrib, .. ore_localization.add_comm_monoid, .. ore_localization.monoid } section UMP variables {T : Type*} [semiring T] variables (f : R →+* T) (fS : S →* units T) variables (hf : ∀ (s : S), f s = fS s) include f fS hf /-- The universal lift from a ring homomorphism `f : R →+* T`, which maps elements in `S` to units of `T`, to a ring homomorphism `R[S⁻¹] →+* T`. This extends the construction on monoids. -/ def universal_hom : R[S⁻¹] →+* T := { map_zero' := begin rw [monoid_hom.to_fun_eq_coe, ore_localization.zero_def, universal_mul_hom_apply], simp end, map_add' := λ x y, begin induction x using ore_localization.ind with r₁ s₁, induction y using ore_localization.ind with r₂ s₂, rcases ore_div_add_char' r₁ r₂ s₁ s₂ with ⟨r₃, s₃, h₃, h₃'⟩, rw h₃', clear h₃', simp only [universal_mul_hom_apply, ring_hom.coe_monoid_hom, ring_hom.to_monoid_hom_eq_coe, monoid_hom.to_fun_eq_coe], simp only [mul_inv_rev, monoid_hom.map_mul, ring_hom.map_add, ring_hom.map_mul, units.coe_mul], rw [add_mul, ←mul_assoc, mul_assoc (f r₁), hf, ←units.coe_mul], simp only [mul_one, mul_right_inv, units.coe_one], congr' 1, rw [mul_assoc], congr' 1, norm_cast at h₃, have h₃' := subtype.coe_eq_of_eq_mk h₃, rw [←units.coe_mul, ←mul_inv_rev, ←fS.map_mul, h₃'], have hs₂r₃ : ↑s₂ * r₃ ∈ S, { rw ←h₃, exact set_like.coe_mem (s₁ * s₃)}, apply (units.inv_mul_cancel_left (fS s₂) _).symm.trans, conv_lhs { congr, skip, rw [←units.mul_inv_cancel_left (fS ⟨s₂ * r₃, hs₂r₃⟩) (fS s₂), mul_assoc, mul_assoc], congr, skip, rw [←hf, ←mul_assoc (f s₂), ←f.map_mul], conv { congr, skip, congr, rw [←h₃] }, rw [hf, ←mul_assoc, ←h₃', units.inv_mul] }, rw [one_mul, ←h₃', units.mul_inv, mul_one], end, .. universal_mul_hom f.to_monoid_hom fS hf } lemma universal_hom_apply {r : R} {s : S} : universal_hom f fS hf (r /ₒ s) = (f r) * ((fS s)⁻¹ : units T) := rfl lemma universal_hom_commutes {r : R} : universal_hom f fS hf (numerator_hom r) = f r := by simp [numerator_hom_apply, universal_hom_apply] lemma universal_hom_unique (φ : R[S⁻¹] →+* T) (huniv : ∀ (r : R), φ (numerator_hom r) = f r) : φ = universal_hom f fS hf := ring_hom.coe_monoid_hom_injective $ universal_mul_hom_unique (ring_hom.to_monoid_hom f) fS hf ↑φ huniv end UMP end semiring section ring variables {R : Type*} [ring R] {S : submonoid R} [ore_set S] /-- Negation on the Ore localization is defined via negation on the numerator. -/ protected def neg : R[S⁻¹] → R[S⁻¹] := lift_expand (λ (r : R) (s : S), (- r) /ₒ s) $ λ r t s ht, by rw [neg_mul_eq_neg_mul, ←ore_localization.expand] instance : has_neg R[S⁻¹] := ⟨ore_localization.neg⟩ @[simp] protected lemma neg_def (r : R) (s : S) : - (r /ₒ s) = (- r) /ₒ s := rfl protected lemma add_left_neg (x : R[S⁻¹]) : (- x) + x = 0 := by induction x using ore_localization.ind with r s; simp instance : ring R[S⁻¹] := { add_left_neg := ore_localization.add_left_neg, .. ore_localization.semiring, .. ore_localization.has_neg } open_locale non_zero_divisors lemma numerator_hom_inj (hS : S ≤ R⁰) : function.injective (numerator_hom : R → R[S⁻¹]) := λ r₁ r₂ h, begin rw [numerator_hom_apply, numerator_hom_apply, ore_div_eq_iff] at h, rcases h with ⟨u, v, h₁, h₂⟩, simp only [S.coe_one, one_mul] at h₂, rwa [←h₂, mul_cancel_right_mem_non_zero_divisor (hS (set_like.coe_mem u)), eq_comm] at h₁, end lemma nontrivial_of_non_zero_divisors [nontrivial R] (hS : S ≤ R⁰) : nontrivial R[S⁻¹] := ⟨⟨0, 1, λ h, begin rw [ore_localization.one_def, ore_localization.zero_def] at h, apply non_zero_divisors.coe_ne_zero 1 (numerator_hom_inj hS h).symm end⟩⟩ end ring section division_ring open_locale non_zero_divisors open_locale classical variables {R : Type*} [ring R] [nontrivial R] [ore_set R⁰] instance : nontrivial R[R⁰⁻¹] := nontrivial_of_non_zero_divisors (refl R⁰) variables [no_zero_divisors R] noncomputable theory /-- The inversion of Ore fractions for a ring without zero divisors, satisying `0⁻¹ = 0` and `(r /ₒ r')⁻¹ = r' /ₒ r` for `r ≠ 0`. -/ protected def inv : R[R⁰⁻¹] → R[R⁰⁻¹] := lift_expand (λ r s, if hr: r = (0 : R) then (0 : R[R⁰⁻¹]) else (s /ₒ ⟨r, λ _, eq_zero_of_ne_zero_of_mul_right_eq_zero hr⟩)) begin intros r t s hst, by_cases hr : r = 0, { simp [hr] }, { by_cases ht : t = 0, { exfalso, apply non_zero_divisors.coe_ne_zero ⟨_, hst⟩, simp [ht, mul_zero] }, { simp only [hr, ht, set_like.coe_mk, dif_neg, not_false_iff, or_self, mul_eq_zero], apply ore_localization.expand } } end instance : has_inv R[R⁰⁻¹] := ⟨ore_localization.inv⟩ protected lemma inv_def {r : R} {s : R⁰} : (r /ₒ s)⁻¹ = if hr: r = (0 : R) then (0 : R[R⁰⁻¹]) else (s /ₒ ⟨r, λ _, eq_zero_of_ne_zero_of_mul_right_eq_zero hr⟩) := rfl protected lemma mul_inv_cancel (x : R[R⁰⁻¹]) (h : x ≠ 0) : x * x⁻¹ = 1 := begin induction x using ore_localization.ind with r s, rw [ore_localization.inv_def, ore_localization.one_def], by_cases hr : r = 0, { exfalso, apply h, simp [hr] }, { simp [hr], apply ore_localization.div_eq_one' } end protected lemma inv_zero : (0 : R[R⁰⁻¹])⁻¹ = 0 := by { rw [ore_localization.zero_def, ore_localization.inv_def], simp } instance : division_ring R[(R⁰)⁻¹] := { mul_inv_cancel := ore_localization.mul_inv_cancel, inv_zero := ore_localization.inv_zero, .. ore_localization.nontrivial, .. ore_localization.has_inv, .. ore_localization.ring } end division_ring end ore_localization
e524797fb2d0d0a10a4e2031a785447f077a624c
4b846d8dabdc64e7ea03552bad8f7fa74763fc67
/tests/lean/run/basic_monitor2.lean
2970a109540e19cfb84a7a032840c3c02b4d35fa
[ "Apache-2.0" ]
permissive
pacchiano/lean
9324b33f3ac3b5c5647285160f9f6ea8d0d767dc
fdadada3a970377a6df8afcd629a6f2eab6e84e8
refs/heads/master
1,611,357,380,399
1,489,870,101,000
1,489,870,101,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
878
lean
meta def get_file (fn : name) : vm format := do { d ← vm.get_decl fn, some n ← return (vm_decl.olean d) | failure, return (to_fmt n) } <|> return (to_fmt "<curr file>") meta def pos_info (fn : name) : vm format := do { d ← vm.get_decl fn, some pos ← return (vm_decl.pos d) | failure, file ← get_file fn, return (file ++ ":" ++ pos.1 ++ ":" ++ pos.2) } <|> return (to_fmt "<position not available>") meta def basic_monitor : vm_monitor nat := { init := 1000, step := λ sz, do csz ← vm.call_stack_size, if sz = csz then return sz else do fn ← vm.curr_fn, pos ← pos_info fn, vm.trace (to_fmt "[" ++ csz ++ "]: " ++ to_fmt fn ++ " @ " ++ pos), return csz } run_cmd vm_monitor.register `basic_monitor set_option debugger true def f : nat → nat | 0 := 0 | (a+1) := f a #eval trace "a" (f 4)
b3c693e005ca2ecfa1189fbdbbb9ee6feb3c17d7
26ac254ecb57ffcb886ff709cf018390161a9225
/src/algebra/group/prod.lean
3f51ede624513296899cb3cccd28430053246ee7
[ "Apache-2.0" ]
permissive
eric-wieser/mathlib
42842584f584359bbe1fc8b88b3ff937c8acd72d
d0df6b81cd0920ad569158c06a3fd5abb9e63301
refs/heads/master
1,669,546,404,255
1,595,254,668,000
1,595,254,668,000
281,173,504
0
0
Apache-2.0
1,595,263,582,000
1,595,263,581,000
null
UTF-8
Lean
false
false
8,949
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Patrick Massot, Yury Kudryashov -/ import algebra.group.hom import algebra.group_with_zero import data.prod /-! # Monoid, group etc structures on `M × N` In this file we define one-binop (`monoid`, `group` etc) structures on `M × N`. We also prove trivial `simp` lemmas, and define the following operations on `monoid_hom`s: * `fst M N : M × N →* M`, `snd M N : M × N →* N`: projections `prod.fst` and `prod.snd` as `monoid_hom`s; * `inl M N : M →* M × N`, `inr M N : N →* M × N`: inclusions of first/second monoid into the product; * `f.prod g : `M →* N × P`: sends `x` to `(f x, g x)`; * `f.coprod g : M × N →* P`: sends `(x, y)` to `f x * g y`; * `f.prod_map g : M × N → M' × N'`: `prod.map f g` as a `monoid_hom`, sends `(x, y)` to `(f x, g y)`. -/ variables {A : Type*} {B : Type*} {G : Type*} {H : Type*} {M : Type*} {N : Type*} {P : Type*} namespace prod @[to_additive] instance [has_mul M] [has_mul N] : has_mul (M × N) := ⟨λ p q, ⟨p.1 * q.1, p.2 * q.2⟩⟩ @[simp, to_additive] lemma fst_mul [has_mul M] [has_mul N] (p q : M × N) : (p * q).1 = p.1 * q.1 := rfl @[simp, to_additive] lemma snd_mul [has_mul M] [has_mul N] (p q : M × N) : (p * q).2 = p.2 * q.2 := rfl @[simp, to_additive] lemma mk_mul_mk [has_mul M] [has_mul N] (a₁ a₂ : M) (b₁ b₂ : N) : (a₁, b₁) * (a₂, b₂) = (a₁ * a₂, b₁ * b₂) := rfl @[to_additive] instance [has_one M] [has_one N] : has_one (M × N) := ⟨(1, 1)⟩ @[simp, to_additive] lemma fst_one [has_one M] [has_one N] : (1 : M × N).1 = 1 := rfl @[simp, to_additive] lemma snd_one [has_one M] [has_one N] : (1 : M × N).2 = 1 := rfl @[to_additive] lemma one_eq_mk [has_one M] [has_one N] : (1 : M × N) = (1, 1) := rfl @[simp, to_additive] lemma mk_eq_one [has_one M] [has_one N] {x : M} {y : N} : (x, y) = 1 ↔ x = 1 ∧ y = 1 := mk.inj_iff @[to_additive] lemma fst_mul_snd [monoid M] [monoid N] (p : M × N) : (p.fst, 1) * (1, p.snd) = p := ext (mul_one p.1) (one_mul p.2) @[to_additive] instance [has_inv M] [has_inv N] : has_inv (M × N) := ⟨λp, (p.1⁻¹, p.2⁻¹)⟩ @[simp, to_additive] lemma fst_inv [has_inv G] [has_inv H] (p : G × H) : (p⁻¹).1 = (p.1)⁻¹ := rfl @[simp, to_additive] lemma snd_inv [has_inv G] [has_inv H] (p : G × H) : (p⁻¹).2 = (p.2)⁻¹ := rfl @[simp, to_additive] lemma inv_mk [has_inv G] [has_inv H] (a : G) (b : H) : (a, b)⁻¹ = (a⁻¹, b⁻¹) := rfl @[to_additive add_semigroup] instance [semigroup M] [semigroup N] : semigroup (M × N) := { mul_assoc := assume a b c, mk.inj_iff.mpr ⟨mul_assoc _ _ _, mul_assoc _ _ _⟩, .. prod.has_mul } @[to_additive add_monoid] instance [monoid M] [monoid N] : monoid (M × N) := { one_mul := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨one_mul _, one_mul _⟩, mul_one := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨mul_one _, mul_one _⟩, .. prod.semigroup, .. prod.has_one } @[to_additive add_group] instance [group G] [group H] : group (G × H) := { mul_left_inv := assume a, mk.inj_iff.mpr ⟨mul_left_inv _, mul_left_inv _⟩, .. prod.monoid, .. prod.has_inv } @[simp] lemma fst_sub [add_group A] [add_group B] (a b : A × B) : (a - b).1 = a.1 - b.1 := rfl @[simp] lemma snd_sub [add_group A] [add_group B] (a b : A × B) : (a - b).2 = a.2 - b.2 := rfl @[simp] lemma mk_sub_mk [add_group A] [add_group B] (x₁ x₂ : A) (y₁ y₂ : B) : (x₁, y₁) - (x₂, y₂) = (x₁ - x₂, y₁ - y₂) := rfl @[to_additive add_comm_semigroup] instance [comm_semigroup G] [comm_semigroup H] : comm_semigroup (G × H) := { mul_comm := assume a b, mk.inj_iff.mpr ⟨mul_comm _ _, mul_comm _ _⟩, .. prod.semigroup } @[to_additive add_comm_monoid] instance [comm_monoid M] [comm_monoid N] : comm_monoid (M × N) := { .. prod.comm_semigroup, .. prod.monoid } @[to_additive add_comm_group] instance [comm_group G] [comm_group H] : comm_group (G × H) := { .. prod.comm_semigroup, .. prod.group } end prod namespace monoid_hom variables (M N) [monoid M] [monoid N] /-- Given monoids `M`, `N`, the natural projection homomorphism from `M × N` to `M`.-/ @[to_additive "Given additive monoids `A`, `B`, the natural projection homomorphism from `A × B` to `A`"] def fst : M × N →* M := ⟨prod.fst, rfl, λ _ _, rfl⟩ /-- Given monoids `M`, `N`, the natural projection homomorphism from `M × N` to `N`.-/ @[to_additive "Given additive monoids `A`, `B`, the natural projection homomorphism from `A × B` to `B`"] def snd : M × N →* N := ⟨prod.snd, rfl, λ _ _, rfl⟩ /-- Given monoids `M`, `N`, the natural inclusion homomorphism from `M` to `M × N`. -/ @[to_additive "Given additive monoids `A`, `B`, the natural inclusion homomorphism from `A` to `A × B`."] def inl : M →* M × N := ⟨λ x, (x, 1), rfl, λ _ _, prod.ext rfl (one_mul 1).symm⟩ /-- Given monoids `M`, `N`, the natural inclusion homomorphism from `N` to `M × N`. -/ @[to_additive "Given additive monoids `A`, `B`, the natural inclusion homomorphism from `B` to `A × B`."] def inr : N →* M × N := ⟨λ y, (1, y), rfl, λ _ _, prod.ext (one_mul 1).symm rfl⟩ variables {M N} @[simp, to_additive] lemma coe_fst : ⇑(fst M N) = prod.fst := rfl @[simp, to_additive] lemma coe_snd : ⇑(snd M N) = prod.snd := rfl @[simp, to_additive] lemma inl_apply (x) : inl M N x = (x, 1) := rfl @[simp, to_additive] lemma inr_apply (y) : inr M N y = (1, y) := rfl @[simp, to_additive] lemma fst_comp_inl : (fst M N).comp (inl M N) = id M := rfl @[simp, to_additive] lemma snd_comp_inl : (snd M N).comp (inl M N) = 1 := rfl @[simp, to_additive] lemma fst_comp_inr : (fst M N).comp (inr M N) = 1 := rfl @[simp, to_additive] lemma snd_comp_inr : (snd M N).comp (inr M N) = id N := rfl section prod variable [monoid P] /-- Combine two `monoid_hom`s `f : M →* N`, `g : M →* P` into `f.prod g : M →* N × P` given by `(f.prod g) x = (f x, g x)` -/ @[to_additive prod "Combine two `add_monoid_hom`s `f : M →+ N`, `g : M →+ P` into `f.prod g : M →+ N × P` given by `(f.prod g) x = (f x, g x)`"] protected def prod (f : M →* N) (g : M →* P) : M →* N × P := { to_fun := λ x, (f x, g x), map_one' := prod.ext f.map_one g.map_one, map_mul' := λ x y, prod.ext (f.map_mul x y) (g.map_mul x y) } @[simp, to_additive prod_apply] lemma prod_apply (f : M →* N) (g : M →* P) (x) : f.prod g x = (f x, g x) := rfl @[simp, to_additive fst_comp_prod] lemma fst_comp_prod (f : M →* N) (g : M →* P) : (fst N P).comp (f.prod g) = f := ext $ λ x, rfl @[simp, to_additive snd_comp_prod] lemma snd_comp_prod (f : M →* N) (g : M →* P) : (snd N P).comp (f.prod g) = g := ext $ λ x, rfl @[simp, to_additive prod_unique] lemma prod_unique (f : M →* N × P) : ((fst N P).comp f).prod ((snd N P).comp f) = f := ext $ λ x, by simp only [prod_apply, coe_fst, coe_snd, comp_apply, prod.mk.eta] end prod section prod_map variables {M' : Type*} {N' : Type*} [monoid M'] [monoid N'] [monoid P] (f : M →* M') (g : N →* N') /-- `prod.map` as a `monoid_hom`. -/ @[to_additive prod_map "`prod.map` as an `add_monoid_hom`"] def prod_map : M × N →* M' × N' := (f.comp (fst M N)).prod (g.comp (snd M N)) @[to_additive prod_map_def] lemma prod_map_def : prod_map f g = (f.comp (fst M N)).prod (g.comp (snd M N)) := rfl @[simp, to_additive coe_prod_map] lemma coe_prod_map : ⇑(prod_map f g) = prod.map f g := rfl @[to_additive prod_comp_prod_map] lemma prod_comp_prod_map (f : P →* M) (g : P →* N) (f' : M →* M') (g' : N →* N') : (f'.prod_map g').comp (f.prod g) = (f'.comp f).prod (g'.comp g) := rfl end prod_map section coprod variables [comm_monoid P] (f : M →* P) (g : N →* P) /-- Coproduct of two `monoid_hom`s with the same codomain: `f.coprod g (p : M × N) = f p.1 * g p.2`. -/ @[to_additive "Coproduct of two `add_monoid_hom`s with the same codomain: `f.coprod g (p : M × N) = f p.1 + g p.2`."] def coprod : M × N →* P := f.comp (fst M N) * g.comp (snd M N) @[simp, to_additive] lemma coprod_apply (p : M × N) : f.coprod g p = f p.1 * g p.2 := rfl @[simp, to_additive] lemma coprod_comp_inl : (f.coprod g).comp (inl M N) = f := ext $ λ x, by simp [coprod_apply] @[simp, to_additive] lemma coprod_comp_inr : (f.coprod g).comp (inr M N) = g := ext $ λ x, by simp [coprod_apply] @[simp, to_additive] lemma coprod_unique (f : M × N →* P) : (f.comp (inl M N)).coprod (f.comp (inr M N)) = f := ext $ λ x, by simp [coprod_apply, inl_apply, inr_apply, ← map_mul] @[simp, to_additive] lemma coprod_inl_inr {M N : Type*} [comm_monoid M] [comm_monoid N] : (inl M N).coprod (inr M N) = id (M × N) := coprod_unique (id $ M × N) lemma comp_coprod {Q : Type*} [comm_monoid Q] (h : P →* Q) (f : M →* P) (g : N →* P) : h.comp (f.coprod g) = (h.comp f).coprod (h.comp g) := ext $ λ x, by simp end coprod end monoid_hom
8cb3e4173626afb2aca6cc13ab343e9b46fb9ecb
6094e25ea0b7699e642463b48e51b2ead6ddc23f
/hott/init/logic.hlean
3f28fff11c4b1ed5aedb9e24c96b605e3b7f9fd0
[ "Apache-2.0" ]
permissive
gbaz/lean
a7835c4e3006fbbb079e8f8ffe18aacc45adebfb
a501c308be3acaa50a2c0610ce2e0d71becf8032
refs/heads/master
1,611,198,791,433
1,451,339,111,000
1,451,339,111,000
48,713,797
0
0
null
1,451,338,939,000
1,451,338,939,000
null
UTF-8
Lean
false
false
24,238
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Floris van Doorn -/ prelude import init.reserved_notation open unit definition id [reducible] [unfold_full] {A : Type} (a : A) : A := a /- not -/ definition not [reducible] (a : Type) := a → empty prefix ¬ := not definition absurd {a b : Type} (H₁ : a) (H₂ : ¬a) : b := empty.rec (λ e, b) (H₂ H₁) definition mt {a b : Type} (H₁ : a → b) (H₂ : ¬b) : ¬a := assume Ha : a, absurd (H₁ Ha) H₂ definition not_empty : ¬empty := assume H : empty, H definition non_contradictory (a : Type) : Type := ¬¬a definition non_contradictory_intro {a : Type} (Ha : a) : ¬¬a := assume Hna : ¬a, absurd Ha Hna definition not.intro {a : Type} (H : a → empty) : ¬a := H /- empty -/ definition empty.elim {c : Type} (H : empty) : c := empty.rec _ H /- eq -/ infix = := eq definition rfl {A : Type} {a : A} := eq.refl a /- These notions are here only to make porting from the standard library easier. They are defined again in init/path.hlean, and those definitions will be used throughout the HoTT-library. That's why the notation for eq below is only local. -/ namespace eq variables {A : Type} {a b c : A} definition subst [unfold 5] {P : A → Type} (H₁ : a = b) (H₂ : P a) : P b := eq.rec H₂ H₁ definition trans [unfold 5] (H₁ : a = b) (H₂ : b = c) : a = c := subst H₂ H₁ definition symm [unfold 4] (H : a = b) : b = a := subst H (refl a) definition mp {a b : Type} : (a = b) → a → b := eq.rec_on definition mpr {a b : Type} : (a = b) → b → a := assume H₁ H₂, eq.rec_on (eq.symm H₁) H₂ namespace ops end ops -- this is just to ensure that this namespace exists. There is nothing in it end eq local postfix ⁻¹ := eq.symm --input with \sy or \-1 or \inv local infixl ⬝ := eq.trans local infixr ▸ := eq.subst -- Auxiliary definition used by automation. It has the same type of eq.rec in the standard library definition eq.nrec.{l₁ l₂} {A : Type.{l₂}} {a : A} {C : A → Type.{l₁}} (H₁ : C a) (b : A) (H₂ : a = b) : C b := eq.rec H₁ H₂ definition congr {A B : Type} {f₁ f₂ : A → B} {a₁ a₂ : A} (H₁ : f₁ = f₂) (H₂ : a₁ = a₂) : f₁ a₁ = f₂ a₂ := eq.subst H₁ (eq.subst H₂ rfl) definition congr_fun {A : Type} {B : A → Type} {f g : Π x, B x} (H : f = g) (a : A) : f a = g a := eq.subst H (eq.refl (f a)) definition congr_arg {A B : Type} (a a' : A) (f : A → B) (Ha : a = a') : f a = f a' := eq.subst Ha rfl definition congr_arg2 {A B C : Type} (a a' : A) (b b' : B) (f : A → B → C) (Ha : a = a') (Hb : b = b') : f a b = f a' b' := eq.subst Ha (eq.subst Hb rfl) section variables {A : Type} {a b c: A} open eq.ops definition trans_rel_left (R : A → A → Type) (H₁ : R a b) (H₂ : b = c) : R a c := H₂ ▸ H₁ definition trans_rel_right (R : A → A → Type) (H₁ : a = b) (H₂ : R b c) : R a c := H₁⁻¹ ▸ H₂ end attribute eq.subst [subst] attribute eq.refl [refl] attribute eq.trans [trans] attribute eq.symm [symm] namespace lift definition down_up.{l₁ l₂} {A : Type.{l₁}} (a : A) : down (up.{l₁ l₂} a) = a := rfl definition up_down.{l₁ l₂} {A : Type.{l₁}} (a : lift.{l₁ l₂} A) : up (down a) = a := lift.rec_on a (λ d, rfl) end lift /- ne -/ definition ne [reducible] {A : Type} (a b : A) := ¬(a = b) notation a ≠ b := ne a b namespace ne open eq.ops variable {A : Type} variables {a b : A} definition intro (H : a = b → empty) : a ≠ b := H definition elim (H : a ≠ b) : a = b → empty := H definition irrefl (H : a ≠ a) : empty := H rfl definition symm (H : a ≠ b) : b ≠ a := assume (H₁ : b = a), H (H₁⁻¹) end ne definition empty_of_ne {A : Type} {a : A} : a ≠ a → empty := ne.irrefl section open eq.ops variables {p : Type₀} definition ne_empty_of_self : p → p ≠ empty := assume (Hp : p) (Heq : p = empty), Heq ▸ Hp definition ne_unit_of_not : ¬p → p ≠ unit := assume (Hnp : ¬p) (Heq : p = unit), (Heq ▸ Hnp) star definition unit_ne_empty : ¬unit = empty := ne_empty_of_self star end /- prod -/ abbreviation pair [constructor] := @prod.mk infixr × := prod variables {a b c d : Type} attribute prod.rec [elim] attribute prod.mk [intro!] protected definition prod.elim [unfold 4] (H₁ : a × b) (H₂ : a → b → c) : c := prod.rec H₂ H₁ definition prod.swap [unfold 3] : a × b → b × a := prod.rec (λHa Hb, prod.mk Hb Ha) /- sum -/ infixr ⊎ := sum infixr + := sum attribute sum.rec [elim] protected definition sum.elim [unfold 4] (H₁ : a ⊎ b) (H₂ : a → c) (H₃ : b → c) : c := sum.rec H₂ H₃ H₁ definition non_contradictory_em (a : Type) : ¬¬(a ⊎ ¬a) := assume not_em : ¬(a ⊎ ¬a), have neg_a : ¬a, from assume pos_a : a, absurd (sum.inl pos_a) not_em, absurd (sum.inr neg_a) not_em definition sum.swap : a ⊎ b → b ⊎ a := sum.rec sum.inr sum.inl /- iff -/ definition iff (a b : Type) := (a → b) × (b → a) notation a <-> b := iff a b notation a ↔ b := iff a b definition iff.intro : (a → b) → (b → a) → (a ↔ b) := prod.mk attribute iff.intro [intro!] definition iff.elim : ((a → b) → (b → a) → c) → (a ↔ b) → c := prod.rec attribute iff.elim [recursor 5] [elim] definition iff.elim_left : (a ↔ b) → a → b := prod.pr1 definition iff.mp := @iff.elim_left definition iff.elim_right : (a ↔ b) → b → a := prod.pr2 definition iff.mpr := @iff.elim_right definition iff.refl [refl] (a : Type) : a ↔ a := iff.intro (assume H, H) (assume H, H) definition iff.rfl {a : Type} : a ↔ a := iff.refl a definition iff.trans [trans] (H₁ : a ↔ b) (H₂ : b ↔ c) : a ↔ c := iff.intro (assume Ha, iff.mp H₂ (iff.mp H₁ Ha)) (assume Hc, iff.mpr H₁ (iff.mpr H₂ Hc)) definition iff.symm [symm] (H : a ↔ b) : b ↔ a := iff.intro (iff.elim_right H) (iff.elim_left H) definition iff.comm : (a ↔ b) ↔ (b ↔ a) := iff.intro iff.symm iff.symm definition iff.of_eq {a b : Type} (H : a = b) : a ↔ b := eq.rec_on H iff.rfl definition not_iff_not_of_iff (H₁ : a ↔ b) : ¬a ↔ ¬b := iff.intro (assume (Hna : ¬ a) (Hb : b), Hna (iff.elim_right H₁ Hb)) (assume (Hnb : ¬ b) (Ha : a), Hnb (iff.elim_left H₁ Ha)) definition of_iff_unit (H : a ↔ unit) : a := iff.mp (iff.symm H) star definition not_of_iff_empty : (a ↔ empty) → ¬a := iff.mp definition iff_unit_intro (H : a) : a ↔ unit := iff.intro (λ Hl, star) (λ Hr, H) definition iff_empty_intro (H : ¬a) : a ↔ empty := iff.intro H (empty.rec _) definition not_non_contradictory_iff_absurd (a : Type) : ¬¬¬a ↔ ¬a := iff.intro (λ (Hl : ¬¬¬a) (Ha : a), Hl (non_contradictory_intro Ha)) absurd definition imp_congr [congr] (H1 : a ↔ c) (H2 : b ↔ d) : (a → b) ↔ (c → d) := iff.intro (λHab Hc, iff.mp H2 (Hab (iff.mpr H1 Hc))) (λHcd Ha, iff.mpr H2 (Hcd (iff.mp H1 Ha))) definition not_not_intro (Ha : a) : ¬¬a := assume Hna : ¬a, Hna Ha definition not_of_not_not_not (H : ¬¬¬a) : ¬a := λ Ha, absurd (not_not_intro Ha) H definition not_unit [simp] : (¬ unit) ↔ empty := iff_empty_intro (not_not_intro star) definition not_empty_iff [simp] : (¬ empty) ↔ unit := iff_unit_intro not_empty definition not_congr [congr] (H : a ↔ b) : ¬a ↔ ¬b := iff.intro (λ H₁ H₂, H₁ (iff.mpr H H₂)) (λ H₁ H₂, H₁ (iff.mp H H₂)) definition ne_self_iff_empty [simp] {A : Type} (a : A) : (not (a = a)) ↔ empty := iff.intro empty_of_ne empty.elim definition eq_self_iff_unit [simp] {A : Type} (a : A) : (a = a) ↔ unit := iff_unit_intro rfl definition iff_not_self [simp] (a : Type) : (a ↔ ¬a) ↔ empty := iff_empty_intro (λ H, have H' : ¬a, from (λ Ha, (iff.mp H Ha) Ha), H' (iff.mpr H H')) definition not_iff_self [simp] (a : Type) : (¬a ↔ a) ↔ empty := iff_empty_intro (λ H, have H' : ¬a, from (λ Ha, (iff.mpr H Ha) Ha), H' (iff.mp H H')) definition unit_iff_empty [simp] : (unit ↔ empty) ↔ empty := iff_empty_intro (λ H, iff.mp H star) definition empty_iff_unit [simp] : (empty ↔ unit) ↔ empty := iff_empty_intro (λ H, iff.mpr H star) definition empty_of_unit_iff_empty : (unit ↔ empty) → empty := assume H, iff.mp H star /- prod simp rules -/ definition prod.imp (H₂ : a → c) (H₃ : b → d) : a × b → c × d := prod.rec (λHa Hb, prod.mk (H₂ Ha) (H₃ Hb)) definition prod_congr [congr] (H1 : a ↔ c) (H2 : b ↔ d) : (a × b) ↔ (c × d) := iff.intro (prod.imp (iff.mp H1) (iff.mp H2)) (prod.imp (iff.mpr H1) (iff.mpr H2)) definition prod.comm [simp] : a × b ↔ b × a := iff.intro prod.swap prod.swap definition prod.assoc [simp] : (a × b) × c ↔ a × (b × c) := iff.intro (prod.rec (λ H' Hc, prod.rec (λ Ha Hb, prod.mk Ha (prod.mk Hb Hc)) H')) (prod.rec (λ Ha, prod.rec (λ Hb Hc, prod.mk (prod.mk Ha Hb) Hc))) definition prod.pr1_comm [simp] : a × (b × c) ↔ b × (a × c) := iff.trans (iff.symm !prod.assoc) (iff.trans (prod_congr !prod.comm !iff.refl) !prod.assoc) definition prod_iff_left {a b : Type} (Hb : b) : (a × b) ↔ a := iff.intro prod.pr1 (λHa, prod.mk Ha Hb) definition prod_iff_right {a b : Type} (Ha : a) : (a × b) ↔ b := iff.intro prod.pr2 (prod.mk Ha) definition prod_unit [simp] (a : Type) : a × unit ↔ a := prod_iff_left star definition unit_prod [simp] (a : Type) : unit × a ↔ a := prod_iff_right star definition prod_empty [simp] (a : Type) : a × empty ↔ empty := iff_empty_intro prod.pr2 definition empty_prod [simp] (a : Type) : empty × a ↔ empty := iff_empty_intro prod.pr1 definition not_prod_self [simp] (a : Type) : (¬a × a) ↔ empty := iff_empty_intro (λ H, prod.elim H (λ H₁ H₂, absurd H₂ H₁)) definition prod_not_self [simp] (a : Type) : (a × ¬a) ↔ empty := iff_empty_intro (λ H, prod.elim H (λ H₁ H₂, absurd H₁ H₂)) definition prod_self [simp] (a : Type) : a × a ↔ a := iff.intro prod.pr1 (assume H, prod.mk H H) /- sum simp rules -/ definition sum.imp (H₂ : a → c) (H₃ : b → d) : a ⊎ b → c ⊎ d := sum.rec (λ H, sum.inl (H₂ H)) (λ H, sum.inr (H₃ H)) definition sum.imp_left (H : a → b) : a ⊎ c → b ⊎ c := sum.imp H id definition sum.imp_right (H : a → b) : c ⊎ a → c ⊎ b := sum.imp id H definition sum_congr [congr] (H1 : a ↔ c) (H2 : b ↔ d) : (a ⊎ b) ↔ (c ⊎ d) := iff.intro (sum.imp (iff.mp H1) (iff.mp H2)) (sum.imp (iff.mpr H1) (iff.mpr H2)) definition sum.comm [simp] : a ⊎ b ↔ b ⊎ a := iff.intro sum.swap sum.swap definition sum.assoc [simp] : (a ⊎ b) ⊎ c ↔ a ⊎ (b ⊎ c) := iff.intro (sum.rec (sum.imp_right sum.inl) (λ H, sum.inr (sum.inr H))) (sum.rec (λ H, sum.inl (sum.inl H)) (sum.imp_left sum.inr)) definition sum.left_comm [simp] : a ⊎ (b ⊎ c) ↔ b ⊎ (a ⊎ c) := iff.trans (iff.symm !sum.assoc) (iff.trans (sum_congr !sum.comm !iff.refl) !sum.assoc) definition sum_unit [simp] (a : Type) : a ⊎ unit ↔ unit := iff_unit_intro (sum.inr star) definition unit_sum [simp] (a : Type) : unit ⊎ a ↔ unit := iff_unit_intro (sum.inl star) definition sum_empty [simp] (a : Type) : a ⊎ empty ↔ a := iff.intro (sum.rec id empty.elim) sum.inl definition empty_sum [simp] (a : Type) : empty ⊎ a ↔ a := iff.trans sum.comm !sum_empty definition sum_self [simp] (a : Type) : a ⊎ a ↔ a := iff.intro (sum.rec id id) sum.inl /- sum resolution rulse -/ definition sum.resolve_left {a b : Type} (H : a ⊎ b) (na : ¬ a) : b := sum.elim H (λ Ha, absurd Ha na) id definition sum.neg_resolve_left {a b : Type} (H : ¬ a ⊎ b) (Ha : a) : b := sum.elim H (λ na, absurd Ha na) id definition sum.resolve_right {a b : Type} (H : a ⊎ b) (nb : ¬ b) : a := sum.elim H id (λ Hb, absurd Hb nb) definition sum.neg_resolve_right {a b : Type} (H : a ⊎ ¬ b) (Hb : b) : a := sum.elim H id (λ nb, absurd Hb nb) /- iff simp rules -/ definition iff_unit [simp] (a : Type) : (a ↔ unit) ↔ a := iff.intro (assume H, iff.mpr H star) iff_unit_intro definition unit_iff [simp] (a : Type) : (unit ↔ a) ↔ a := iff.trans iff.comm !iff_unit definition iff_empty [simp] (a : Type) : (a ↔ empty) ↔ ¬ a := iff.intro prod.pr1 iff_empty_intro definition empty_iff [simp] (a : Type) : (empty ↔ a) ↔ ¬ a := iff.trans iff.comm !iff_empty definition iff_self [simp] (a : Type) : (a ↔ a) ↔ unit := iff_unit_intro iff.rfl definition iff_congr [congr] (H1 : a ↔ c) (H2 : b ↔ d) : (a ↔ b) ↔ (c ↔ d) := prod_congr (imp_congr H1 H2) (imp_congr H2 H1) /- decidable -/ inductive decidable [class] (p : Type) : Type := | inl : p → decidable p | inr : ¬p → decidable p definition decidable_unit [instance] : decidable unit := decidable.inl star definition decidable_empty [instance] : decidable empty := decidable.inr not_empty -- We use "dependent" if-then-else to be able to communicate the if-then-else condition -- to the branches definition dite (c : Type) [H : decidable c] {A : Type} : (c → A) → (¬ c → A) → A := decidable.rec_on H /- if-then-else -/ definition ite (c : Type) [H : decidable c] {A : Type} (t e : A) : A := decidable.rec_on H (λ Hc, t) (λ Hnc, e) namespace decidable variables {p q : Type} definition by_cases {q : Type} [C : decidable p] : (p → q) → (¬p → q) → q := !dite theorem em (p : Type) [H : decidable p] : p ⊎ ¬p := by_cases sum.inl sum.inr theorem by_contradiction [Hp : decidable p] (H : ¬p → empty) : p := if H1 : p then H1 else empty.rec _ (H H1) end decidable section variables {p q : Type} open decidable definition decidable_of_decidable_of_iff (Hp : decidable p) (H : p ↔ q) : decidable q := if Hp : p then inl (iff.mp H Hp) else inr (iff.mp (not_iff_not_of_iff H) Hp) definition decidable_of_decidable_of_eq {p q : Type} (Hp : decidable p) (H : p = q) : decidable q := decidable_of_decidable_of_iff Hp (iff.of_eq H) protected definition sum.by_cases [Hp : decidable p] [Hq : decidable q] {A : Type} (h : p ⊎ q) (h₁ : p → A) (h₂ : q → A) : A := if hp : p then h₁ hp else if hq : q then h₂ hq else empty.rec _ (sum.elim h hp hq) end section variables {p q : Type} open decidable (rec_on inl inr) definition decidable_prod [instance] [Hp : decidable p] [Hq : decidable q] : decidable (p × q) := if hp : p then if hq : q then inl (prod.mk hp hq) else inr (assume H : p × q, hq (prod.pr2 H)) else inr (assume H : p × q, hp (prod.pr1 H)) definition decidable_sum [instance] [Hp : decidable p] [Hq : decidable q] : decidable (p ⊎ q) := if hp : p then inl (sum.inl hp) else if hq : q then inl (sum.inr hq) else inr (sum.rec hp hq) definition decidable_not [instance] [Hp : decidable p] : decidable (¬p) := if hp : p then inr (absurd hp) else inl hp definition decidable_implies [instance] [Hp : decidable p] [Hq : decidable q] : decidable (p → q) := if hp : p then if hq : q then inl (assume H, hq) else inr (assume H : p → q, absurd (H hp) hq) else inl (assume Hp, absurd Hp hp) definition decidable_iff [instance] [Hp : decidable p] [Hq : decidable q] : decidable (p ↔ q) := decidable_prod end definition decidable_pred [reducible] {A : Type} (R : A → Type) := Π (a : A), decidable (R a) definition decidable_rel [reducible] {A : Type} (R : A → A → Type) := Π (a b : A), decidable (R a b) definition decidable_eq [reducible] (A : Type) := decidable_rel (@eq A) definition decidable_ne [instance] {A : Type} [H : decidable_eq A] (a b : A) : decidable (a ≠ b) := decidable_implies namespace bool theorem ff_ne_tt : ff = tt → empty | [none] end bool open bool definition is_dec_eq {A : Type} (p : A → A → bool) : Type := Π ⦃x y : A⦄, p x y = tt → x = y definition is_dec_refl {A : Type} (p : A → A → bool) : Type := Πx, p x x = tt open decidable protected definition bool.has_decidable_eq [instance] : Πa b : bool, decidable (a = b) | ff ff := inl rfl | ff tt := inr ff_ne_tt | tt ff := inr (ne.symm ff_ne_tt) | tt tt := inl rfl definition decidable_eq_of_bool_pred {A : Type} {p : A → A → bool} (H₁ : is_dec_eq p) (H₂ : is_dec_refl p) : decidable_eq A := take x y : A, if Hp : p x y = tt then inl (H₁ Hp) else inr (assume Hxy : x = y, (eq.subst Hxy Hp) (H₂ y)) /- inhabited -/ inductive inhabited [class] (A : Type) : Type := mk : A → inhabited A protected definition inhabited.value {A : Type} : inhabited A → A := inhabited.rec (λa, a) protected definition inhabited.destruct {A : Type} {B : Type} (H1 : inhabited A) (H2 : A → B) : B := inhabited.rec H2 H1 definition default (A : Type) [H : inhabited A] : A := inhabited.value H definition arbitrary [irreducible] (A : Type) [H : inhabited A] : A := inhabited.value H definition Type.is_inhabited [instance] : inhabited Type := inhabited.mk (lift unit) definition inhabited_fun [instance] (A : Type) {B : Type} [H : inhabited B] : inhabited (A → B) := inhabited.rec_on H (λb, inhabited.mk (λa, b)) definition inhabited_Pi [instance] (A : Type) {B : A → Type} [H : Πx, inhabited (B x)] : inhabited (Πx, B x) := inhabited.mk (λa, !default) protected definition bool.is_inhabited [instance] : inhabited bool := inhabited.mk ff protected definition pos_num.is_inhabited [instance] : inhabited pos_num := inhabited.mk pos_num.one protected definition num.is_inhabited [instance] : inhabited num := inhabited.mk num.zero inductive nonempty [class] (A : Type) : Type := intro : A → nonempty A protected definition nonempty.elim {A : Type} {B : Type} (H1 : nonempty A) (H2 : A → B) : B := nonempty.rec H2 H1 theorem nonempty_of_inhabited [instance] {A : Type} [H : inhabited A] : nonempty A := nonempty.intro !default theorem nonempty_of_exists {A : Type} {P : A → Type} : (sigma P) → nonempty A := sigma.rec (λw H, nonempty.intro w) /- subsingleton -/ inductive subsingleton [class] (A : Type) : Type := intro : (Π a b : A, a = b) → subsingleton A protected definition subsingleton.elim {A : Type} [H : subsingleton A] : Π(a b : A), a = b := subsingleton.rec (λp, p) H protected theorem rec_subsingleton {p : Type} [H : decidable p] {H1 : p → Type} {H2 : ¬p → Type} [H3 : Π(h : p), subsingleton (H1 h)] [H4 : Π(h : ¬p), subsingleton (H2 h)] : subsingleton (decidable.rec_on H H1 H2) := decidable.rec_on H (λh, H3 h) (λh, H4 h) --this can be proven using dependent version of "by_cases" theorem if_pos {c : Type} [H : decidable c] (Hc : c) {A : Type} {t e : A} : (ite c t e) = t := decidable.rec (λ Hc : c, eq.refl (@ite c (decidable.inl Hc) A t e)) (λ Hnc : ¬c, absurd Hc Hnc) H theorem if_neg {c : Type} [H : decidable c] (Hnc : ¬c) {A : Type} {t e : A} : (ite c t e) = e := decidable.rec (λ Hc : c, absurd Hc Hnc) (λ Hnc : ¬c, eq.refl (@ite c (decidable.inr Hnc) A t e)) H theorem if_t_t [simp] (c : Type) [H : decidable c] {A : Type} (t : A) : (ite c t t) = t := decidable.rec (λ Hc : c, eq.refl (@ite c (decidable.inl Hc) A t t)) (λ Hnc : ¬c, eq.refl (@ite c (decidable.inr Hnc) A t t)) H theorem implies_of_if_pos {c t e : Type} [H : decidable c] (h : ite c t e) : c → t := assume Hc, eq.rec_on (if_pos Hc) h theorem implies_of_if_neg {c t e : Type} [H : decidable c] (h : ite c t e) : ¬c → e := assume Hnc, eq.rec_on (if_neg Hnc) h theorem if_ctx_congr {A : Type} {b c : Type} [dec_b : decidable b] [dec_c : decidable c] {x y u v : A} (h_c : b ↔ c) (h_t : c → x = u) (h_e : ¬c → y = v) : ite b x y = ite c u v := decidable.rec_on dec_b (λ hp : b, calc ite b x y = x : if_pos hp ... = u : h_t (iff.mp h_c hp) ... = ite c u v : if_pos (iff.mp h_c hp)) (λ hn : ¬b, calc ite b x y = y : if_neg hn ... = v : h_e (iff.mp (not_iff_not_of_iff h_c) hn) ... = ite c u v : if_neg (iff.mp (not_iff_not_of_iff h_c) hn)) theorem if_congr [congr] {A : Type} {b c : Type} [dec_b : decidable b] [dec_c : decidable c] {x y u v : A} (h_c : b ↔ c) (h_t : x = u) (h_e : y = v) : ite b x y = ite c u v := @if_ctx_congr A b c dec_b dec_c x y u v h_c (λ h, h_t) (λ h, h_e) theorem if_ctx_simp_congr {A : Type} {b c : Type} [dec_b : decidable b] {x y u v : A} (h_c : b ↔ c) (h_t : c → x = u) (h_e : ¬c → y = v) : ite b x y = (@ite c (decidable_of_decidable_of_iff dec_b h_c) A u v) := @if_ctx_congr A b c dec_b (decidable_of_decidable_of_iff dec_b h_c) x y u v h_c h_t h_e theorem if_simp_congr [congr] {A : Type} {b c : Type} [dec_b : decidable b] {x y u v : A} (h_c : b ↔ c) (h_t : x = u) (h_e : y = v) : ite b x y = (@ite c (decidable_of_decidable_of_iff dec_b h_c) A u v) := @if_ctx_simp_congr A b c dec_b x y u v h_c (λ h, h_t) (λ h, h_e) definition if_unit [simp] {A : Type} (t e : A) : (if unit then t else e) = t := if_pos star definition if_empty [simp] {A : Type} (t e : A) : (if empty then t else e) = e := if_neg not_empty theorem if_ctx_congr_prop {b c x y u v : Type} [dec_b : decidable b] [dec_c : decidable c] (h_c : b ↔ c) (h_t : c → (x ↔ u)) (h_e : ¬c → (y ↔ v)) : ite b x y ↔ ite c u v := decidable.rec_on dec_b (λ hp : b, calc ite b x y ↔ x : iff.of_eq (if_pos hp) ... ↔ u : h_t (iff.mp h_c hp) ... ↔ ite c u v : iff.of_eq (if_pos (iff.mp h_c hp))) (λ hn : ¬b, calc ite b x y ↔ y : iff.of_eq (if_neg hn) ... ↔ v : h_e (iff.mp (not_iff_not_of_iff h_c) hn) ... ↔ ite c u v : iff.of_eq (if_neg (iff.mp (not_iff_not_of_iff h_c) hn))) theorem if_congr_prop [congr] {b c x y u v : Type} [dec_b : decidable b] [dec_c : decidable c] (h_c : b ↔ c) (h_t : x ↔ u) (h_e : y ↔ v) : ite b x y ↔ ite c u v := if_ctx_congr_prop h_c (λ h, h_t) (λ h, h_e) theorem if_ctx_simp_congr_prop {b c x y u v : Type} [dec_b : decidable b] (h_c : b ↔ c) (h_t : c → (x ↔ u)) (h_e : ¬c → (y ↔ v)) : ite b x y ↔ (@ite c (decidable_of_decidable_of_iff dec_b h_c) Type u v) := @if_ctx_congr_prop b c x y u v dec_b (decidable_of_decidable_of_iff dec_b h_c) h_c h_t h_e theorem if_simp_congr_prop [congr] {b c x y u v : Type} [dec_b : decidable b] (h_c : b ↔ c) (h_t : x ↔ u) (h_e : y ↔ v) : ite b x y ↔ (@ite c (decidable_of_decidable_of_iff dec_b h_c) Type u v) := @if_ctx_simp_congr_prop b c x y u v dec_b h_c (λ h, h_t) (λ h, h_e) -- Remark: dite and ite are "definitionally equal" when we ignore the proofs. theorem dite_ite_eq (c : Type) [H : decidable c] {A : Type} (t : A) (e : A) : dite c (λh, t) (λh, e) = ite c t e := rfl definition is_unit (c : Type) [H : decidable c] : Type₀ := if c then unit else empty definition is_empty (c : Type) [H : decidable c] : Type₀ := if c then empty else unit definition of_is_unit {c : Type} [H₁ : decidable c] (H₂ : is_unit c) : c := decidable.rec_on H₁ (λ Hc, Hc) (λ Hnc, empty.rec _ (if_neg Hnc ▸ H₂)) notation `dec_star` := of_is_unit star theorem not_of_not_is_unit {c : Type} [H₁ : decidable c] (H₂ : ¬ is_unit c) : ¬ c := if Hc : c then absurd star (if_pos Hc ▸ H₂) else Hc theorem not_of_is_empty {c : Type} [H₁ : decidable c] (H₂ : is_empty c) : ¬ c := if Hc : c then empty.rec _ (if_pos Hc ▸ H₂) else Hc theorem of_not_is_empty {c : Type} [H₁ : decidable c] (H₂ : ¬ is_empty c) : c := if Hc : c then Hc else absurd star (if_neg Hc ▸ H₂) -- The following symbols should not be considered in the pattern inference procedure used by -- heuristic instantiation. attribute prod sum not iff ite dite eq ne [no_pattern] -- namespace used to collect congruence rules for "contextual simplification" namespace contextual attribute if_ctx_simp_congr [congr] attribute if_ctx_simp_congr_prop [congr] end contextual
b89423df4f2d1e0b4cb40008633a0026e63458f0
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/algebra/category/Group/biproducts.lean
f26c732b28e00773fc56a792a584f671b29639fd
[ "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,003
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.category.Group.basic import algebra.category.Group.preadditive import category_theory.limits.shapes.biproducts import algebra.group.pi /-! # The category of abelian groups has finite biproducts -/ open category_theory open category_theory.limits open_locale big_operators universe u namespace AddCommGroup instance has_binary_product (G H : AddCommGroup.{u}) : has_binary_product G H := { cone := { X := AddCommGroup.of (G × H), π := { app := λ j, walking_pair.cases_on j (add_monoid_hom.fst G H) (add_monoid_hom.snd G H) }}, is_limit := { lift := λ s, add_monoid_hom.prod (s.π.app walking_pair.left) (s.π.app walking_pair.right), fac' := begin rintros s (⟨⟩|⟨⟩); { ext x, dsimp, simp, }, end, uniq' := λ s m w, begin ext; [rw ← w walking_pair.left, rw ← w walking_pair.right]; refl, end, } } instance (G H : AddCommGroup.{u}) : has_binary_biproduct G H := has_binary_biproduct.of_has_binary_product _ _ -- We verify that the underlying type of the biproduct we've just defined is definitionally -- the cartesian product of the underlying types: example (G H : AddCommGroup.{u}) : ((G ⊞ H : AddCommGroup) : Type u) = (G × H) := rfl -- Furthermore, our biproduct will automatically function as a coproduct. example (G H : AddCommGroup.{u}) : has_colimit (pair G H) := by apply_instance variables {J : Type u} (F : (discrete J) ⥤ AddCommGroup.{u}) namespace has_limit /-- The map from an arbitrary cone over a indexed family of abelian groups to the cartesian product of those groups. -/ def lift (s : cone F) : s.X ⟶ AddCommGroup.of (Π j, F.obj j) := { to_fun := λ x j, s.π.app j x, map_zero' := by { ext, simp }, map_add' := λ x y, by { ext, simp }, } @[simp] lemma lift_apply (s : cone F) (x : s.X) (j : J) : (lift F s) x j = s.π.app j x := rfl instance has_limit_discrete : has_limit F := { cone := { X := AddCommGroup.of (Π j, F.obj j), π := discrete.nat_trans (λ j, add_monoid_hom.apply (λ j, F.obj j) j), }, is_limit := { lift := lift F, fac' := λ s j, by { ext, dsimp, simp, }, uniq' := λ s m w, begin ext x j, dsimp only [has_limit.lift], simp only [add_monoid_hom.coe_mk], exact congr_arg (λ f : s.X ⟶ F.obj j, (f : s.X → F.obj j) x) (w j), end, }, } end has_limit section open has_limit variables [decidable_eq J] [fintype J] instance (f : J → AddCommGroup.{u}) : has_biproduct f := has_biproduct.of_has_product _ -- We verify that the underlying type of the biproduct we've just defined is definitionally -- the dependent function type: example (f : J → AddCommGroup.{u}) : ((⨁ f : AddCommGroup) : Type u) = (Π j, f j) := rfl end instance : has_finite_biproducts AddCommGroup := ⟨λ J _ _, { has_biproduct := λ f, by exactI infer_instance }⟩ end AddCommGroup
ad07f0c9b170737b91865cd1166e4a21a04126db
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/linear_algebra/coevaluation.lean
31abc9c6cc8e8e24db612ab2890c7ab308445a97
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
4,267
lean
/- Copyright (c) 2021 Jakob von Raumer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jakob von Raumer -/ import linear_algebra.contraction import linear_algebra.finite_dimensional import linear_algebra.dual /-! # The coevaluation map on finite dimensional vector spaces > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Given a finite dimensional vector space `V` over a field `K` this describes the canonical linear map from `K` to `V ⊗ dual K V` which corresponds to the identity function on `V`. ## Tags coevaluation, dual module, tensor product ## Future work * Prove that this is independent of the choice of basis on `V`. -/ noncomputable theory section coevaluation open tensor_product finite_dimensional open_locale tensor_product big_operators universes u v variables (K : Type u) [field K] variables (V : Type v) [add_comm_group V] [module K V] [finite_dimensional K V] /-- The coevaluation map is a linear map from a field `K` to a finite dimensional vector space `V`. -/ def coevaluation : K →ₗ[K] V ⊗[K] (module.dual K V) := let bV := basis.of_vector_space K V in (basis.singleton unit K).constr K $ λ _, ∑ (i : basis.of_vector_space_index K V), bV i ⊗ₜ[K] bV.coord i lemma coevaluation_apply_one : (coevaluation K V) (1 : K) = let bV := basis.of_vector_space K V in ∑ (i : basis.of_vector_space_index K V), bV i ⊗ₜ[K] bV.coord i := begin simp only [coevaluation, id], rw [(basis.singleton unit K).constr_apply_fintype K], simp only [fintype.univ_punit, finset.sum_const, one_smul, basis.singleton_repr, basis.equiv_fun_apply,basis.coe_of_vector_space, one_nsmul, finset.card_singleton], end open tensor_product /-- This lemma corresponds to one of the coherence laws for duals in rigid categories, see `category_theory.monoidal.rigid`. -/ lemma contract_left_assoc_coevaluation : ((contract_left K V).rtensor _) ∘ₗ (tensor_product.assoc K _ _ _).symm.to_linear_map ∘ₗ ((coevaluation K V).ltensor (module.dual K V)) = (tensor_product.lid K _).symm.to_linear_map ∘ₗ (tensor_product.rid K _).to_linear_map := begin letI := classical.dec_eq (basis.of_vector_space_index K V), apply tensor_product.ext, apply (basis.of_vector_space K V).dual_basis.ext, intro j, apply linear_map.ext_ring, rw [linear_map.compr₂_apply, linear_map.compr₂_apply, tensor_product.mk_apply], simp only [linear_map.coe_comp, function.comp_app, linear_equiv.coe_to_linear_map], rw [rid_tmul, one_smul, lid_symm_apply], simp only [linear_equiv.coe_to_linear_map, linear_map.ltensor_tmul, coevaluation_apply_one], rw [tensor_product.tmul_sum, linear_equiv.map_sum], simp only [assoc_symm_tmul], rw [linear_map.map_sum], simp only [linear_map.rtensor_tmul, contract_left_apply], simp only [basis.coe_dual_basis, basis.coord_apply, basis.repr_self_apply, tensor_product.ite_tmul], rw [finset.sum_ite_eq'], simp only [finset.mem_univ, if_true] end /-- This lemma corresponds to one of the coherence laws for duals in rigid categories, see `category_theory.monoidal.rigid`. -/ lemma contract_left_assoc_coevaluation' : ((contract_left K V).ltensor _) ∘ₗ (tensor_product.assoc K _ _ _).to_linear_map ∘ₗ ((coevaluation K V).rtensor V) = (tensor_product.rid K _).symm.to_linear_map ∘ₗ (tensor_product.lid K _).to_linear_map := begin letI := classical.dec_eq (basis.of_vector_space_index K V), apply tensor_product.ext, apply linear_map.ext_ring, apply (basis.of_vector_space K V).ext, intro j, rw [linear_map.compr₂_apply, linear_map.compr₂_apply, tensor_product.mk_apply], simp only [linear_map.coe_comp, function.comp_app, linear_equiv.coe_to_linear_map], rw [lid_tmul, one_smul, rid_symm_apply], simp only [linear_equiv.coe_to_linear_map, linear_map.rtensor_tmul, coevaluation_apply_one], rw [tensor_product.sum_tmul, linear_equiv.map_sum], simp only [assoc_tmul], rw [linear_map.map_sum], simp only [linear_map.ltensor_tmul, contract_left_apply], simp only [basis.coord_apply, basis.repr_self_apply, tensor_product.tmul_ite], rw [finset.sum_ite_eq], simp only [finset.mem_univ, if_true] end end coevaluation
c6207bff0f50af118dbcb66ecdcf411094e43f6f
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Init/Control/StateCps.lean
6a1c39c8356ab7bb6a4743ece3b90ab09c39d82c
[ "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
3,670
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Control.Lawful /- The State monad transformer using CPS style. -/ def StateCpsT (σ : Type u) (m : Type u → Type v) (α : Type u) := (δ : Type u) → σ → (α → σ → m δ) → m δ namespace StateCpsT @[inline] def runK {α σ : Type u} {m : Type u → Type v} (x : StateCpsT σ m α) (s : σ) (k : α → σ → m β) : m β := x _ s k @[inline] def run {α σ : Type u} {m : Type u → Type v} [Monad m] (x : StateCpsT σ m α) (s : σ) : m (α × σ) := runK x s (fun a s => pure (a, s)) @[inline] def run' {α σ : Type u} {m : Type u → Type v} [Monad m] (x : StateCpsT σ m α) (s : σ) : m α := runK x s (fun a s => pure a) instance : Monad (StateCpsT σ m) where map f x := fun δ s k => x δ s fun a s => k (f a) s pure a := fun δ s k => k a s bind x f := fun δ s k => x δ s fun a s => f a δ s k instance : LawfulMonad (StateCpsT σ m) := by refine' { .. } <;> intros <;> rfl instance : MonadStateOf σ (StateCpsT σ m) where get := fun δ s k => k s s set s := fun δ _ k => k ⟨⟩ s modifyGet f := fun _ s k => let (a, s) := f s; k a s @[inline] protected def lift [Monad m] (x : m α) : StateCpsT σ m α := fun _ s k => x >>= (k . s) instance [Monad m] : MonadLift m (StateCpsT σ m) where monadLift := StateCpsT.lift @[simp] theorem runK_pure {m : Type u → Type v} (a : α) (s : σ) (k : α → σ → m β) : (pure a : StateCpsT σ m α).runK s k = k a s := rfl @[simp] theorem runK_get {m : Type u → Type v} (s : σ) (k : σ → σ → m β) : (get : StateCpsT σ m σ).runK s k = k s s := rfl @[simp] theorem runK_set {m : Type u → Type v} (s s' : σ) (k : PUnit → σ → m β) : (set s' : StateCpsT σ m PUnit).runK s k = k ⟨⟩ s' := rfl @[simp] theorem runK_modify {m : Type u → Type v} (f : σ → σ) (s : σ) (k : PUnit → σ → m β) : (modify f : StateCpsT σ m PUnit).runK s k = k ⟨⟩ (f s) := rfl @[simp] theorem runK_lift {α σ : Type u} [Monad m] (x : m α) (s : σ) (k : α → σ → m β) : (StateCpsT.lift x : StateCpsT σ m α).runK s k = x >>= (k . s) := rfl @[simp] theorem runK_monadLift {σ : Type u} [Monad m] [MonadLiftT n m] (x : n α) (s : σ) (k : α → σ → m β) : (monadLift x : StateCpsT σ m α).runK s k = (monadLift x : m α) >>= (k . s) := rfl @[simp] theorem runK_bind_pure {α σ : Type u} [Monad m] (a : α) (f : α → StateCpsT σ m β) (s : σ) (k : β → σ → m γ) : (pure a >>= f).runK s k = (f a).runK s k := rfl @[simp] theorem runK_bind_lift {α σ : Type u} [Monad m] (x : m α) (f : α → StateCpsT σ m β) (s : σ) (k : β → σ → m γ) : (StateCpsT.lift x >>= f).runK s k = x >>= fun a => (f a).runK s k := rfl @[simp] theorem runK_bind_get {σ : Type u} [Monad m] (f : σ → StateCpsT σ m β) (s : σ) (k : β → σ → m γ) : (get >>= f).runK s k = (f s).runK s k := rfl @[simp] theorem runK_bind_set {σ : Type u} [Monad m] (f : PUnit → StateCpsT σ m β) (s s' : σ) (k : β → σ → m γ) : (set s' >>= f).runK s k = (f ⟨⟩).runK s' k := rfl @[simp] theorem runK_bind_modify {σ : Type u} [Monad m] (f : σ → σ) (g : PUnit → StateCpsT σ m β) (s : σ) (k : β → σ → m γ) : (modify f >>= g).runK s k = (g ⟨⟩).runK (f s) k := rfl @[simp] theorem run_eq [Monad m] (x : StateCpsT σ m α) (s : σ) : x.run s = x.runK s (fun a s => pure (a, s)) := rfl @[simp] theorem run'_eq [Monad m] (x : StateCpsT σ m α) (s : σ) : x.run' s = x.runK s (fun a s => pure a) := rfl end StateCpsT
7e46bbc9e32437fa97bed1189e355bd38da54e5d
d436468d80b739ba7e06843c4d0d2070e43448e5
/src/group_theory/coset.lean
db393663f2eb73b6d5ae24113c53ca803f063eb3
[ "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
9,159
lean
/- Copyright (c) 2018 Mitchell Rowett. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mitchell Rowett, Scott Morrison -/ import group_theory.subgroup data.equiv.basic data.quot open set function variable {α : Type*} @[to_additive left_add_coset] def left_coset [has_mul α] (a : α) (s : set α) : set α := (λ x, a * x) '' s @[to_additive right_add_coset] def right_coset [has_mul α] (s : set α) (a : α) : set α := (λ x, x * a) '' s localized "infix ` *l `:70 := left_coset" in coset localized "infix ` +l `:70 := left_add_coset" in coset localized "infix ` *r `:70 := right_coset" in coset localized "infix ` +r `:70 := right_add_coset" in coset section coset_mul variable [has_mul α] @[to_additive mem_left_add_coset] lemma mem_left_coset {s : set α} {x : α} (a : α) (hxS : x ∈ s) : a * x ∈ a *l s := mem_image_of_mem (λ b : α, a * b) hxS @[to_additive mem_right_add_coset] lemma mem_right_coset {s : set α} {x : α} (a : α) (hxS : x ∈ s) : x * a ∈ s *r a := mem_image_of_mem (λ b : α, b * a) hxS @[to_additive left_add_coset_equiv] def left_coset_equiv (s : set α) (a b : α) := a *l s = b *l s @[to_additive left_add_coset_equiv_rel] lemma left_coset_equiv_rel (s : set α) : equivalence (left_coset_equiv s) := mk_equivalence (left_coset_equiv s) (λ a, rfl) (λ a b, eq.symm) (λ a b c, eq.trans) end coset_mul section coset_semigroup variable [semigroup α] @[simp] lemma left_coset_assoc (s : set α) (a b : α) : a *l (b *l s) = (a * b) *l s := by simp [left_coset, right_coset, (image_comp _ _ _).symm, function.comp, mul_assoc] attribute [to_additive left_add_coset_assoc] left_coset_assoc @[simp] lemma right_coset_assoc (s : set α) (a b : α) : s *r a *r b = s *r (a * b) := by simp [left_coset, right_coset, (image_comp _ _ _).symm, function.comp, mul_assoc] attribute [to_additive right_add_coset_assoc] right_coset_assoc @[to_additive left_add_coset_right_add_coset] lemma left_coset_right_coset (s : set α) (a b : α) : a *l s *r b = a *l (s *r b) := by simp [left_coset, right_coset, (image_comp _ _ _).symm, function.comp, mul_assoc] end coset_semigroup section coset_monoid variables [monoid α] (s : set α) @[simp] lemma one_left_coset : 1 *l s = s := set.ext $ by simp [left_coset] attribute [to_additive zero_left_add_coset] one_left_coset @[simp] lemma right_coset_one : s *r 1 = s := set.ext $ by simp [right_coset] attribute [to_additive right_add_coset_zero] right_coset_one end coset_monoid section coset_submonoid open submonoid variables [monoid α] (s : submonoid α) @[to_additive mem_own_left_add_coset] lemma mem_own_left_coset (a : α) : a ∈ a *l s := suffices a * 1 ∈ a *l s, by simpa, mem_left_coset a (one_mem s) @[to_additive mem_own_right_add_coset] lemma mem_own_right_coset (a : α) : a ∈ (s : set α) *r a := suffices 1 * a ∈ (s : set α) *r a, by simpa, mem_right_coset a (one_mem s) @[to_additive mem_left_add_coset_left_add_coset] lemma mem_left_coset_left_coset {a : α} (ha : a *l s = s) : a ∈ s := by rw [←submonoid.mem_coe, ←ha]; exact mem_own_left_coset s a @[to_additive mem_right_add_coset_right_add_coset] lemma mem_right_coset_right_coset {a : α} (ha : (s : set α) *r a = s) : a ∈ s := by rw [←submonoid.mem_coe, ←ha]; exact mem_own_right_coset s a end coset_submonoid section coset_group variables [group α] {s : set α} {x : α} @[to_additive mem_left_add_coset_iff] lemma mem_left_coset_iff (a : α) : x ∈ a *l s ↔ a⁻¹ * x ∈ s := iff.intro (assume ⟨b, hb, eq⟩, by simp [eq.symm, hb]) (assume h, ⟨a⁻¹ * x, h, by simp⟩) @[to_additive mem_right_add_coset_iff] lemma mem_right_coset_iff (a : α) : x ∈ s *r a ↔ x * a⁻¹ ∈ s := iff.intro (assume ⟨b, hb, eq⟩, by simp [eq.symm, hb]) (assume h, ⟨x * a⁻¹, h, by simp⟩) end coset_group section coset_subgroup open submonoid open is_subgroup variables [group α] (s : set α) [is_subgroup s] @[to_additive left_add_coset_mem_left_add_coset] lemma left_coset_mem_left_coset {a : α} (ha : a ∈ s) : a *l s = s := set.ext $ by simp [mem_left_coset_iff, mul_mem_cancel_right s (inv_mem ha)] @[to_additive right_add_coset_mem_right_add_coset] lemma right_coset_mem_right_coset {a : α} (ha : a ∈ s) : s *r a = s := set.ext $ assume b, by simp [mem_right_coset_iff, mul_mem_cancel_left s (inv_mem ha)] @[to_additive normal_of_eq_add_cosets] theorem normal_of_eq_cosets [normal_subgroup s] (g : α) : g *l s = s *r g := set.ext $ assume a, by simp [mem_left_coset_iff, mem_right_coset_iff]; rw [mem_norm_comm_iff] @[to_additive eq_add_cosets_of_normal] theorem eq_cosets_of_normal (h : ∀ g, g *l s = s *r g) : normal_subgroup s := ⟨assume a ha g, show g * a * g⁻¹ ∈ s, by rw [← mem_right_coset_iff, ← h]; exact mem_left_coset g ha⟩ @[to_additive normal_iff_eq_add_cosets] theorem normal_iff_eq_cosets : normal_subgroup s ↔ ∀ g, g *l s = s *r g := ⟨@normal_of_eq_cosets _ _ s _, eq_cosets_of_normal s⟩ end coset_subgroup run_cmd to_additive.map_namespace `quotient_group `quotient_add_group namespace quotient_group @[to_additive] def left_rel [group α] (s : set α) [is_subgroup s] : setoid α := ⟨λ x y, x⁻¹ * y ∈ s, assume x, by simp [is_submonoid.one_mem], assume x y hxy, have (x⁻¹ * y)⁻¹ ∈ s, from is_subgroup.inv_mem hxy, by simpa using this, assume x y z hxy hyz, have x⁻¹ * y * (y⁻¹ * z) ∈ s, from is_submonoid.mul_mem hxy hyz, by simpa [mul_assoc] using this⟩ /-- `quotient s` is the quotient type representing the left cosets of `s`. If `s` is a normal subgroup, `quotient s` is a group -/ @[to_additive] def quotient [group α] (s : set α) [is_subgroup s] : Type* := quotient (left_rel s) variables [group α] {s : set α} [is_subgroup s] @[to_additive] def mk (a : α) : quotient s := quotient.mk' a @[elab_as_eliminator, to_additive] lemma induction_on {C : quotient s → Prop} (x : quotient s) (H : ∀ z, C (quotient_group.mk z)) : C x := quotient.induction_on' x H @[to_additive] instance : has_coe_t α (quotient s) := ⟨mk⟩ -- note [use has_coe_t] @[elab_as_eliminator, to_additive] lemma induction_on' {C : quotient s → Prop} (x : quotient s) (H : ∀ z : α, C z) : C x := quotient.induction_on' x H @[to_additive] instance [group α] (s : set α) [is_subgroup s] : inhabited (quotient s) := ⟨((1 : α) : quotient s)⟩ @[to_additive quotient_add_group.eq] protected lemma eq {a b : α} : (a : quotient s) = b ↔ a⁻¹ * b ∈ s := quotient.eq' @[to_additive] lemma eq_class_eq_left_coset [group α] (s : set α) [is_subgroup s] (g : α) : {x : α | (x : quotient s) = g} = left_coset g s := set.ext $ λ z, by rw [mem_left_coset_iff, set.mem_set_of_eq, eq_comm, quotient_group.eq] end quotient_group namespace is_subgroup open quotient_group variables [group α] {s : set α} @[to_additive] def left_coset_equiv_subgroup (g : α) : left_coset g s ≃ s := ⟨λ x, ⟨g⁻¹ * x.1, (mem_left_coset_iff _).1 x.2⟩, λ x, ⟨g * x.1, x.1, x.2, rfl⟩, λ ⟨x, hx⟩, subtype.eq $ by simp, λ ⟨g, hg⟩, subtype.eq $ by simp⟩ @[to_additive] noncomputable def group_equiv_quotient_times_subgroup (hs : is_subgroup s) : α ≃ quotient s × s := calc α ≃ Σ L : quotient s, {x : α // (x : quotient s)= L} : (equiv.sigma_preimage_equiv quotient_group.mk).symm ... ≃ Σ L : quotient s, left_coset (quotient.out' L) s : equiv.sigma_congr_right (λ L, begin rw ← eq_class_eq_left_coset, show {x // quotient.mk' x = L} ≃ {x : α // quotient.mk' x = quotient.mk' _}, simp [-quotient.eq'] end) ... ≃ Σ L : quotient s, s : equiv.sigma_congr_right (λ L, left_coset_equiv_subgroup _) ... ≃ quotient s × s : equiv.sigma_equiv_prod _ _ end is_subgroup namespace quotient_group variables [group α] noncomputable def preimage_mk_equiv_subgroup_times_set (s : set α) [is_subgroup s] (t : set (quotient s)) : quotient_group.mk ⁻¹' t ≃ s × t := have h : ∀ {x : quotient s} {a : α}, x ∈ t → a ∈ s → (quotient.mk' (quotient.out' x * a) : quotient s) = quotient.mk' (quotient.out' x) := λ x a hx ha, quotient.sound' (show (quotient.out' x * a)⁻¹ * quotient.out' x ∈ s, from (is_subgroup.inv_mem_iff _).1 $ by rwa [mul_inv_rev, inv_inv, ← mul_assoc, inv_mul_self, one_mul]), { to_fun := λ ⟨a, ha⟩, ⟨⟨(quotient.out' (quotient.mk' a))⁻¹ * a, @quotient.exact' _ (left_rel s) _ _ $ (quotient.out_eq' _)⟩, ⟨quotient.mk' a, ha⟩⟩, inv_fun := λ ⟨⟨a, ha⟩, ⟨x, hx⟩⟩, ⟨quotient.out' x * a, show quotient.mk' _ ∈ t, by simp [h hx ha, hx]⟩, left_inv := λ ⟨a, ha⟩, subtype.eq $ show _ * _ = a, by simp, right_inv := λ ⟨⟨a, ha⟩, ⟨x, hx⟩⟩, show (_, _) = _, by simp [h hx ha] } end quotient_group /- Note [use has_coe_t]: We use the class `has_coe_t` instead of `has_coe` if the first-argument is a variable. Using `has_coe` would cause looping of type-class inference. See https://leanprover.zulipchat.com/#narrow/stream/113488-general/topic/remove.20all.20instances.20with.20variable.20domain -/
7183d680461eefa4124347afe1ecdeaf0d12328d
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/limits/constructions/limits_of_products_and_equalizers.lean
246e4e9e5e4eadfe6a578155a71c98e69610a705
[ "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,105
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta, Scott Morrison -/ import category_theory.limits.shapes.equalizers import category_theory.limits.shapes.finite_products import category_theory.limits.preserves.shapes.products import category_theory.limits.preserves.shapes.equalizers /-! # Constructing limits from products and equalizers. If a category has all products, and all equalizers, then it has all limits. Similarly, if it has all finite products, and all equalizers, then it has all finite limits. If a functor preserves all products and equalizers, then it preserves all limits. Similarly, if it preserves all finite products and equalizers, then it preserves all finite limits. # TODO Provide the dual results. Show the analogous results for functors which reflect or create (co)limits. -/ open category_theory open opposite namespace category_theory.limits universes v u u₂ variables {C : Type u} [category.{v} C] variables {J : Type v} [small_category J] -- We hide the "implementation details" inside a namespace namespace has_limit_of_has_products_of_has_equalizers variables {F : J ⥤ C} {c₁ : fan F.obj} {c₂ : fan (λ f : (Σ p : J × J, p.1 ⟶ p.2), F.obj f.1.2)} (s t : c₁.X ⟶ c₂.X) (hs : ∀ (f : Σ p : J × J, p.1 ⟶ p.2), s ≫ c₂.π.app f = c₁.π.app f.1.1 ≫ F.map f.2) (ht : ∀ (f : Σ p : J × J, p.1 ⟶ p.2), t ≫ c₂.π.app f = c₁.π.app f.1.2) (i : fork s t) include hs ht /-- (Implementation) Given the appropriate product and equalizer cones, build the cone for `F` which is limiting if the given cones are also. -/ @[simps] def build_limit : cone F := { X := i.X, π := { app := λ j, i.ι ≫ c₁.π.app _, naturality' := λ j₁ j₂ f, begin dsimp, rw [category.id_comp, category.assoc, ← hs ⟨⟨_, _⟩, f⟩, i.condition_assoc, ht], end} } variable {i} /-- (Implementation) Show the cone constructed in `build_limit` is limiting, provided the cones used in its construction are. -/ def build_is_limit (t₁ : is_limit c₁) (t₂ : is_limit c₂) (hi : is_limit i) : is_limit (build_limit s t hs ht i) := { lift := λ q, begin refine hi.lift (fork.of_ι _ _), { refine t₁.lift (fan.mk _ (λ j, _)), apply q.π.app j }, { apply t₂.hom_ext, simp [hs, ht] }, end, uniq' := λ q m w, hi.hom_ext (i.equalizer_ext (t₁.hom_ext (by simpa using w))) } end has_limit_of_has_products_of_has_equalizers open has_limit_of_has_products_of_has_equalizers /-- Given the existence of the appropriate (possibly finite) products and equalizers, we know a limit of `F` exists. (This assumes the existence of all equalizers, which is technically stronger than needed.) -/ lemma has_limit_of_equalizer_and_product (F : J ⥤ C) [has_limit (discrete.functor F.obj)] [has_limit (discrete.functor (λ f : (Σ p : J × J, p.1 ⟶ p.2), F.obj f.1.2))] [has_equalizers C] : has_limit F := has_limit.mk { cone := _, is_limit := build_is_limit (pi.lift (λ f, limit.π _ _ ≫ F.map f.2)) (pi.lift (λ f, limit.π _ f.1.2)) (by simp) (by simp) (limit.is_limit _) (limit.is_limit _) (limit.is_limit _) } /-- Any category with products and equalizers has all limits. See https://stacks.math.columbia.edu/tag/002N. -/ lemma limits_from_equalizers_and_products [has_products C] [has_equalizers C] : has_limits C := { has_limits_of_shape := λ J 𝒥, { has_limit := λ F, by exactI has_limit_of_equalizer_and_product F } } /-- Any category with finite products and equalizers has all finite limits. See https://stacks.math.columbia.edu/tag/002O. -/ lemma finite_limits_from_equalizers_and_finite_products [has_finite_products C] [has_equalizers C] : has_finite_limits C := ⟨λ J _ _, { has_limit := λ F, by exactI has_limit_of_equalizer_and_product F }⟩ variables {D : Type u₂} [category.{v} D] noncomputable theory section variables [has_limits_of_shape (discrete J) C] [has_limits_of_shape (discrete (Σ p : J × J, p.1 ⟶ p.2)) C] [has_equalizers C] variables (G : C ⥤ D) [preserves_limits_of_shape walking_parallel_pair G] [preserves_limits_of_shape (discrete J) G] [preserves_limits_of_shape (discrete (Σ p : J × J, p.1 ⟶ p.2)) G] /-- If a functor preserves equalizers and the appropriate products, it preserves limits. -/ def preserves_limit_of_preserves_equalizers_and_product : preserves_limits_of_shape J G := { preserves_limit := λ K, begin let P := ∏ K.obj, let Q := ∏ (λ (f : (Σ (p : J × J), p.fst ⟶ p.snd)), K.obj f.1.2), let s : P ⟶ Q := pi.lift (λ f, limit.π _ _ ≫ K.map f.2), let t : P ⟶ Q := pi.lift (λ f, limit.π _ f.1.2), let I := equalizer s t, let i : I ⟶ P := equalizer.ι s t, apply preserves_limit_of_preserves_limit_cone (build_is_limit s t (by simp) (by simp) (limit.is_limit _) (limit.is_limit _) (limit.is_limit _)), refine is_limit.of_iso_limit (build_is_limit _ _ _ _ _ _ _) _, { exact fan.mk _ (λ j, G.map (pi.π _ j)) }, { exact fan.mk (G.obj Q) (λ f, G.map (pi.π _ f)) }, { apply G.map s }, { apply G.map t }, { intro f, dsimp, simp only [←G.map_comp, limit.lift_π, fan.mk_π_app] }, { intro f, dsimp, simp only [←G.map_comp, limit.lift_π, fan.mk_π_app] }, { apply fork.of_ι (G.map i) _, simp only [← G.map_comp, equalizer.condition] }, { apply is_limit_of_has_product_of_preserves_limit }, { apply is_limit_of_has_product_of_preserves_limit }, { apply is_limit_fork_map_of_is_limit, apply equalizer_is_equalizer }, refine cones.ext (iso.refl _) _, intro j, dsimp, simp, -- See note [dsimp, simp]. end } end /-- If G preserves equalizers and finite products, it preserves finite limits. -/ def preserves_finite_limits_of_preserves_equalizers_and_finite_products [has_equalizers C] [has_finite_products C] (G : C ⥤ D) [preserves_limits_of_shape walking_parallel_pair G] [∀ J [fintype J], preserves_limits_of_shape (discrete J) G] (J : Type v) [small_category J] [fin_category J] : preserves_limits_of_shape J G := preserves_limit_of_preserves_equalizers_and_product G /-- If G preserves equalizers and products, it preserves all limits. -/ def preserves_limits_of_preserves_equalizers_and_products [has_equalizers C] [has_products C] (G : C ⥤ D) [preserves_limits_of_shape walking_parallel_pair G] [∀ J, preserves_limits_of_shape (discrete J) G] : preserves_limits G := { preserves_limits_of_shape := λ J 𝒥, by exactI preserves_limit_of_preserves_equalizers_and_product G } /-! We now dualize the above constructions, resorting to copy-paste. -/ -- We hide the "implementation details" inside a namespace namespace has_colimit_of_has_coproducts_of_has_coequalizers variables {F : J ⥤ C} {c₁ : cofan (λ f : (Σ p : J × J, p.1 ⟶ p.2), F.obj f.1.1)} {c₂ : cofan F.obj} (s t : c₁.X ⟶ c₂.X) (hs : ∀ (f : Σ p : J × J, p.1 ⟶ p.2), c₁.ι.app f ≫ s = F.map f.2 ≫ c₂.ι.app f.1.2) (ht : ∀ (f : Σ p : J × J, p.1 ⟶ p.2), c₁.ι.app f ≫ t = c₂.ι.app f.1.1) (i : cofork s t) include hs ht /-- (Implementation) Given the appropriate coproduct and coequalizer cocones, build the cocone for `F` which is colimiting if the given cocones are also. -/ @[simps] def build_colimit : cocone F := { X := i.X, ι := { app := λ j, c₂.ι.app _ ≫ i.π, naturality' := λ j₁ j₂ f, begin dsimp, rw [category.comp_id, ←reassoc_of (hs ⟨⟨_, _⟩, f⟩), i.condition, ←category.assoc, ht], end} } variable {i} /-- (Implementation) Show the cocone constructed in `build_colimit` is colimiting, provided the cocones used in its construction are. -/ def build_is_colimit (t₁ : is_colimit c₁) (t₂ : is_colimit c₂) (hi : is_colimit i) : is_colimit (build_colimit s t hs ht i) := { desc := λ q, begin refine hi.desc (cofork.of_π _ _), { refine t₂.desc (cofan.mk _ (λ j, _)), apply q.ι.app j }, { apply t₁.hom_ext, simp [reassoc_of hs, reassoc_of ht] }, end, uniq' := λ q m w, hi.hom_ext (i.coequalizer_ext (t₂.hom_ext (by simpa using w))) } end has_colimit_of_has_coproducts_of_has_coequalizers open has_colimit_of_has_coproducts_of_has_coequalizers /-- Given the existence of the appropriate (possibly finite) coproducts and coequalizers, we know a colimit of `F` exists. (This assumes the existence of all coequalizers, which is technically stronger than needed.) -/ lemma has_colimit_of_coequalizer_and_coproduct (F : J ⥤ C) [has_colimit (discrete.functor F.obj)] [has_colimit (discrete.functor (λ f : (Σ p : J × J, p.1 ⟶ p.2), F.obj f.1.1))] [has_coequalizers C] : has_colimit F := has_colimit.mk { cocone := _, is_colimit := build_is_colimit (sigma.desc (λ f, F.map f.2 ≫ colimit.ι (discrete.functor F.obj) f.1.2)) (sigma.desc (λ f, colimit.ι (discrete.functor F.obj) f.1.1)) (by simp) (by simp) (colimit.is_colimit _) (colimit.is_colimit _) (colimit.is_colimit _) } /-- Any category with coproducts and coequalizers has all colimits. See https://stacks.math.columbia.edu/tag/002P. -/ lemma colimits_from_coequalizers_and_coproducts [has_products C] [has_equalizers C] : has_limits C := { has_limits_of_shape := λ J 𝒥, { has_limit := λ F, by exactI has_limit_of_equalizer_and_product F } } /-- Any category with finite coproducts and coequalizers has all finite colimits. See https://stacks.math.columbia.edu/tag/002Q. -/ lemma finite_colimits_from_coequalizers_and_finite_coproducts [has_finite_coproducts C] [has_coequalizers C] : has_finite_colimits C := ⟨λ J _ _, { has_colimit := λ F, by exactI has_colimit_of_coequalizer_and_coproduct F }⟩ noncomputable theory section variables [has_colimits_of_shape (discrete J) C] [has_colimits_of_shape (discrete (Σ p : J × J, p.1 ⟶ p.2)) C] [has_coequalizers C] variables (G : C ⥤ D) [preserves_colimits_of_shape walking_parallel_pair G] [preserves_colimits_of_shape (discrete J) G] [preserves_colimits_of_shape (discrete (Σ p : J × J, p.1 ⟶ p.2)) G] /-- If a functor preserves coequalizers and the appropriate coproducts, it preserves colimits. -/ def preserves_colimit_of_preserves_coequalizers_and_coproduct : preserves_colimits_of_shape J G := { preserves_colimit := λ K, begin let P := ∐ K.obj, let Q := ∐ (λ (f : (Σ (p : J × J), p.fst ⟶ p.snd)), K.obj f.1.1), let s : Q ⟶ P := sigma.desc (λ f, K.map f.2 ≫ colimit.ι (discrete.functor K.obj) _), let t : Q ⟶ P := sigma.desc (λ f, colimit.ι (discrete.functor K.obj) f.1.1), let I := coequalizer s t, let i : P ⟶ I := coequalizer.π s t, apply preserves_colimit_of_preserves_colimit_cocone (build_is_colimit s t (by simp) (by simp) (colimit.is_colimit _) (colimit.is_colimit _) (colimit.is_colimit _)), refine is_colimit.of_iso_colimit (build_is_colimit _ _ _ _ _ _ _) _, { exact cofan.mk (G.obj Q) (λ j, G.map (sigma.ι _ j)) }, { exact cofan.mk _ (λ f, G.map (sigma.ι _ f)) }, { apply G.map s }, { apply G.map t }, { intro f, dsimp, simp only [←G.map_comp, colimit.ι_desc, cofan.mk_ι_app] }, { intro f, dsimp, simp only [←G.map_comp, colimit.ι_desc, cofan.mk_ι_app] }, { apply cofork.of_π (G.map i) _, simp only [← G.map_comp, coequalizer.condition] }, { apply is_colimit_of_has_coproduct_of_preserves_colimit }, { apply is_colimit_of_has_coproduct_of_preserves_colimit }, { apply is_colimit_cofork_map_of_is_colimit, apply coequalizer_is_coequalizer }, refine cocones.ext (iso.refl _) _, intro j, dsimp, simp, -- See note [dsimp, simp]. end } end /-- If G preserves coequalizers and finite coproducts, it preserves finite colimits. -/ def preserves_finite_colimits_of_preserves_coequalizers_and_finite_coproducts [has_coequalizers C] [has_finite_coproducts C] (G : C ⥤ D) [preserves_colimits_of_shape walking_parallel_pair G] [∀ J [fintype J], preserves_colimits_of_shape (discrete J) G] (J : Type v) [small_category J] [fin_category J] : preserves_colimits_of_shape J G := preserves_colimit_of_preserves_coequalizers_and_coproduct G /-- If G preserves coequalizers and coproducts, it preserves all colimits. -/ def preserves_colimits_of_preserves_coequalizers_and_coproducts [has_coequalizers C] [has_coproducts C] (G : C ⥤ D) [preserves_colimits_of_shape walking_parallel_pair G] [∀ J, preserves_colimits_of_shape (discrete J) G] : preserves_colimits G := { preserves_colimits_of_shape := λ J 𝒥, by exactI preserves_colimit_of_preserves_coequalizers_and_coproduct G } end category_theory.limits
46b4533462b8d1b0716ec01034ea0960c8b369ab
a726f88081e44db9edfd14d32cfe9c4393ee56a4
/src/game/world9/level2.lean
ff38d7739c83936b7d95c57ab3e05267971f9fc3
[]
no_license
b-mehta/natural_number_game
80451bf10277adc89a55dbe8581692c36d822462
9faf799d0ab48ecbc89b3d70babb65ba64beee3b
refs/heads/master
1,598,525,389,186
1,573,516,674,000
1,573,516,674,000
217,339,684
0
0
null
1,571,933,100,000
1,571,933,099,000
null
UTF-8
Lean
false
false
555
lean
import game.world9.level1 -- hide namespace mynat -- hide /- # Advanced Multiplication World ## Level 2: `eq_zero_or_eq_zero_of_mul_eq_zero` A variant on the previous level. -/ /- Theorem If $a * b = 0$, then at least one of $a$ or $b$ is equal to zero. -/ theorem eq_zero_or_eq_zero_of_mul_eq_zero (a b : mynat) (h : a * b = 0) : a = 0 ∨ b = 0 := begin [less_leaky] cases a with d, left, refl, cases b with e he, right, refl, exfalso, rw mul_succ at h, rw add_succ at h, exact succ_ne_zero _ h, end end mynat -- hide
a76c77c32f1461ccaf2af5a2a1f6d0f43f10d624
e0f9ba56b7fedc16ef8697f6caeef5898b435143
/src/tactic/linarith.lean
e1c1892d10ec886eb9d8f1aac3a06cb6f78fcb57
[ "Apache-2.0" ]
permissive
anrddh/mathlib
6a374da53c7e3a35cb0298b0cd67824efef362b4
a4266a01d2dcb10de19369307c986d038c7bb6a6
refs/heads/master
1,656,710,827,909
1,589,560,456,000
1,589,560,456,000
264,271,800
0
0
Apache-2.0
1,589,568,062,000
1,589,568,061,000
null
UTF-8
Lean
false
false
35,448
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Robert Y. Lewis -/ import tactic.ring import data.tree /-! # `linarith` A tactic for discharging linear arithmetic goals using Fourier-Motzkin elimination. `linarith` is (in principle) complete for ℚ and ℝ. It is not complete for non-dense orders, i.e. ℤ. - @TODO: investigate storing comparisons in a list instead of a set, for possible efficiency gains - @TODO: delay proofs of denominator normalization and nat casting until after contradiction is found -/ meta def nat.to_pexpr : ℕ → pexpr | 0 := ``(0) | 1 := ``(1) | n := if n % 2 = 0 then ``(bit0 %%(nat.to_pexpr (n/2))) else ``(bit1 %%(nat.to_pexpr (n/2))) open native namespace linarith section lemmas lemma int.coe_nat_bit0 (n : ℕ) : (↑(bit0 n : ℕ) : ℤ) = bit0 (↑n : ℤ) := by simp [bit0] lemma int.coe_nat_bit1 (n : ℕ) : (↑(bit1 n : ℕ) : ℤ) = bit1 (↑n : ℤ) := by simp [bit1, bit0] lemma int.coe_nat_bit0_mul (n : ℕ) (x : ℕ) : (↑(bit0 n * x) : ℤ) = (↑(bit0 n) : ℤ) * (↑x : ℤ) := by simp lemma int.coe_nat_bit1_mul (n : ℕ) (x : ℕ) : (↑(bit1 n * x) : ℤ) = (↑(bit1 n) : ℤ) * (↑x : ℤ) := by simp lemma int.coe_nat_one_mul (x : ℕ) : (↑(1 * x) : ℤ) = 1 * (↑x : ℤ) := by simp lemma int.coe_nat_zero_mul (x : ℕ) : (↑(0 * x) : ℤ) = 0 * (↑x : ℤ) := by simp lemma int.coe_nat_mul_bit0 (n : ℕ) (x : ℕ) : (↑(x * bit0 n) : ℤ) = (↑x : ℤ) * (↑(bit0 n) : ℤ) := by simp lemma int.coe_nat_mul_bit1 (n : ℕ) (x : ℕ) : (↑(x * bit1 n) : ℤ) = (↑x : ℤ) * (↑(bit1 n) : ℤ) := by simp lemma int.coe_nat_mul_one (x : ℕ) : (↑(x * 1) : ℤ) = (↑x : ℤ) * 1 := by simp lemma int.coe_nat_mul_zero (x : ℕ) : (↑(x * 0) : ℤ) = (↑x : ℤ) * 0 := by simp lemma nat_eq_subst {n1 n2 : ℕ} {z1 z2 : ℤ} (hn : n1 = n2) (h1 : ↑n1 = z1) (h2 : ↑n2 = z2) : z1 = z2 := by simpa [eq.symm h1, eq.symm h2, int.coe_nat_eq_coe_nat_iff] lemma nat_le_subst {n1 n2 : ℕ} {z1 z2 : ℤ} (hn : n1 ≤ n2) (h1 : ↑n1 = z1) (h2 : ↑n2 = z2) : z1 ≤ z2 := by simpa [eq.symm h1, eq.symm h2, int.coe_nat_le] lemma nat_lt_subst {n1 n2 : ℕ} {z1 z2 : ℤ} (hn : n1 < n2) (h1 : ↑n1 = z1) (h2 : ↑n2 = z2) : z1 < z2 := by simpa [eq.symm h1, eq.symm h2, int.coe_nat_lt] lemma eq_of_eq_of_eq {α} [ordered_semiring α] {a b : α} (ha : a = 0) (hb : b = 0) : a + b = 0 := by simp * lemma le_of_eq_of_le {α} [ordered_semiring α] {a b : α} (ha : a = 0) (hb : b ≤ 0) : a + b ≤ 0 := by simp * lemma lt_of_eq_of_lt {α} [ordered_semiring α] {a b : α} (ha : a = 0) (hb : b < 0) : a + b < 0 := by simp * lemma le_of_le_of_eq {α} [ordered_semiring α] {a b : α} (ha : a ≤ 0) (hb : b = 0) : a + b ≤ 0 := by simp * lemma lt_of_lt_of_eq {α} [ordered_semiring α] {a b : α} (ha : a < 0) (hb : b = 0) : a + b < 0 := by simp * lemma mul_neg {α} [ordered_ring α] {a b : α} (ha : a < 0) (hb : b > 0) : b * a < 0 := have (-b)*a > 0, from mul_pos_of_neg_of_neg (neg_neg_of_pos hb) ha, neg_of_neg_pos (by simpa) lemma mul_nonpos {α} [ordered_ring α] {a b : α} (ha : a ≤ 0) (hb : b > 0) : b * a ≤ 0 := have (-b)*a ≥ 0, from mul_nonneg_of_nonpos_of_nonpos (le_of_lt (neg_neg_of_pos hb)) ha, (by simpa) lemma mul_eq {α} [ordered_semiring α] {a b : α} (ha : a = 0) (hb : b > 0) : b * a = 0 := by simp * lemma eq_of_not_lt_of_not_gt {α} [linear_order α] (a b : α) (h1 : ¬ a < b) (h2 : ¬ b < a) : a = b := le_antisymm (le_of_not_gt h2) (le_of_not_gt h1) lemma add_subst {α} [ring α] {n e1 e2 t1 t2 : α} (h1 : n * e1 = t1) (h2 : n * e2 = t2) : n * (e1 + e2) = t1 + t2 := by simp [left_distrib, *] lemma sub_subst {α} [ring α] {n e1 e2 t1 t2 : α} (h1 : n * e1 = t1) (h2 : n * e2 = t2) : n * (e1 - e2) = t1 - t2 := by simp [left_distrib, *, sub_eq_add_neg] lemma neg_subst {α} [ring α] {n e t : α} (h1 : n * e = t) : n * (-e) = -t := by simp * private meta def apnn : tactic unit := `[norm_num] lemma mul_subst {α} [comm_ring α] {n1 n2 k e1 e2 t1 t2 : α} (h1 : n1 * e1 = t1) (h2 : n2 * e2 = t2) (h3 : n1*n2 = k . apnn) : k * (e1 * e2) = t1 * t2 := have h3 : n1 * n2 = k, from h3, by rw [←h3, mul_comm n1, mul_assoc n2, ←mul_assoc n1, h1, ←mul_assoc n2, mul_comm n2, mul_assoc, h2] -- OUCH lemma div_subst {α} [field α] {n1 n2 k e1 e2 t1 : α} (h1 : n1 * e1 = t1) (h2 : n2 / e2 = 1) (h3 : n1*n2 = k) : k * (e1 / e2) = t1 := by rw [←h3, mul_assoc, mul_div_comm, h2, ←mul_assoc, h1, mul_comm, one_mul] end lemmas section datatypes @[derive decidable_eq, derive inhabited] inductive ineq | eq | le | lt open ineq def ineq.max : ineq → ineq → ineq | eq a := a | le a := a | lt a := lt def ineq.is_lt : ineq → ineq → bool | eq le := tt | eq lt := tt | le lt := tt | _ _ := ff def ineq.to_string : ineq → string | eq := "=" | le := "≤" | lt := "<" instance : has_to_string ineq := ⟨ineq.to_string⟩ /-- The main datatype for FM elimination. Variables are represented by natural numbers, each of which has an integer coefficient. Index 0 is reserved for constants, i.e. `coeffs.find 0` is the coefficient of 1. The represented term is `coeffs.keys.sum (λ i, coeffs.find i * Var[i])`. str determines the direction of the comparison -- is it < 0, ≤ 0, or = 0? -/ @[derive _root_.inhabited] meta structure comp := (str : ineq) (coeffs : rb_map ℕ int) meta inductive comp_source | assump : ℕ → comp_source | add : comp_source → comp_source → comp_source | scale : ℕ → comp_source → comp_source meta def comp_source.flatten : comp_source → rb_map ℕ ℕ | (comp_source.assump n) := mk_rb_map.insert n 1 | (comp_source.add c1 c2) := (comp_source.flatten c1).add (comp_source.flatten c2) | (comp_source.scale n c) := (comp_source.flatten c).map (λ v, v * n) meta def comp_source.to_string : comp_source → string | (comp_source.assump e) := to_string e | (comp_source.add c1 c2) := comp_source.to_string c1 ++ " + " ++ comp_source.to_string c2 | (comp_source.scale n c) := to_string n ++ " * " ++ comp_source.to_string c meta instance comp_source.has_to_format : has_to_format comp_source := ⟨λ a, comp_source.to_string a⟩ meta structure pcomp := (c : comp) (src : comp_source) meta def map_lt (m1 m2 : rb_map ℕ int) : bool := list.lex (prod.lex (<) (<)) m1.to_list m2.to_list -- make more efficient meta def comp.lt (c1 c2 : comp) : bool := (c1.str.is_lt c2.str) || (c1.str = c2.str) && map_lt c1.coeffs c2.coeffs meta instance comp.has_lt : has_lt comp := ⟨λ a b, comp.lt a b⟩ meta instance pcomp.has_lt : has_lt pcomp := ⟨λ p1 p2, p1.c < p2.c⟩ -- short-circuit type class inference meta instance pcomp.has_lt_dec : decidable_rel ((<) : pcomp → pcomp → Prop) := by apply_instance meta def comp.coeff_of (c : comp) (a : ℕ) : ℤ := c.coeffs.zfind a meta def comp.scale (c : comp) (n : ℕ) : comp := { c with coeffs := c.coeffs.map ((*) (n : ℤ)) } meta def comp.add (c1 c2 : comp) : comp := ⟨c1.str.max c2.str, c1.coeffs.add c2.coeffs⟩ meta def pcomp.scale (c : pcomp) (n : ℕ) : pcomp := ⟨c.c.scale n, comp_source.scale n c.src⟩ meta def pcomp.add (c1 c2 : pcomp) : pcomp := ⟨c1.c.add c2.c, comp_source.add c1.src c2.src⟩ meta instance pcomp.to_format : has_to_format pcomp := ⟨λ p, to_fmt p.c.coeffs ++ to_string p.c.str ++ "0"⟩ meta instance comp.to_format : has_to_format comp := ⟨λ p, to_fmt p.coeffs⟩ end datatypes section fm_elim /-- If `c1` and `c2` both contain variable `a` with opposite coefficients, produces `v1`, `v2`, and `c` such that `a` has been cancelled in `c := v1*c1 + v2*c2`. -/ meta def elim_var (c1 c2 : comp) (a : ℕ) : option (ℕ × ℕ × comp) := let v1 := c1.coeff_of a, v2 := c2.coeff_of a in if v1 * v2 < 0 then let vlcm := nat.lcm v1.nat_abs v2.nat_abs, v1' := vlcm / v1.nat_abs, v2' := vlcm / v2.nat_abs in some ⟨v1', v2', comp.add (c1.scale v1') (c2.scale v2')⟩ else none meta def pelim_var (p1 p2 : pcomp) (a : ℕ) : option pcomp := do (n1, n2, c) ← elim_var p1.c p2.c a, return ⟨c, comp_source.add (p1.src.scale n1) (p2.src.scale n2)⟩ meta def comp.is_contr (c : comp) : bool := c.coeffs.empty ∧ c.str = ineq.lt meta def pcomp.is_contr (p : pcomp) : bool := p.c.is_contr meta def elim_with_set (a : ℕ) (p : pcomp) (comps : rb_set pcomp) : rb_set pcomp := if ¬ p.c.coeffs.contains a then mk_rb_set.insert p else comps.fold mk_rb_set $ λ pc s, match pelim_var p pc a with | some pc := s.insert pc | none := s end /-- The state for the elimination monad. * `vars`: the set of variables present in `comps` * `comps`: a set of comparisons * `inputs`: a set of pairs of exprs `(t, pf)`, where `t` is a term and `pf` is a proof that `t {<, ≤, =} 0`, indexed by `ℕ`. * `has_false`: stores a `pcomp` of `0 < 0` if one has been found TODO: is it more efficient to store comps as a list, to avoid comparisons? -/ meta structure linarith_structure := (vars : rb_set ℕ) (comps : rb_set pcomp) @[reducible, derive [monad, monad_except pcomp]] meta def linarith_monad := state_t linarith_structure (except_t pcomp id) meta def get_vars : linarith_monad (rb_set ℕ) := linarith_structure.vars <$> get meta def get_var_list : linarith_monad (list ℕ) := rb_set.to_list <$> get_vars meta def get_comps : linarith_monad (rb_set pcomp) := linarith_structure.comps <$> get meta def validate : linarith_monad unit := do ⟨_, comps⟩ ← get, match comps.to_list.find (λ p : pcomp, p.is_contr) with | none := return () | some c := throw c end meta def update (vars : rb_set ℕ) (comps : rb_set pcomp) : linarith_monad unit := state_t.put ⟨vars, comps⟩ >> validate meta def monad.elim_var (a : ℕ) : linarith_monad unit := do vs ← get_vars, when (vs.contains a) $ do comps ← get_comps, let cs' := comps.fold mk_rb_set (λ p s, s.union (elim_with_set a p comps)), update (vs.erase a) cs' meta def elim_all_vars : linarith_monad unit := get_var_list >>= list.mmap' monad.elim_var end fm_elim section parse open ineq tactic meta def map_of_expr_mul_aux (c1 c2 : rb_map ℕ ℤ) : option (rb_map ℕ ℤ) := match c1.keys, c2.keys with | [0], _ := some $ c2.scale (c1.zfind 0) | _, [0] := some $ c1.scale (c2.zfind 0) | [], _ := some mk_rb_map | _, [] := some mk_rb_map | _, _ := none end meta def list.mfind {α} (tac : α → tactic unit) : list α → tactic α | [] := failed | (h::t) := tac h >> return h <|> list.mfind t meta def rb_map.find_defeq (red : transparency) {v} (m : expr_map v) (e : expr) : tactic v := prod.snd <$> list.mfind (λ p, is_def_eq e p.1 red) m.to_list /-- Turns an expression into a map from `ℕ` to `ℤ`, for use in a `comp` object. The `expr_map` `ℕ` argument identifies which expressions have already been assigned numbers. Returns a new map. -/ meta def map_of_expr (red : transparency) : expr_map ℕ → expr → tactic (expr_map ℕ × rb_map ℕ ℤ) | m e@`(%%e1 * %%e2) := (do (m', comp1) ← map_of_expr m e1, (m', comp2) ← map_of_expr m' e2, mp ← map_of_expr_mul_aux comp1 comp2, return (m', mp)) <|> (do k ← rb_map.find_defeq red m e, return (m, mk_rb_map.insert k 1)) <|> (let n := m.size + 1 in return (m.insert e n, mk_rb_map.insert n 1)) | m `(%%e1 + %%e2) := do (m', comp1) ← map_of_expr m e1, (m', comp2) ← map_of_expr m' e2, return (m', comp1.add comp2) | m `(%%e1 - %%e2) := do (m', comp1) ← map_of_expr m e1, (m', comp2) ← map_of_expr m' e2, return (m', comp1.add (comp2.scale (-1))) | m `(-%%e) := do (m', comp) ← map_of_expr m e, return (m', comp.scale (-1)) | m e := match e.to_int with | some 0 := return ⟨m, mk_rb_map⟩ | some z := return ⟨m, mk_rb_map.insert 0 z⟩ | none := (do k ← rb_map.find_defeq red m e, return (m, mk_rb_map.insert k 1)) <|> (let n := m.size + 1 in return (m.insert e n, mk_rb_map.insert n 1)) end meta def parse_into_comp_and_expr : expr → option (ineq × expr) | `(%%e < 0) := (ineq.lt, e) | `(%%e ≤ 0) := (ineq.le, e) | `(%%e = 0) := (ineq.eq, e) | _ := none meta def to_comp (red : transparency) (e : expr) (m : expr_map ℕ) : tactic (comp × expr_map ℕ) := do (iq, e) ← parse_into_comp_and_expr e, (m', comp') ← map_of_expr red m e, return ⟨⟨iq, comp'⟩, m'⟩ meta def to_comp_fold (red : transparency) : expr_map ℕ → list expr → tactic (list (option comp) × expr_map ℕ) | m [] := return ([], m) | m (h::t) := (do (c, m') ← to_comp red h m, (l, mp) ← to_comp_fold m' t, return (c::l, mp)) <|> (do (l, mp) ← to_comp_fold m t, return (none::l, mp)) /-- Takes a list of proofs of props of the form `t {<, ≤, =} 0`, and creates a `linarith_structure`. -/ meta def mk_linarith_structure (red : transparency) (l : list expr) : tactic (linarith_structure × rb_map ℕ (expr × expr)) := do pftps ← l.mmap infer_type, (l', map) ← to_comp_fold red mk_rb_map pftps, let lz := list.enum $ ((l.zip pftps).zip l').filter_map (λ ⟨a, b⟩, prod.mk a <$> b), let prmap := rb_map.of_list $ lz.map (λ ⟨n, x⟩, (n, x.1)), let vars : rb_set ℕ := rb_map.set_of_list $ list.range map.size.succ, let pc : rb_set pcomp := rb_map.set_of_list $ lz.map (λ ⟨n, x⟩, ⟨x.2, comp_source.assump n⟩), return (⟨vars, pc⟩, prmap) meta def linarith_monad.run (red : transparency) {α} (tac : linarith_monad α) (l : list expr) : tactic ((pcomp ⊕ α) × rb_map ℕ (expr × expr)) := do (struct, inputs) ← mk_linarith_structure red l, match (state_t.run (validate >> tac) struct).run with | (except.ok (a, _)) := return (sum.inr a, inputs) | (except.error contr) := return (sum.inl contr, inputs) end end parse section prove open ineq tactic meta def get_rel_sides : expr → tactic (expr × expr) | `(%%a < %%b) := return (a, b) | `(%%a ≤ %%b) := return (a, b) | `(%%a = %%b) := return (a, b) | `(%%a ≥ %%b) := return (a, b) | `(%%a > %%b) := return (a, b) | _ := failed meta def mul_expr (n : ℕ) (e : expr) : pexpr := if n = 1 then ``(%%e) else ``(%%(nat.to_pexpr n) * %%e) meta def add_exprs_aux : pexpr → list pexpr → pexpr | p [] := p | p [a] := ``(%%p + %%a) | p (h::t) := add_exprs_aux ``(%%p + %%h) t meta def add_exprs : list pexpr → pexpr | [] := ``(0) | (h::t) := add_exprs_aux h t meta def find_contr (m : rb_set pcomp) : option pcomp := m.keys.find (λ p, p.c.is_contr) meta def ineq_const_mul_nm : ineq → name | lt := ``mul_neg | le := ``mul_nonpos | eq := ``mul_eq meta def ineq_const_nm : ineq → ineq → (name × ineq) | eq eq := (``eq_of_eq_of_eq, eq) | eq le := (``le_of_eq_of_le, le) | eq lt := (``lt_of_eq_of_lt, lt) | le eq := (``le_of_le_of_eq, le) | le le := (`add_nonpos, le) | le lt := (`add_neg_of_nonpos_of_neg, lt) | lt eq := (``lt_of_lt_of_eq, lt) | lt le := (`add_neg_of_neg_of_nonpos, lt) | lt lt := (`add_neg, lt) meta def mk_single_comp_zero_pf (c : ℕ) (h : expr) : tactic (ineq × expr) := do tp ← infer_type h, some (iq, e) ← return $ parse_into_comp_and_expr tp, if c = 0 then do e' ← mk_app ``zero_mul [e], return (eq, e') else if c = 1 then return (iq, h) else do nm ← resolve_name (ineq_const_mul_nm iq), tp ← (prod.snd <$> (infer_type h >>= get_rel_sides)) >>= infer_type, cpos ← to_expr ``((%%c.to_pexpr : %%tp) > 0), (_, ex) ← solve_aux cpos `[norm_num, done], -- e' ← mk_app (ineq_const_mul_nm iq) [h, ex], -- this takes many seconds longer in some examples! why? e' ← to_expr ``(%%nm %%h %%ex) ff, return (iq, e') meta def mk_lt_zero_pf_aux (c : ineq) (pf npf : expr) (coeff : ℕ) : tactic (ineq × expr) := do (iq, h') ← mk_single_comp_zero_pf coeff npf, let (nm, niq) := ineq_const_nm c iq, n ← resolve_name nm, e' ← to_expr ``(%%n %%pf %%h'), return (niq, e') /-- Takes a list of coefficients `[c]` and list of expressions, of equal length. Each expression is a proof of a prop of the form `t {<, ≤, =} 0`. Produces a proof that the sum of `(c*t) {<, ≤, =} 0`, where the `comp` is as strong as possible. -/ meta def mk_lt_zero_pf : list ℕ → list expr → tactic expr | _ [] := fail "no linear hypotheses found" | [c] [h] := prod.snd <$> mk_single_comp_zero_pf c h | (c::ct) (h::t) := do (iq, h') ← mk_single_comp_zero_pf c h, prod.snd <$> (ct.zip t).mfoldl (λ pr ce, mk_lt_zero_pf_aux pr.1 pr.2 ce.2 ce.1) (iq, h') | _ _ := fail "not enough args to mk_lt_zero_pf" meta def term_of_ineq_prf (prf : expr) : tactic expr := do (lhs, _) ← infer_type prf >>= get_rel_sides, return lhs meta structure linarith_config := (discharger : tactic unit := `[ring]) (restrict_type : option Type := none) (restrict_type_reflect : reflected restrict_type . apply_instance) (exfalso : bool := tt) (transparency : transparency := reducible) (split_hypotheses : bool := tt) meta def ineq_pf_tp (pf : expr) : tactic expr := do (_, z) ← infer_type pf >>= get_rel_sides, infer_type z meta def mk_neg_one_lt_zero_pf (tp : expr) : tactic expr := to_expr ``((neg_neg_of_pos zero_lt_one : -1 < (0 : %%tp))) /-- Assumes `e` is a proof that `t = 0`. Creates a proof that `-t = 0`. -/ meta def mk_neg_eq_zero_pf (e : expr) : tactic expr := to_expr ``(neg_eq_zero.mpr %%e) meta def add_neg_eq_pfs : list expr → tactic (list expr) | [] := return [] | (h::t) := do some (iq, tp) ← parse_into_comp_and_expr <$> infer_type h, match iq with | ineq.eq := do nep ← mk_neg_eq_zero_pf h, tl ← add_neg_eq_pfs t, return $ h::nep::tl | _ := list.cons h <$> add_neg_eq_pfs t end /-- Takes a list of proofs of propositions of the form `t {<, ≤, =} 0`, and tries to prove the goal `false`. -/ meta def prove_false_by_linarith1 (cfg : linarith_config) : list expr → tactic unit | [] := fail "no args to linarith" | l@(h::t) := do l' ← add_neg_eq_pfs l, hz ← ineq_pf_tp h >>= mk_neg_one_lt_zero_pf, (sum.inl contr, inputs) ← elim_all_vars.run cfg.transparency (hz::l') | fail "linarith failed to find a contradiction", let coeffs := inputs.keys.map (λ k, (contr.src.flatten.ifind k)), let pfs : list expr := inputs.keys.map (λ k, (inputs.ifind k).1), let zip := (coeffs.zip pfs).filter (λ pr, pr.1 ≠ 0), let (coeffs, pfs) := zip.unzip, mls ← zip.mmap (λ pr, do e ← term_of_ineq_prf pr.2, return (mul_expr pr.1 e)), sm ← to_expr $ add_exprs mls, tgt ← to_expr ``(%%sm = 0), (a, b) ← solve_aux tgt (cfg.discharger >> done), pf ← mk_lt_zero_pf coeffs pfs, pftp ← infer_type pf, (_, nep, _) ← rewrite_core b pftp, pf' ← mk_eq_mp nep pf, mk_app `lt_irrefl [pf'] >>= exact end prove section normalize open tactic set_option eqn_compiler.max_steps 50000 meta def rem_neg (prf : expr) : expr → tactic expr | `(_ ≤ _) := to_expr ``(lt_of_not_ge %%prf) | `(_ < _) := to_expr ``(le_of_not_gt %%prf) | `(_ > _) := to_expr ``(le_of_not_gt %%prf) | `(_ ≥ _) := to_expr ``(lt_of_not_ge %%prf) | e := failed meta def rearr_comp : expr → expr → tactic expr | prf `(%%a ≤ 0) := return prf | prf `(%%a < 0) := return prf | prf `(%%a = 0) := return prf | prf `(%%a ≥ 0) := to_expr ``(neg_nonpos.mpr %%prf) | prf `(%%a > 0) := to_expr ``(neg_neg_of_pos %%prf) | prf `(0 ≥ %%a) := to_expr ``(show %%a ≤ 0, from %%prf) | prf `(0 > %%a) := to_expr ``(show %%a < 0, from %%prf) | prf `(0 = %%a) := to_expr ``(eq.symm %%prf) | prf `(0 ≤ %%a) := to_expr ``(neg_nonpos.mpr %%prf) | prf `(0 < %%a) := to_expr ``(neg_neg_of_pos %%prf) | prf `(%%a ≤ %%b) := to_expr ``(sub_nonpos.mpr %%prf) | prf `(%%a < %%b) := to_expr ``(sub_neg_of_lt %%prf) | prf `(%%a = %%b) := to_expr ``(sub_eq_zero.mpr %%prf) | prf `(%%a > %%b) := to_expr ``(sub_neg_of_lt %%prf) | prf `(%%a ≥ %%b) := to_expr ``(sub_nonpos.mpr %%prf) | prf `(¬ %%t) := do nprf ← rem_neg prf t, tp ← infer_type nprf, rearr_comp nprf tp | prf _ := fail "couldn't rearrange comp" meta def is_numeric : expr → option ℚ | `(%%e1 + %%e2) := (+) <$> is_numeric e1 <*> is_numeric e2 | `(%%e1 - %%e2) := has_sub.sub <$> is_numeric e1 <*> is_numeric e2 | `(%%e1 * %%e2) := (*) <$> is_numeric e1 <*> is_numeric e2 | `(%%e1 / %%e2) := (/) <$> is_numeric e1 <*> is_numeric e2 | `(-%%e) := rat.neg <$> is_numeric e | e := e.to_rat meta def find_cancel_factor : expr → ℕ × tree ℕ | `(%%e1 + %%e2) := let (v1, t1) := find_cancel_factor e1, (v2, t2) := find_cancel_factor e2, lcm := v1.lcm v2 in (lcm, tree.node lcm t1 t2) | `(%%e1 - %%e2) := let (v1, t1) := find_cancel_factor e1, (v2, t2) := find_cancel_factor e2, lcm := v1.lcm v2 in (lcm, tree.node lcm t1 t2) | `(%%e1 * %%e2) := match is_numeric e1, is_numeric e2 with | none, none := (1, tree.node 1 tree.nil tree.nil) | _, _ := let (v1, t1) := find_cancel_factor e1, (v2, t2) := find_cancel_factor e2, pd := v1*v2 in (pd, tree.node pd t1 t2) end | `(%%e1 / %%e2) := match is_numeric e2 with | some q := let (v1, t1) := find_cancel_factor e1, n := v1.lcm q.num.nat_abs in (n, tree.node n t1 (tree.node q.num.nat_abs tree.nil tree.nil)) | none := (1, tree.node 1 tree.nil tree.nil) end | `(-%%e) := find_cancel_factor e | _ := (1, tree.node 1 tree.nil tree.nil) open tree meta def mk_prod_prf : ℕ → tree ℕ → expr → tactic expr | v (node _ lhs rhs) `(%%e1 + %%e2) := do v1 ← mk_prod_prf v lhs e1, v2 ← mk_prod_prf v rhs e2, mk_app ``add_subst [v1, v2] | v (node _ lhs rhs) `(%%e1 - %%e2) := do v1 ← mk_prod_prf v lhs e1, v2 ← mk_prod_prf v rhs e2, mk_app ``sub_subst [v1, v2] | v (node n lhs@(node ln _ _) rhs) `(%%e1 * %%e2) := do tp ← infer_type e1, v1 ← mk_prod_prf ln lhs e1, v2 ← mk_prod_prf (v/ln) rhs e2, ln' ← tp.of_nat ln, vln' ← tp.of_nat (v/ln), v' ← tp.of_nat v, ntp ← to_expr ``(%%ln' * %%vln' = %%v'), (_, npf) ← solve_aux ntp `[norm_num, done], mk_app ``mul_subst [v1, v2, npf] | v (node n lhs rhs@(node rn _ _)) `(%%e1 / %%e2) := do tp ← infer_type e1, v1 ← mk_prod_prf (v/rn) lhs e1, rn' ← tp.of_nat rn, vrn' ← tp.of_nat (v/rn), n' ← tp.of_nat n, v' ← tp.of_nat v, ntp ← to_expr ``(%%rn' / %%e2 = 1), (_, npf) ← solve_aux ntp `[norm_num, done], ntp2 ← to_expr ``(%%vrn' * %%n' = %%v'), (_, npf2) ← solve_aux ntp2 `[norm_num, done], mk_app ``div_subst [v1, npf, npf2] | v t `(-%%e) := do v' ← mk_prod_prf v t e, mk_app ``neg_subst [v'] | v _ e := do tp ← infer_type e, v' ← tp.of_nat v, e' ← to_expr ``(%%v' * %%e), mk_app `eq.refl [e'] /-- Given `e`, a term with rational division, produces a natural number `n` and a proof of `n*e = e'`, where `e'` has no division. -/ meta def kill_factors (e : expr) : tactic (ℕ × expr) := let (n, t) := find_cancel_factor e in do e' ← mk_prod_prf n t e, return (n, e') open expr meta def expr_contains (n : name) : expr → bool | (const nm _) := nm = n | (lam _ _ _ bd) := expr_contains bd | (pi _ _ _ bd) := expr_contains bd | (app e1 e2) := expr_contains e1 || expr_contains e2 | _ := ff lemma sub_into_lt {α} [ordered_semiring α] {a b : α} (he : a = b) (hl : a ≤ 0) : b ≤ 0 := by rwa he at hl meta def norm_hyp_aux (h' lhs : expr) : tactic expr := do (v, lhs') ← kill_factors lhs, if v = 1 then return h' else do (ih, h'') ← mk_single_comp_zero_pf v h', (_, nep, _) ← infer_type h'' >>= rewrite_core lhs', mk_eq_mp nep h'' meta def norm_hyp (h : expr) : tactic expr := do htp ← infer_type h, h' ← rearr_comp h htp, some (c, lhs) ← parse_into_comp_and_expr <$> infer_type h', if expr_contains `has_div.div lhs then norm_hyp_aux h' lhs else return h' meta def get_contr_lemma_name : expr → option name | `(%%a < %%b) := return `lt_of_not_ge | `(%%a ≤ %%b) := return `le_of_not_gt | `(%%a = %%b) := return ``eq_of_not_lt_of_not_gt | `(%%a ≠ %%b) := return `not.intro | `(%%a ≥ %%b) := return `le_of_not_gt | `(%%a > %%b) := return `lt_of_not_ge | `(¬ %%a < %%b) := return `not.intro | `(¬ %%a ≤ %%b) := return `not.intro | `(¬ %%a = %%b) := return `not.intro | `(¬ %%a ≥ %%b) := return `not.intro | `(¬ %%a > %%b) := return `not.intro | _ := none /-- Assumes the input `t` is of type `ℕ`. Produces `t'` of type `ℤ` such that `↑t = t'` and a proof of equality. -/ meta def cast_expr (e : expr) : tactic (expr × expr) := do s ← [`int.coe_nat_add, `int.coe_nat_zero, `int.coe_nat_one, ``int.coe_nat_bit0_mul, ``int.coe_nat_bit1_mul, ``int.coe_nat_zero_mul, ``int.coe_nat_one_mul, ``int.coe_nat_mul_bit0, ``int.coe_nat_mul_bit1, ``int.coe_nat_mul_zero, ``int.coe_nat_mul_one, ``int.coe_nat_bit0, ``int.coe_nat_bit1].mfoldl simp_lemmas.add_simp simp_lemmas.mk, ce ← to_expr ``(↑%%e : ℤ), simplify s [] ce {fail_if_unchanged := ff} meta def is_nat_int_coe : expr → option expr | `((↑(%%n : ℕ) : ℤ)) := some n | _ := none meta def mk_coe_nat_nonneg_prf (e : expr) : tactic expr := mk_app `int.coe_nat_nonneg [e] meta def get_nat_comps : expr → list expr | `(%%a + %%b) := (get_nat_comps a).append (get_nat_comps b) | `(%%a * %%b) := (get_nat_comps a).append (get_nat_comps b) | e := match is_nat_int_coe e with | some e' := [e'] | none := [] end meta def mk_coe_nat_nonneg_prfs (e : expr) : tactic (list expr) := (get_nat_comps e).mmap mk_coe_nat_nonneg_prf meta def mk_cast_eq_and_nonneg_prfs (pf a b : expr) (ln : name) : tactic (list expr) := do (a', prfa) ← cast_expr a, (b', prfb) ← cast_expr b, la ← mk_coe_nat_nonneg_prfs a', lb ← mk_coe_nat_nonneg_prfs b', pf' ← mk_app ln [pf, prfa, prfb], return $ pf'::(la.append lb) meta def mk_int_pfs_of_nat_pf (pf : expr) : tactic (list expr) := do tp ← infer_type pf, match tp with | `(%%a = %%b) := mk_cast_eq_and_nonneg_prfs pf a b ``nat_eq_subst | `(%%a ≤ %%b) := mk_cast_eq_and_nonneg_prfs pf a b ``nat_le_subst | `(%%a < %%b) := mk_cast_eq_and_nonneg_prfs pf a b ``nat_lt_subst | `(%%a ≥ %%b) := mk_cast_eq_and_nonneg_prfs pf b a ``nat_le_subst | `(%%a > %%b) := mk_cast_eq_and_nonneg_prfs pf b a ``nat_lt_subst | `(¬ %%a ≤ %%b) := do pf' ← mk_app ``lt_of_not_ge [pf], mk_cast_eq_and_nonneg_prfs pf' b a ``nat_lt_subst | `(¬ %%a < %%b) := do pf' ← mk_app ``le_of_not_gt [pf], mk_cast_eq_and_nonneg_prfs pf' b a ``nat_le_subst | `(¬ %%a ≥ %%b) := do pf' ← mk_app ``lt_of_not_ge [pf], mk_cast_eq_and_nonneg_prfs pf' a b ``nat_lt_subst | `(¬ %%a > %%b) := do pf' ← mk_app ``le_of_not_gt [pf], mk_cast_eq_and_nonneg_prfs pf' a b ``nat_le_subst | _ := fail "mk_int_pfs_of_nat_pf failed: proof is not an inequality" end meta def mk_non_strict_int_pf_of_strict_int_pf (pf : expr) : tactic expr := do tp ← infer_type pf, match tp with | `(%%a < %%b) := to_expr ``(@cast (%%a < %%b) (%%a + 1 ≤ %%b) (by refl) %%pf) | `(%%a > %%b) := to_expr ``(@cast (%%a > %%b) (%%a ≥ %%b + 1) (by refl) %%pf) | `(¬ %%a ≤ %%b) := to_expr ``(@cast (%%a > %%b) (%%a ≥ %%b + 1) (by refl) (lt_of_not_ge %%pf)) | `(¬ %%a ≥ %%b) := to_expr ``(@cast (%%a < %%b) (%%a + 1 ≤ %%b) (by refl) (lt_of_not_ge %%pf)) | _ := fail "mk_non_strict_int_pf_of_strict_int_pf failed: proof is not an inequality" end meta def guard_is_nat_prop : expr → tactic unit | `(%%a = _) := infer_type a >>= unify `(ℕ) | `(%%a ≤ _) := infer_type a >>= unify `(ℕ) | `(%%a < _) := infer_type a >>= unify `(ℕ) | `(%%a ≥ _) := infer_type a >>= unify `(ℕ) | `(%%a > _) := infer_type a >>= unify `(ℕ) | `(¬ %%p) := guard_is_nat_prop p | _ := failed meta def guard_is_strict_int_prop : expr → tactic unit | `(%%a < _) := infer_type a >>= unify `(ℤ) | `(%%a > _) := infer_type a >>= unify `(ℤ) | `(¬ %%a ≤ _) := infer_type a >>= unify `(ℤ) | `(¬ %%a ≥ _) := infer_type a >>= unify `(ℤ) | _ := failed meta def replace_nat_pfs : list expr → tactic (list expr) | [] := return [] | (h::t) := (do infer_type h >>= guard_is_nat_prop, ls ← mk_int_pfs_of_nat_pf h, list.append ls <$> replace_nat_pfs t) <|> list.cons h <$> replace_nat_pfs t meta def replace_strict_int_pfs : list expr → tactic (list expr) | [] := return [] | (h::t) := (do infer_type h >>= guard_is_strict_int_prop, l ← mk_non_strict_int_pf_of_strict_int_pf h, list.cons l <$> replace_strict_int_pfs t) <|> list.cons h <$> replace_strict_int_pfs t meta def partition_by_type_aux : rb_lmap expr expr → list expr → tactic (rb_lmap expr expr) | m [] := return m | m (h::t) := do tp ← ineq_pf_tp h, partition_by_type_aux (m.insert tp h) t meta def partition_by_type (l : list expr) : tactic (rb_lmap expr expr) := partition_by_type_aux mk_rb_map l private meta def try_linarith_on_lists (cfg : linarith_config) (ls : list (list expr)) : tactic unit := (first $ ls.map $ prove_false_by_linarith1 cfg) <|> fail "linarith failed" /-- Takes a list of proofs of propositions. Filters out the proofs of linear (in)equalities, and tries to use them to prove `false`. If `pref_type` is given, starts by working over this type. -/ meta def prove_false_by_linarith (cfg : linarith_config) (pref_type : option expr) (l : list expr) : tactic unit := do l' ← replace_nat_pfs l, l'' ← replace_strict_int_pfs l', ls ← list.reduce_option <$> l''.mmap (λ h, (do s ← norm_hyp h, return (some s)) <|> return none) >>= partition_by_type, pref_type ← (unify pref_type.iget `(ℕ) >> return (some `(ℤ) : option expr)) <|> return pref_type, match cfg.restrict_type, rb_map.values ls, pref_type with | some rtp, _, _ := do m ← mk_mvar, unify `(some %%m : option Type) cfg.restrict_type_reflect, m ← instantiate_mvars m, prove_false_by_linarith1 cfg (ls.ifind m) | none, [ls'], _ := prove_false_by_linarith1 cfg ls' | none, ls', none := try_linarith_on_lists cfg ls' | none, _, (some t) := prove_false_by_linarith1 cfg (ls.ifind t) <|> try_linarith_on_lists cfg (rb_map.values (ls.erase t)) end end normalize end linarith section open tactic linarith open lean lean.parser interactive tactic interactive.types local postfix `?`:9001 := optional local postfix *:9001 := many meta def linarith.elab_arg_list : option (list pexpr) → tactic (list expr) | none := return [] | (some l) := l.mmap i_to_expr meta def linarith.preferred_type_of_goal : option expr → tactic (option expr) | none := return none | (some e) := some <$> ineq_pf_tp e /-- `linarith.interactive_aux cfg o_goal restrict_hyps args`: * `cfg` is a `linarith_config` object * `o_goal : option expr` is the local constant corresponding to the former goal, if there was one * `restrict_hyps : bool` is `tt` if `linarith only [...]` was used * `args : option (list pexpr)` is the optional list of arguments in `linarith [...]` -/ meta def linarith.interactive_aux (cfg : linarith_config) : option expr → bool → option (list pexpr) → tactic unit | none tt none := fail "linarith only called with no arguments" | none tt (some l) := l.mmap i_to_expr >>= prove_false_by_linarith cfg none | (some e) tt l := do tp ← ineq_pf_tp e, list.cons e <$> linarith.elab_arg_list l >>= prove_false_by_linarith cfg (some tp) | oe ff l := do otp ← linarith.preferred_type_of_goal oe, list.append <$> local_context <*> (list.filter (λ a, bnot $ expr.is_local_constant a) <$> linarith.elab_arg_list l) >>= prove_false_by_linarith cfg otp /-- Tries to prove a goal of `false` by linear arithmetic on hypotheses. If the goal is a linear (in)equality, tries to prove it by contradiction. If the goal is not `false` or an inequality, applies `exfalso` and tries linarith on the hypotheses. * `linarith` will use all relevant hypotheses in the local context. * `linarith [t1, t2, t3]` will add proof terms t1, t2, t3 to the local context. * `linarith only [h1, h2, h3, t1, t2, t3]` will use only the goal (if relevant), local hypotheses `h1`, `h2`, `h3`, and proofs `t1`, `t2`, `t3`. It will ignore the rest of the local context. * `linarith!` will use a stronger reducibility setting to identify atoms. Config options: * `linarith {exfalso := ff}` will fail on a goal that is neither an inequality nor `false` * `linarith {restrict_type := T}` will run only on hypotheses that are inequalities over `T` * `linarith {discharger := tac}` will use `tac` instead of `ring` for normalization. Options: `ring2`, `ring SOP`, `simp` -/ meta def tactic.interactive.linarith (red : parse ((tk "!")?)) (restr : parse ((tk "only")?)) (hyps : parse pexpr_list?) (cfg : linarith_config := {}) : tactic unit := let cfg := if red.is_some then {cfg with transparency := semireducible, discharger := `[ring!]} else cfg in do t ← target, when cfg.split_hypotheses (try auto.split_hyps), match get_contr_lemma_name t with | some nm := seq (applyc nm) $ do t ← intro1, linarith.interactive_aux cfg (some t) restr.is_some hyps | none := if cfg.exfalso then exfalso >> linarith.interactive_aux cfg none restr.is_some hyps else fail "linarith failed: target type is not an inequality." end add_hint_tactic "linarith" /-- `linarith` attempts to find a contradiction between hypotheses that are linear (in)equalities. Equivalently, it can prove a linear inequality by assuming its negation and proving `false`. In theory, `linarith` should prove any goal that is true in the theory of linear arithmetic over the rationals. While there is some special handling for non-dense orders like `nat` and `int`, this tactic is not complete for these theories and will not prove every true goal. An example: ```lean example (x y z : ℚ) (h1 : 2*x < 3*y) (h2 : -4*x + 2*z < 0) (h3 : 12*y - 4* z < 0) : false := by linarith ``` `linarith` will use all appropriate hypotheses and the negation of the goal, if applicable. `linarith [t1, t2, t3]` will additionally use proof terms `t1, t2, t3`. `linarith only [h1, h2, h3, t1, t2, t3]` will use only the goal (if relevant), local hypotheses `h1`, `h2`, `h3`, and proofs `t1`, `t2`, `t3`. It will ignore the rest of the local context. `linarith!` will use a stronger reducibility setting to try to identify atoms. For example, ```lean example (x : ℚ) : id x ≥ x := by linarith ``` will fail, because `linarith` will not identify `x` and `id x`. `linarith!` will. This can sometimes be expensive. `linarith {discharger := tac, restrict_type := tp, exfalso := ff}` takes a config object with five optional arguments: * `discharger` specifies a tactic to be used for reducing an algebraic equation in the proof stage. The default is `ring`. Other options currently include `ring SOP` or `simp` for basic problems. * `restrict_type` will only use hypotheses that are inequalities over `tp`. This is useful if you have e.g. both integer and rational valued inequalities in the local context, which can sometimes confuse the tactic. * `transparency` controls how hard `linarith` will try to match atoms to each other. By default it will only unfold `reducible` definitions. * If `split_hypotheses` is true, `linarith` will split conjunctions in the context into separate hypotheses. * If `exfalso` is false, `linarith` will fail when the goal is neither an inequality nor `false`. (True by default.) -/ add_tactic_doc { name := "linarith", category := doc_category.tactic, decl_names := [`tactic.interactive.linarith], tags := ["arithmetic", "decision procedure", "finishing"] } end
bf6b5ce5ca910efba848166571b06b4bd63f12a3
205f0fc16279a69ea36e9fd158e3a97b06834ce2
/src/01_Equality/04_propositions_as_types.lean
5c322b7cf31b47d8075874093770cf25d0cd295e
[]
no_license
kevinsullivan/cs-dm-lean
b21d3ca1a9b2a0751ba13fcb4e7b258010a5d124
a06a94e98be77170ca1df486c8189338b16cf6c6
refs/heads/master
1,585,948,743,595
1,544,339,346,000
1,544,339,346,000
155,570,767
1
3
null
1,541,540,372,000
1,540,995,993,000
Lean
UTF-8
Lean
false
false
6,749
lean
/- Wait! Lean is telling us that: eq.refl 0 : 0 = 0. Putting parenthesis in can make it easier to read: (eq.refl 0) : (0 = 0). We've so far read this as saying that (eq.refl 0) is a proof of 0 = 0. But the observant reader will see that it looks just like a type judgment as well. It looks like it's saying that (eq.refl 0) is a value of type (0 = 0). And indeed that is exactly what it's saying. Here is the deep idea: in the "constructive logic" of Lean, propositions are formalized as types, and proofs are represented values of these types! A proof, then, is valid for a given proposition if it is a value of the corresponding type. And Lean's type checker can always determine whether that is the case! In lieu of human checking of the validity of proofs, we therefore now have a mechanical proof checker! Read the eq.refl inference rule again. We can now see it clearly as defining a computation. It can now be seen as saying, "if you give me any value, t, I will infer its type, T, and will construct and return a value of type, t = t. Not only that but the type-checker will provide you with a very high degree of assurance that it's a valid proof! -/ /- We can also now understand what it means when we say that Lean is a proof checker. It means that Lean will not allow us to use proofs that are not valid with respect to the propositions/types they are said to prove, because they won't type check. -/ /- Let's look at type checking a little more deeply. We can always assign to a variable a value of the type that the variable is declared to have. -/ def n : nat := 1 /- This Lean definition says that n is a variable for which a value of type nat must be provided (n : nat), and it goes on to assign to n ( := ) the value 1. The Lean type checker checks that 1 is a value of type nat, which it is. Lean therefore accepts the definition, and consequently n is defined, with the value, 1, for the remainder of this file. -/ /- EXERCISE: Define s to have the type, string, and the value, "Hello, Lean!" -/ /- We note that we could have elided the explicit type declaration (n : nat), as Lean infers from the value, 1, on the right, that the intended type of n can only be nat. -/ def n' := 1 #check n' /- EXERCISE: define s' to be "Hello, Lean", leaving it to Lean to infer the type of s'. -/ /- The type checker also absolutely prevents the assignment to a variable of a value that is not of the right type. Read the following code and identify the type error, then uncomment it and see how Lean detects and reports the error. Be sure you understand the error message. This one is self-explanatory. -/ -- def n'' : nat := "Hello Lean!" /- Now let's replace the "nat" type with the type "0 = 0." Remember, every proposition is now viewed as a type. We could thus similarly declare a variable, p, to have this type, just as we declared n to have type nat. Finally we would need to assign to p a value of this type, which is to say a proof of 0 = 0. Compare this code carefully with that for n, above. Note the deep parallels. Here, however, rather than assigning a value such as 1, we're assigning a value that is a proof, and it, in turn, is produced by applying the eq.refl inference rule to the value 0. -/ def p : 0 = 0 := (eq.refl 0) /- variable type bind value/proof -/ #check p -- what is the type of p? #reduce p -- what is the value of p? /- EXERCISE: To the variable s, bind a proof of the proposition that "Hello Lean!" is equal to itself. EXERCISE: Do the same for the Boolean value, tt. -/ /- And just as the type checker prevents the assignment of a value that is not of the right type to a variable such as n, so it also prevents the assignment to p of a proof that is not of the right type. -/ /- EXERCISE. Explain precisely why Lean reports an error for this code and what it means. (Uncomment the code to see the error, then replace the comments so that the error isn't a problem in the rest of this file.) -/ -- def p' : 0 = 0 := (eq.refl 1) /- EXERCISE: Explain why could you never use eq.refl to successfully produce a proof of 0 = 1? Explain. -/ /- In Lean and related proof assistants, propositions are types, proofs are values of proposition types, and proof checking *is* type checking. Put a start next to this paragraph and be sure that you understand it. It takes time and study to fully grasp these concepts. -/ /- EXERCISE: Prove the following theorem, teqt, that 2 = 1 + 1. Try using eq.refl. -/ /- That last proposition, 2 = 1 + 1, is a bit different because it has different terms on each side of the equals sign. In Lean, these terms are reduced (evaluated) before they are compared, and so eq.refl can still be used to prove this proposition. -/ /- * What is the type of a proposition? *-/ /- We've already seen that types are values, too, and that a type thus has a type. The type of nat is Type, for example. So, in Lean, what is the type of a proposition, such as 0 = 0? Let's find out using #check. -/ #check (0 = 0) /- EXERCISE: What is the type of (0 = 1)? Answer before you #check it, then #check it to confirm. EXERCISE: What is the type of "Hello Lean" = "Hello Lean"? -/ /- Lean tells us that the type of each proposition is Prop. In Lean, every logical proposition is of type Prop, just as every ordinary computational type, such as nat, bool, or string, is of type, Type. So how do Prop and Type relate? Where does Prop fit in? What is its type? What is the type of Prop? We can of course just #check it! -/ #check Prop /- Ah ha. Prop is of type Type, which is to say that that Prop is of type, Type 0. We thus now have a complete picture of the type hierarchy of Lean. Prop : Type : Type 1 : Type 2 : Type 3 : ... | | 0 = 0 nat | | eq.refl 0 1 Prop is the first type in the hierarchy. Every propositional type is of type Prop. We illustrate here that the type (0=0) is of type Prop, but so is 0 = 1, 1 = 1, tt = tt, and so are all of the other propositions we'll ever see in Lean. All propositions, which again are themselves types, are of type Prop in the logic of Lean. By contrast, computational types, such as nat, but also string, bool, and function types (we will see them soon enough) are of type, Type. The lowest layer in the diagram illustrates where values fit in. The proof, eq.refl 0, is a value of type (0 = 0), just as 1 is a value of type nat. We will never need types above Type in this class. Mathematicians, logicians, and program verification experts who use Lean and other tools like it do sometimes need to be careful about how values fall into the various "type universes," as these various levels are called. -/
cd64044c169a9d69d48dbf14d98aa558e6aeb97c
9dc8cecdf3c4634764a18254e94d43da07142918
/src/analysis/calculus/mean_value.lean
3a9e0bc673cae6c880260ea90b2496cceb248600
[ "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
74,763
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel, Yury Kudryashov -/ import analysis.calculus.local_extr import analysis.convex.slope import analysis.convex.topology import data.complex.is_R_or_C /-! # The mean value inequality and equalities In this file we prove the following facts: * `convex.norm_image_sub_le_of_norm_deriv_le` : if `f` is differentiable on a convex set `s` and the norm of its derivative is bounded by `C`, then `f` is Lipschitz continuous on `s` with constant `C`; also a variant in which what is bounded by `C` is the norm of the difference of the derivative from a fixed linear map. This lemma and its versions are formulated using `is_R_or_C`, so they work both for real and complex derivatives. * `image_le_of*`, `image_norm_le_of_*` : several similar lemmas deducing `f x ≤ B x` or `∥f x∥ ≤ B x` from upper estimates on `f'` or `∥f'∥`, respectively. These lemmas differ by their assumptions: * `of_liminf_*` lemmas assume that limit inferior of some ratio is less than `B' x`; * `of_deriv_right_*`, `of_norm_deriv_right_*` lemmas assume that the right derivative or its norm is less than `B' x`; * `of_*_lt_*` lemmas assume a strict inequality whenever `f x = B x` or `∥f x∥ = B x`; * `of_*_le_*` lemmas assume a non-strict inequality everywhere on `[a, b)`; * name of a lemma ends with `'` if (1) it assumes that `B` is continuous on `[a, b]` and has a right derivative at every point of `[a, b)`, and (2) the lemma has a counterpart assuming that `B` is differentiable everywhere on `ℝ` * `norm_image_sub_le_*_segment` : if derivative of `f` on `[a, b]` is bounded above by a constant `C`, then `∥f x - f a∥ ≤ C * ∥x - a∥`; several versions deal with right derivative and derivative within `[a, b]` (`has_deriv_within_at` or `deriv_within`). * `convex.is_const_of_fderiv_within_eq_zero` : if a function has derivative `0` on a convex set `s`, then it is a constant on `s`. * `exists_ratio_has_deriv_at_eq_ratio_slope` and `exists_ratio_deriv_eq_ratio_slope` : Cauchy's Mean Value Theorem. * `exists_has_deriv_at_eq_slope` and `exists_deriv_eq_slope` : Lagrange's Mean Value Theorem. * `domain_mvt` : Lagrange's Mean Value Theorem, applied to a segment in a convex domain. * `convex.image_sub_lt_mul_sub_of_deriv_lt`, `convex.mul_sub_lt_image_sub_of_lt_deriv`, `convex.image_sub_le_mul_sub_of_deriv_le`, `convex.mul_sub_le_image_sub_of_le_deriv`, if `∀ x, C (</≤/>/≥) (f' x)`, then `C * (y - x) (</≤/>/≥) (f y - f x)` whenever `x < y`. * `convex.monotone_on_of_deriv_nonneg`, `convex.antitone_on_of_deriv_nonpos`, `convex.strict_mono_of_deriv_pos`, `convex.strict_anti_of_deriv_neg` : if the derivative of a function is non-negative/non-positive/positive/negative, then the function is monotone/antitone/strictly monotone/strictly monotonically decreasing. * `convex_on_of_deriv_monotone_on`, `convex_on_of_deriv2_nonneg` : if the derivative of a function is increasing or its second derivative is nonnegative, then the original function is convex. * `strict_fderiv_of_cont_diff` : a C^1 function over the reals is strictly differentiable. (This is a corollary of the mean value inequality.) -/ variables {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] {F : Type*} [normed_add_comm_group F] [normed_space ℝ F] open metric set asymptotics continuous_linear_map filter open_locale classical topological_space nnreal /-! ### One-dimensional fencing inequalities -/ /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `f a ≤ B a`; * `B` has right derivative `B'` at every point of `[a, b)`; * for each `x ∈ [a, b)` the right-side limit inferior of `(f z - f x) / (z - x)` is bounded above by a function `f'`; * we have `f' x < B' x` whenever `f x = B x`. Then `f x ≤ B x` everywhere on `[a, b]`. -/ lemma image_le_of_liminf_slope_right_lt_deriv_boundary' {f f' : ℝ → ℝ} {a b : ℝ} (hf : continuous_on f (Icc a b)) -- `hf'` actually says `liminf (f z - f x) / (z - x) ≤ f' x` (hf' : ∀ x ∈ Ico a b, ∀ r, f' x < r → ∃ᶠ z in 𝓝[>] x, slope f x z < r) {B B' : ℝ → ℝ} (ha : f a ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ici x) x) (bound : ∀ x ∈ Ico a b, f x = B x → f' x < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → f x ≤ B x := begin change Icc a b ⊆ {x | f x ≤ B x}, set s := {x | f x ≤ B x} ∩ Icc a b, have A : continuous_on (λ x, (f x, B x)) (Icc a b), from hf.prod hB, have : is_closed s, { simp only [s, inter_comm], exact A.preimage_closed_of_closed is_closed_Icc order_closed_topology.is_closed_le' }, apply this.Icc_subset_of_forall_exists_gt ha, rintros x ⟨hxB : f x ≤ B x, xab⟩ y hy, cases hxB.lt_or_eq with hxB hxB, { -- If `f x < B x`, then all we need is continuity of both sides refine nonempty_of_mem (inter_mem _ (Ioc_mem_nhds_within_Ioi ⟨le_rfl, hy⟩)), have : ∀ᶠ x in 𝓝[Icc a b] x, f x < B x, from A x (Ico_subset_Icc_self xab) (is_open.mem_nhds (is_open_lt continuous_fst continuous_snd) hxB), have : ∀ᶠ x in 𝓝[>] x, f x < B x, from nhds_within_le_of_mem (Icc_mem_nhds_within_Ioi xab) this, exact this.mono (λ y, le_of_lt) }, { rcases exists_between (bound x xab hxB) with ⟨r, hfr, hrB⟩, specialize hf' x xab r hfr, have HB : ∀ᶠ z in 𝓝[>] x, r < slope B x z, from (has_deriv_within_at_iff_tendsto_slope' $ lt_irrefl x).1 (hB' x xab).Ioi_of_Ici (Ioi_mem_nhds hrB), obtain ⟨z, hfz, hzB, hz⟩ : ∃ z, slope f x z < r ∧ r < slope B x z ∧ z ∈ Ioc x y, from (hf'.and_eventually (HB.and (Ioc_mem_nhds_within_Ioi ⟨le_rfl, hy⟩))).exists, refine ⟨z, _, hz⟩, have := (hfz.trans hzB).le, rwa [slope_def_field, slope_def_field, div_le_div_right (sub_pos.2 hz.1), hxB, sub_le_sub_iff_right] at this } end /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `f a ≤ B a`; * `B` has derivative `B'` everywhere on `ℝ`; * for each `x ∈ [a, b)` the right-side limit inferior of `(f z - f x) / (z - x)` is bounded above by a function `f'`; * we have `f' x < B' x` whenever `f x = B x`. Then `f x ≤ B x` everywhere on `[a, b]`. -/ lemma image_le_of_liminf_slope_right_lt_deriv_boundary {f f' : ℝ → ℝ} {a b : ℝ} (hf : continuous_on f (Icc a b)) -- `hf'` actually says `liminf (f z - f x) / (z - x) ≤ f' x` (hf' : ∀ x ∈ Ico a b, ∀ r, f' x < r → ∃ᶠ z in 𝓝[>] x, slope f x z < r) {B B' : ℝ → ℝ} (ha : f a ≤ B a) (hB : ∀ x, has_deriv_at B (B' x) x) (bound : ∀ x ∈ Ico a b, f x = B x → f' x < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → f x ≤ B x := image_le_of_liminf_slope_right_lt_deriv_boundary' hf hf' ha (λ x hx, (hB x).continuous_at.continuous_within_at) (λ x hx, (hB x).has_deriv_within_at) bound /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `f a ≤ B a`; * `B` has right derivative `B'` at every point of `[a, b)`; * for each `x ∈ [a, b)` the right-side limit inferior of `(f z - f x) / (z - x)` is bounded above by `B'`. Then `f x ≤ B x` everywhere on `[a, b]`. -/ lemma image_le_of_liminf_slope_right_le_deriv_boundary {f : ℝ → ℝ} {a b : ℝ} (hf : continuous_on f (Icc a b)) {B B' : ℝ → ℝ} (ha : f a ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ici x) x) -- `bound` actually says `liminf (f z - f x) / (z - x) ≤ B' x` (bound : ∀ x ∈ Ico a b, ∀ r, B' x < r → ∃ᶠ z in 𝓝[>] x, slope f x z < r) : ∀ ⦃x⦄, x ∈ Icc a b → f x ≤ B x := begin have Hr : ∀ x ∈ Icc a b, ∀ r > 0, f x ≤ B x + r * (x - a), { intros x hx r hr, apply image_le_of_liminf_slope_right_lt_deriv_boundary' hf bound, { rwa [sub_self, mul_zero, add_zero] }, { exact hB.add (continuous_on_const.mul (continuous_id.continuous_on.sub continuous_on_const)) }, { assume x hx, exact (hB' x hx).add (((has_deriv_within_at_id x (Ici x)).sub_const a).const_mul r) }, { assume x hx _, rw [mul_one], exact (lt_add_iff_pos_right _).2 hr }, exact hx }, assume x hx, have : continuous_within_at (λ r, B x + r * (x - a)) (Ioi 0) 0, from continuous_within_at_const.add (continuous_within_at_id.mul continuous_within_at_const), convert continuous_within_at_const.closure_le _ this (Hr x hx); simp end /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `f a ≤ B a`; * `B` has right derivative `B'` at every point of `[a, b)`; * `f` has right derivative `f'` at every point of `[a, b)`; * we have `f' x < B' x` whenever `f x = B x`. Then `f x ≤ B x` everywhere on `[a, b]`. -/ lemma image_le_of_deriv_right_lt_deriv_boundary' {f f' : ℝ → ℝ} {a b : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) {B B' : ℝ → ℝ} (ha : f a ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ici x) x) (bound : ∀ x ∈ Ico a b, f x = B x → f' x < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → f x ≤ B x := image_le_of_liminf_slope_right_lt_deriv_boundary' hf (λ x hx r hr, (hf' x hx).liminf_right_slope_le hr) ha hB hB' bound /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `f a ≤ B a`; * `B` has derivative `B'` everywhere on `ℝ`; * `f` has right derivative `f'` at every point of `[a, b)`; * we have `f' x < B' x` whenever `f x = B x`. Then `f x ≤ B x` everywhere on `[a, b]`. -/ lemma image_le_of_deriv_right_lt_deriv_boundary {f f' : ℝ → ℝ} {a b : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) {B B' : ℝ → ℝ} (ha : f a ≤ B a) (hB : ∀ x, has_deriv_at B (B' x) x) (bound : ∀ x ∈ Ico a b, f x = B x → f' x < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → f x ≤ B x := image_le_of_deriv_right_lt_deriv_boundary' hf hf' ha (λ x hx, (hB x).continuous_at.continuous_within_at) (λ x hx, (hB x).has_deriv_within_at) bound /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `f a ≤ B a`; * `B` has derivative `B'` everywhere on `ℝ`; * `f` has right derivative `f'` at every point of `[a, b)`; * we have `f' x ≤ B' x` on `[a, b)`. Then `f x ≤ B x` everywhere on `[a, b]`. -/ lemma image_le_of_deriv_right_le_deriv_boundary {f f' : ℝ → ℝ} {a b : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) {B B' : ℝ → ℝ} (ha : f a ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ici x) x) (bound : ∀ x ∈ Ico a b, f' x ≤ B' x) : ∀ ⦃x⦄, x ∈ Icc a b → f x ≤ B x := image_le_of_liminf_slope_right_le_deriv_boundary hf ha hB hB' $ assume x hx r hr, (hf' x hx).liminf_right_slope_le (lt_of_le_of_lt (bound x hx) hr) /-! ### Vector-valued functions `f : ℝ → E` -/ section variables {f : ℝ → E} {a b : ℝ} /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `∥f a∥ ≤ B a`; * `B` has right derivative at every point of `[a, b)`; * for each `x ∈ [a, b)` the right-side limit inferior of `(∥f z∥ - ∥f x∥) / (z - x)` is bounded above by a function `f'`; * we have `f' x < B' x` whenever `∥f x∥ = B x`. Then `∥f x∥ ≤ B x` everywhere on `[a, b]`. -/ lemma image_norm_le_of_liminf_right_slope_norm_lt_deriv_boundary {E : Type*} [normed_add_comm_group E] {f : ℝ → E} {f' : ℝ → ℝ} (hf : continuous_on f (Icc a b)) -- `hf'` actually says `liminf (∥f z∥ - ∥f x∥) / (z - x) ≤ f' x` (hf' : ∀ x ∈ Ico a b, ∀ r, f' x < r → ∃ᶠ z in 𝓝[>] x, slope (norm ∘ f) x z < r) {B B' : ℝ → ℝ} (ha : ∥f a∥ ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ici x) x) (bound : ∀ x ∈ Ico a b, ∥f x∥ = B x → f' x < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → ∥f x∥ ≤ B x := image_le_of_liminf_slope_right_lt_deriv_boundary' (continuous_norm.comp_continuous_on hf) hf' ha hB hB' bound /-- General fencing theorem for continuous functions with an estimate on the norm of the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `∥f a∥ ≤ B a`; * `f` and `B` have right derivatives `f'` and `B'` respectively at every point of `[a, b)`; * the norm of `f'` is strictly less than `B'` whenever `∥f x∥ = B x`. Then `∥f x∥ ≤ B x` everywhere on `[a, b]`. We use one-sided derivatives in the assumptions to make this theorem work for piecewise differentiable functions. -/ lemma image_norm_le_of_norm_deriv_right_lt_deriv_boundary' {f' : ℝ → E} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) {B B' : ℝ → ℝ} (ha : ∥f a∥ ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ici x) x) (bound : ∀ x ∈ Ico a b, ∥f x∥ = B x → ∥f' x∥ < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → ∥f x∥ ≤ B x := image_norm_le_of_liminf_right_slope_norm_lt_deriv_boundary hf (λ x hx r hr, (hf' x hx).liminf_right_slope_norm_le hr) ha hB hB' bound /-- General fencing theorem for continuous functions with an estimate on the norm of the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `∥f a∥ ≤ B a`; * `f` has right derivative `f'` at every point of `[a, b)`; * `B` has derivative `B'` everywhere on `ℝ`; * the norm of `f'` is strictly less than `B'` whenever `∥f x∥ = B x`. Then `∥f x∥ ≤ B x` everywhere on `[a, b]`. We use one-sided derivatives in the assumptions to make this theorem work for piecewise differentiable functions. -/ lemma image_norm_le_of_norm_deriv_right_lt_deriv_boundary {f' : ℝ → E} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) {B B' : ℝ → ℝ} (ha : ∥f a∥ ≤ B a) (hB : ∀ x, has_deriv_at B (B' x) x) (bound : ∀ x ∈ Ico a b, ∥f x∥ = B x → ∥f' x∥ < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → ∥f x∥ ≤ B x := image_norm_le_of_norm_deriv_right_lt_deriv_boundary' hf hf' ha (λ x hx, (hB x).continuous_at.continuous_within_at) (λ x hx, (hB x).has_deriv_within_at) bound /-- General fencing theorem for continuous functions with an estimate on the norm of the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `∥f a∥ ≤ B a`; * `f` and `B` have right derivatives `f'` and `B'` respectively at every point of `[a, b)`; * we have `∥f' x∥ ≤ B x` everywhere on `[a, b)`. Then `∥f x∥ ≤ B x` everywhere on `[a, b]`. We use one-sided derivatives in the assumptions to make this theorem work for piecewise differentiable functions. -/ lemma image_norm_le_of_norm_deriv_right_le_deriv_boundary' {f' : ℝ → E} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) {B B' : ℝ → ℝ} (ha : ∥f a∥ ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ici x) x) (bound : ∀ x ∈ Ico a b, ∥f' x∥ ≤ B' x) : ∀ ⦃x⦄, x ∈ Icc a b → ∥f x∥ ≤ B x := image_le_of_liminf_slope_right_le_deriv_boundary (continuous_norm.comp_continuous_on hf) ha hB hB' $ (λ x hx r hr, (hf' x hx).liminf_right_slope_norm_le (lt_of_le_of_lt (bound x hx) hr)) /-- General fencing theorem for continuous functions with an estimate on the norm of the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `∥f a∥ ≤ B a`; * `f` has right derivative `f'` at every point of `[a, b)`; * `B` has derivative `B'` everywhere on `ℝ`; * we have `∥f' x∥ ≤ B x` everywhere on `[a, b)`. Then `∥f x∥ ≤ B x` everywhere on `[a, b]`. We use one-sided derivatives in the assumptions to make this theorem work for piecewise differentiable functions. -/ lemma image_norm_le_of_norm_deriv_right_le_deriv_boundary {f' : ℝ → E} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) {B B' : ℝ → ℝ} (ha : ∥f a∥ ≤ B a) (hB : ∀ x, has_deriv_at B (B' x) x) (bound : ∀ x ∈ Ico a b, ∥f' x∥ ≤ B' x) : ∀ ⦃x⦄, x ∈ Icc a b → ∥f x∥ ≤ B x := image_norm_le_of_norm_deriv_right_le_deriv_boundary' hf hf' ha (λ x hx, (hB x).continuous_at.continuous_within_at) (λ x hx, (hB x).has_deriv_within_at) bound /-- A function on `[a, b]` with the norm of the right derivative bounded by `C` satisfies `∥f x - f a∥ ≤ C * (x - a)`. -/ theorem norm_image_sub_le_of_norm_deriv_right_le_segment {f' : ℝ → E} {C : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) (bound : ∀x ∈ Ico a b, ∥f' x∥ ≤ C) : ∀ x ∈ Icc a b, ∥f x - f a∥ ≤ C * (x - a) := begin let g := λ x, f x - f a, have hg : continuous_on g (Icc a b), from hf.sub continuous_on_const, have hg' : ∀ x ∈ Ico a b, has_deriv_within_at g (f' x) (Ici x) x, { assume x hx, simpa using (hf' x hx).sub (has_deriv_within_at_const _ _ _) }, let B := λ x, C * (x - a), have hB : ∀ x, has_deriv_at B C x, { assume x, simpa using (has_deriv_at_const x C).mul ((has_deriv_at_id x).sub (has_deriv_at_const x a)) }, convert image_norm_le_of_norm_deriv_right_le_deriv_boundary hg hg' _ hB bound, simp only [g, B], rw [sub_self, norm_zero, sub_self, mul_zero] end /-- A function on `[a, b]` with the norm of the derivative within `[a, b]` bounded by `C` satisfies `∥f x - f a∥ ≤ C * (x - a)`, `has_deriv_within_at` version. -/ theorem norm_image_sub_le_of_norm_deriv_le_segment' {f' : ℝ → E} {C : ℝ} (hf : ∀ x ∈ Icc a b, has_deriv_within_at f (f' x) (Icc a b) x) (bound : ∀x ∈ Ico a b, ∥f' x∥ ≤ C) : ∀ x ∈ Icc a b, ∥f x - f a∥ ≤ C * (x - a) := begin refine norm_image_sub_le_of_norm_deriv_right_le_segment (λ x hx, (hf x hx).continuous_within_at) (λ x hx, _) bound, exact (hf x $ Ico_subset_Icc_self hx).nhds_within (Icc_mem_nhds_within_Ici hx) end /-- A function on `[a, b]` with the norm of the derivative within `[a, b]` bounded by `C` satisfies `∥f x - f a∥ ≤ C * (x - a)`, `deriv_within` version. -/ theorem norm_image_sub_le_of_norm_deriv_le_segment {C : ℝ} (hf : differentiable_on ℝ f (Icc a b)) (bound : ∀x ∈ Ico a b, ∥deriv_within f (Icc a b) x∥ ≤ C) : ∀ x ∈ Icc a b, ∥f x - f a∥ ≤ C * (x - a) := begin refine norm_image_sub_le_of_norm_deriv_le_segment' _ bound, exact λ x hx, (hf x hx).has_deriv_within_at end /-- A function on `[0, 1]` with the norm of the derivative within `[0, 1]` bounded by `C` satisfies `∥f 1 - f 0∥ ≤ C`, `has_deriv_within_at` version. -/ theorem norm_image_sub_le_of_norm_deriv_le_segment_01' {f' : ℝ → E} {C : ℝ} (hf : ∀ x ∈ Icc (0:ℝ) 1, has_deriv_within_at f (f' x) (Icc (0:ℝ) 1) x) (bound : ∀x ∈ Ico (0:ℝ) 1, ∥f' x∥ ≤ C) : ∥f 1 - f 0∥ ≤ C := by simpa only [sub_zero, mul_one] using norm_image_sub_le_of_norm_deriv_le_segment' hf bound 1 (right_mem_Icc.2 zero_le_one) /-- A function on `[0, 1]` with the norm of the derivative within `[0, 1]` bounded by `C` satisfies `∥f 1 - f 0∥ ≤ C`, `deriv_within` version. -/ theorem norm_image_sub_le_of_norm_deriv_le_segment_01 {C : ℝ} (hf : differentiable_on ℝ f (Icc (0:ℝ) 1)) (bound : ∀x ∈ Ico (0:ℝ) 1, ∥deriv_within f (Icc (0:ℝ) 1) x∥ ≤ C) : ∥f 1 - f 0∥ ≤ C := by simpa only [sub_zero, mul_one] using norm_image_sub_le_of_norm_deriv_le_segment hf bound 1 (right_mem_Icc.2 zero_le_one) theorem constant_of_has_deriv_right_zero (hcont : continuous_on f (Icc a b)) (hderiv : ∀ x ∈ Ico a b, has_deriv_within_at f 0 (Ici x) x) : ∀ x ∈ Icc a b, f x = f a := by simpa only [zero_mul, norm_le_zero_iff, sub_eq_zero] using λ x hx, norm_image_sub_le_of_norm_deriv_right_le_segment hcont hderiv (λ y hy, by rw norm_le_zero_iff) x hx theorem constant_of_deriv_within_zero (hdiff : differentiable_on ℝ f (Icc a b)) (hderiv : ∀ x ∈ Ico a b, deriv_within f (Icc a b) x = 0) : ∀ x ∈ Icc a b, f x = f a := begin have H : ∀ x ∈ Ico a b, ∥deriv_within f (Icc a b) x∥ ≤ 0 := by simpa only [norm_le_zero_iff] using λ x hx, hderiv x hx, simpa only [zero_mul, norm_le_zero_iff, sub_eq_zero] using λ x hx, norm_image_sub_le_of_norm_deriv_le_segment hdiff H x hx, end variables {f' g : ℝ → E} /-- If two continuous functions on `[a, b]` have the same right derivative and are equal at `a`, then they are equal everywhere on `[a, b]`. -/ theorem eq_of_has_deriv_right_eq (derivf : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) (derivg : ∀ x ∈ Ico a b, has_deriv_within_at g (f' x) (Ici x) x) (fcont : continuous_on f (Icc a b)) (gcont : continuous_on g (Icc a b)) (hi : f a = g a) : ∀ y ∈ Icc a b, f y = g y := begin simp only [← @sub_eq_zero _ _ (f _)] at hi ⊢, exact hi ▸ constant_of_has_deriv_right_zero (fcont.sub gcont) (λ y hy, by simpa only [sub_self] using (derivf y hy).sub (derivg y hy)), end /-- If two differentiable functions on `[a, b]` have the same derivative within `[a, b]` everywhere on `[a, b)` and are equal at `a`, then they are equal everywhere on `[a, b]`. -/ theorem eq_of_deriv_within_eq (fdiff : differentiable_on ℝ f (Icc a b)) (gdiff : differentiable_on ℝ g (Icc a b)) (hderiv : eq_on (deriv_within f (Icc a b)) (deriv_within g (Icc a b)) (Ico a b)) (hi : f a = g a) : ∀ y ∈ Icc a b, f y = g y := begin have A : ∀ y ∈ Ico a b, has_deriv_within_at f (deriv_within f (Icc a b) y) (Ici y) y := λ y hy, (fdiff y (mem_Icc_of_Ico hy)).has_deriv_within_at.nhds_within (Icc_mem_nhds_within_Ici hy), have B : ∀ y ∈ Ico a b, has_deriv_within_at g (deriv_within g (Icc a b) y) (Ici y) y := λ y hy, (gdiff y (mem_Icc_of_Ico hy)).has_deriv_within_at.nhds_within (Icc_mem_nhds_within_Ici hy), exact eq_of_has_deriv_right_eq A (λ y hy, (hderiv hy).symm ▸ B y hy) fdiff.continuous_on gdiff.continuous_on hi end end /-! ### Vector-valued functions `f : E → G` Theorems in this section work both for real and complex differentiable functions. We use assumptions `[is_R_or_C 𝕜] [normed_space 𝕜 E] [normed_space 𝕜 G]` to achieve this result. For the domain `E` we also assume `[normed_space ℝ E]` to have a notion of a `convex` set. -/ section variables {𝕜 G : Type*} [is_R_or_C 𝕜] [normed_space 𝕜 E] [normed_add_comm_group G] [normed_space 𝕜 G] namespace convex variables {f : E → G} {C : ℝ} {s : set E} {x y : E} {f' : E → E →L[𝕜] G} {φ : E →L[𝕜] G} /-- The mean value theorem on a convex set: if the derivative of a function is bounded by `C`, then the function is `C`-Lipschitz. Version with `has_fderiv_within`. -/ theorem norm_image_sub_le_of_norm_has_fderiv_within_le (hf : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (bound : ∀x∈s, ∥f' x∥ ≤ C) (hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x∥ ≤ C * ∥y - x∥ := begin letI : normed_space ℝ G := restrict_scalars.normed_space ℝ 𝕜 G, /- By composition with `t ↦ x + t • (y-x)`, we reduce to a statement for functions defined on `[0,1]`, for which it is proved in `norm_image_sub_le_of_norm_deriv_le_segment`. We just have to check the differentiability of the composition and bounds on its derivative, which is straightforward but tedious for lack of automation. -/ have C0 : 0 ≤ C := le_trans (norm_nonneg _) (bound x xs), set g : ℝ → E := λ t, x + t • (y - x), have Dg : ∀ t, has_deriv_at g (y-x) t, { assume t, simpa only [one_smul] using ((has_deriv_at_id t).smul_const (y - x)).const_add x }, have segm : Icc 0 1 ⊆ g ⁻¹' s, { rw [← image_subset_iff, ← segment_eq_image'], apply hs.segment_subset xs ys }, have : f x = f (g 0), by { simp only [g], rw [zero_smul, add_zero] }, rw this, have : f y = f (g 1), by { simp only [g], rw [one_smul, add_sub_cancel'_right] }, rw this, have D2: ∀ t ∈ Icc (0:ℝ) 1, has_deriv_within_at (f ∘ g) (f' (g t) (y - x)) (Icc 0 1) t, { intros t ht, have : has_fderiv_within_at f ((f' (g t)).restrict_scalars ℝ) s (g t), from hf (g t) (segm ht), exact this.comp_has_deriv_within_at _ (Dg t).has_deriv_within_at segm }, apply norm_image_sub_le_of_norm_deriv_le_segment_01' D2, refine λ t ht, le_of_op_norm_le _ _ _, exact bound (g t) (segm $ Ico_subset_Icc_self ht) end /-- The mean value theorem on a convex set: if the derivative of a function is bounded by `C` on `s`, then the function is `C`-Lipschitz on `s`. Version with `has_fderiv_within` and `lipschitz_on_with`. -/ theorem lipschitz_on_with_of_nnnorm_has_fderiv_within_le {C : ℝ≥0} (hf : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (bound : ∀x∈s, ∥f' x∥₊ ≤ C) (hs : convex ℝ s) : lipschitz_on_with C f s := begin rw lipschitz_on_with_iff_norm_sub_le, intros x x_in y y_in, exact hs.norm_image_sub_le_of_norm_has_fderiv_within_le hf bound y_in x_in end /-- Let `s` be a convex set in a real normed vector space `E`, let `f : E → G` be a function differentiable within `s` in a neighborhood of `x : E` with derivative `f'`. Suppose that `f'` is continuous within `s` at `x`. Then for any number `K : ℝ≥0` larger than `∥f' x∥₊`, `f` is `K`-Lipschitz on some neighborhood of `x` within `s`. See also `convex.exists_nhds_within_lipschitz_on_with_of_has_fderiv_within_at` for a version that claims existence of `K` instead of an explicit estimate. -/ lemma exists_nhds_within_lipschitz_on_with_of_has_fderiv_within_at_of_nnnorm_lt (hs : convex ℝ s) {f : E → G} (hder : ∀ᶠ y in 𝓝[s] x, has_fderiv_within_at f (f' y) s y) (hcont : continuous_within_at f' s x) (K : ℝ≥0) (hK : ∥f' x∥₊ < K) : ∃ t ∈ 𝓝[s] x, lipschitz_on_with K f t := begin obtain ⟨ε, ε0, hε⟩ : ∃ ε > 0, ball x ε ∩ s ⊆ {y | has_fderiv_within_at f (f' y) s y ∧ ∥f' y∥₊ < K}, from mem_nhds_within_iff.1 (hder.and $ hcont.nnnorm.eventually (gt_mem_nhds hK)), rw inter_comm at hε, refine ⟨s ∩ ball x ε, inter_mem_nhds_within _ (ball_mem_nhds _ ε0), _⟩, exact (hs.inter (convex_ball _ _)).lipschitz_on_with_of_nnnorm_has_fderiv_within_le (λ y hy, (hε hy).1.mono (inter_subset_left _ _)) (λ y hy, (hε hy).2.le) end /-- Let `s` be a convex set in a real normed vector space `E`, let `f : E → G` be a function differentiable within `s` in a neighborhood of `x : E` with derivative `f'`. Suppose that `f'` is continuous within `s` at `x`. Then for any number `K : ℝ≥0` larger than `∥f' x∥₊`, `f` is Lipschitz on some neighborhood of `x` within `s`. See also `convex.exists_nhds_within_lipschitz_on_with_of_has_fderiv_within_at_of_nnnorm_lt` for a version with an explicit estimate on the Lipschitz constant. -/ lemma exists_nhds_within_lipschitz_on_with_of_has_fderiv_within_at (hs : convex ℝ s) {f : E → G} (hder : ∀ᶠ y in 𝓝[s] x, has_fderiv_within_at f (f' y) s y) (hcont : continuous_within_at f' s x) : ∃ K (t ∈ 𝓝[s] x), lipschitz_on_with K f t := (exists_gt _).imp $ hs.exists_nhds_within_lipschitz_on_with_of_has_fderiv_within_at_of_nnnorm_lt hder hcont /-- The mean value theorem on a convex set: if the derivative of a function within this set is bounded by `C`, then the function is `C`-Lipschitz. Version with `fderiv_within`. -/ theorem norm_image_sub_le_of_norm_fderiv_within_le (hf : differentiable_on 𝕜 f s) (bound : ∀x∈s, ∥fderiv_within 𝕜 f s x∥ ≤ C) (hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x∥ ≤ C * ∥y - x∥ := hs.norm_image_sub_le_of_norm_has_fderiv_within_le (λ x hx, (hf x hx).has_fderiv_within_at) bound xs ys /-- The mean value theorem on a convex set: if the derivative of a function is bounded by `C` on `s`, then the function is `C`-Lipschitz on `s`. Version with `fderiv_within` and `lipschitz_on_with`. -/ theorem lipschitz_on_with_of_nnnorm_fderiv_within_le {C : ℝ≥0} (hf : differentiable_on 𝕜 f s) (bound : ∀ x ∈ s, ∥fderiv_within 𝕜 f s x∥₊ ≤ C) (hs : convex ℝ s) : lipschitz_on_with C f s:= hs.lipschitz_on_with_of_nnnorm_has_fderiv_within_le (λ x hx, (hf x hx).has_fderiv_within_at) bound /-- The mean value theorem on a convex set: if the derivative of a function is bounded by `C`, then the function is `C`-Lipschitz. Version with `fderiv`. -/ theorem norm_image_sub_le_of_norm_fderiv_le (hf : ∀ x ∈ s, differentiable_at 𝕜 f x) (bound : ∀x∈s, ∥fderiv 𝕜 f x∥ ≤ C) (hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x∥ ≤ C * ∥y - x∥ := hs.norm_image_sub_le_of_norm_has_fderiv_within_le (λ x hx, (hf x hx).has_fderiv_at.has_fderiv_within_at) bound xs ys /-- The mean value theorem on a convex set: if the derivative of a function is bounded by `C` on `s`, then the function is `C`-Lipschitz on `s`. Version with `fderiv` and `lipschitz_on_with`. -/ theorem lipschitz_on_with_of_nnnorm_fderiv_le {C : ℝ≥0} (hf : ∀ x ∈ s, differentiable_at 𝕜 f x) (bound : ∀x∈s, ∥fderiv 𝕜 f x∥₊ ≤ C) (hs : convex ℝ s) : lipschitz_on_with C f s := hs.lipschitz_on_with_of_nnnorm_has_fderiv_within_le (λ x hx, (hf x hx).has_fderiv_at.has_fderiv_within_at) bound /-- Variant of the mean value inequality on a convex set, using a bound on the difference between the derivative and a fixed linear map, rather than a bound on the derivative itself. Version with `has_fderiv_within`. -/ theorem norm_image_sub_le_of_norm_has_fderiv_within_le' (hf : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (bound : ∀x∈s, ∥f' x - φ∥ ≤ C) (hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x - φ (y - x)∥ ≤ C * ∥y - x∥ := begin /- We subtract `φ` to define a new function `g` for which `g' = 0`, for which the previous theorem applies, `convex.norm_image_sub_le_of_norm_has_fderiv_within_le`. Then, we just need to glue together the pieces, expressing back `f` in terms of `g`. -/ let g := λy, f y - φ y, have hg : ∀ x ∈ s, has_fderiv_within_at g (f' x - φ) s x := λ x xs, (hf x xs).sub φ.has_fderiv_within_at, calc ∥f y - f x - φ (y - x)∥ = ∥f y - f x - (φ y - φ x)∥ : by simp ... = ∥(f y - φ y) - (f x - φ x)∥ : by abel ... = ∥g y - g x∥ : by simp ... ≤ C * ∥y - x∥ : convex.norm_image_sub_le_of_norm_has_fderiv_within_le hg bound hs xs ys, end /-- Variant of the mean value inequality on a convex set. Version with `fderiv_within`. -/ theorem norm_image_sub_le_of_norm_fderiv_within_le' (hf : differentiable_on 𝕜 f s) (bound : ∀x∈s, ∥fderiv_within 𝕜 f s x - φ∥ ≤ C) (hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x - φ (y - x)∥ ≤ C * ∥y - x∥ := hs.norm_image_sub_le_of_norm_has_fderiv_within_le' (λ x hx, (hf x hx).has_fderiv_within_at) bound xs ys /-- Variant of the mean value inequality on a convex set. Version with `fderiv`. -/ theorem norm_image_sub_le_of_norm_fderiv_le' (hf : ∀ x ∈ s, differentiable_at 𝕜 f x) (bound : ∀x∈s, ∥fderiv 𝕜 f x - φ∥ ≤ C) (hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x - φ (y - x)∥ ≤ C * ∥y - x∥ := hs.norm_image_sub_le_of_norm_has_fderiv_within_le' (λ x hx, (hf x hx).has_fderiv_at.has_fderiv_within_at) bound xs ys /-- If a function has zero Fréchet derivative at every point of a convex set, then it is a constant on this set. -/ theorem is_const_of_fderiv_within_eq_zero (hs : convex ℝ s) (hf : differentiable_on 𝕜 f s) (hf' : ∀ x ∈ s, fderiv_within 𝕜 f s x = 0) (hx : x ∈ s) (hy : y ∈ s) : f x = f y := have bound : ∀ x ∈ s, ∥fderiv_within 𝕜 f s x∥ ≤ 0, from λ x hx, by simp only [hf' x hx, norm_zero], by simpa only [(dist_eq_norm _ _).symm, zero_mul, dist_le_zero, eq_comm] using hs.norm_image_sub_le_of_norm_fderiv_within_le hf bound hx hy theorem _root_.is_const_of_fderiv_eq_zero (hf : differentiable 𝕜 f) (hf' : ∀ x, fderiv 𝕜 f x = 0) (x y : E) : f x = f y := convex_univ.is_const_of_fderiv_within_eq_zero hf.differentiable_on (λ x _, by rw fderiv_within_univ; exact hf' x) trivial trivial end convex namespace convex variables {f f' : 𝕜 → G} {s : set 𝕜} {x y : 𝕜} /-- The mean value theorem on a convex set in dimension 1: if the derivative of a function is bounded by `C`, then the function is `C`-Lipschitz. Version with `has_deriv_within`. -/ theorem norm_image_sub_le_of_norm_has_deriv_within_le {C : ℝ} (hf : ∀ x ∈ s, has_deriv_within_at f (f' x) s x) (bound : ∀x∈s, ∥f' x∥ ≤ C) (hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x∥ ≤ C * ∥y - x∥ := convex.norm_image_sub_le_of_norm_has_fderiv_within_le (λ x hx, (hf x hx).has_fderiv_within_at) (λ x hx, le_trans (by simp) (bound x hx)) hs xs ys /-- The mean value theorem on a convex set in dimension 1: if the derivative of a function is bounded by `C` on `s`, then the function is `C`-Lipschitz on `s`. Version with `has_deriv_within` and `lipschitz_on_with`. -/ theorem lipschitz_on_with_of_nnnorm_has_deriv_within_le {C : ℝ≥0} (hs : convex ℝ s) (hf : ∀ x ∈ s, has_deriv_within_at f (f' x) s x) (bound : ∀x∈s, ∥f' x∥₊ ≤ C) : lipschitz_on_with C f s := convex.lipschitz_on_with_of_nnnorm_has_fderiv_within_le (λ x hx, (hf x hx).has_fderiv_within_at) (λ x hx, le_trans (by simp) (bound x hx)) hs /-- The mean value theorem on a convex set in dimension 1: if the derivative of a function within this set is bounded by `C`, then the function is `C`-Lipschitz. Version with `deriv_within` -/ theorem norm_image_sub_le_of_norm_deriv_within_le {C : ℝ} (hf : differentiable_on 𝕜 f s) (bound : ∀x∈s, ∥deriv_within f s x∥ ≤ C) (hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x∥ ≤ C * ∥y - x∥ := hs.norm_image_sub_le_of_norm_has_deriv_within_le (λ x hx, (hf x hx).has_deriv_within_at) bound xs ys /-- The mean value theorem on a convex set in dimension 1: if the derivative of a function is bounded by `C` on `s`, then the function is `C`-Lipschitz on `s`. Version with `deriv_within` and `lipschitz_on_with`. -/ theorem lipschitz_on_with_of_nnnorm_deriv_within_le {C : ℝ≥0} (hs : convex ℝ s) (hf : differentiable_on 𝕜 f s) (bound : ∀x∈s, ∥deriv_within f s x∥₊ ≤ C) : lipschitz_on_with C f s := hs.lipschitz_on_with_of_nnnorm_has_deriv_within_le (λ x hx, (hf x hx).has_deriv_within_at) bound /-- The mean value theorem on a convex set in dimension 1: if the derivative of a function is bounded by `C`, then the function is `C`-Lipschitz. Version with `deriv`. -/ theorem norm_image_sub_le_of_norm_deriv_le {C : ℝ} (hf : ∀ x ∈ s, differentiable_at 𝕜 f x) (bound : ∀x∈s, ∥deriv f x∥ ≤ C) (hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x∥ ≤ C * ∥y - x∥ := hs.norm_image_sub_le_of_norm_has_deriv_within_le (λ x hx, (hf x hx).has_deriv_at.has_deriv_within_at) bound xs ys /-- The mean value theorem on a convex set in dimension 1: if the derivative of a function is bounded by `C` on `s`, then the function is `C`-Lipschitz on `s`. Version with `deriv` and `lipschitz_on_with`. -/ theorem lipschitz_on_with_of_nnnorm_deriv_le {C : ℝ≥0} (hf : ∀ x ∈ s, differentiable_at 𝕜 f x) (bound : ∀x∈s, ∥deriv f x∥₊ ≤ C) (hs : convex ℝ s) : lipschitz_on_with C f s := hs.lipschitz_on_with_of_nnnorm_has_deriv_within_le (λ x hx, (hf x hx).has_deriv_at.has_deriv_within_at) bound /-- The mean value theorem set in dimension 1: if the derivative of a function is bounded by `C`, then the function is `C`-Lipschitz. Version with `deriv` and `lipschitz_with`. -/ theorem _root_.lipschitz_with_of_nnnorm_deriv_le {C : ℝ≥0} (hf : differentiable 𝕜 f) (bound : ∀ x, ∥deriv f x∥₊ ≤ C) : lipschitz_with C f := lipschitz_on_univ.1 $ convex_univ.lipschitz_on_with_of_nnnorm_deriv_le (λ x hx, hf x) (λ x hx, bound x) /-- If `f : 𝕜 → G`, `𝕜 = R` or `𝕜 = ℂ`, is differentiable everywhere and its derivative equal zero, then it is a constant function. -/ theorem _root_.is_const_of_deriv_eq_zero (hf : differentiable 𝕜 f) (hf' : ∀ x, deriv f x = 0) (x y : 𝕜) : f x = f y := is_const_of_fderiv_eq_zero hf (λ z, by { ext, simp [← deriv_fderiv, hf'] }) _ _ end convex end /-! ### Functions `[a, b] → ℝ`. -/ section interval -- Declare all variables here to make sure they come in a correct order variables (f f' : ℝ → ℝ) {a b : ℝ} (hab : a < b) (hfc : continuous_on f (Icc a b)) (hff' : ∀ x ∈ Ioo a b, has_deriv_at f (f' x) x) (hfd : differentiable_on ℝ f (Ioo a b)) (g g' : ℝ → ℝ) (hgc : continuous_on g (Icc a b)) (hgg' : ∀ x ∈ Ioo a b, has_deriv_at g (g' x) x) (hgd : differentiable_on ℝ g (Ioo a b)) include hab hfc hff' hgc hgg' /-- Cauchy's **Mean Value Theorem**, `has_deriv_at` version. -/ lemma exists_ratio_has_deriv_at_eq_ratio_slope : ∃ c ∈ Ioo a b, (g b - g a) * f' c = (f b - f a) * g' c := begin let h := λ x, (g b - g a) * f x - (f b - f a) * g x, have hI : h a = h b, { simp only [h], ring }, let h' := λ x, (g b - g a) * f' x - (f b - f a) * g' x, have hhh' : ∀ x ∈ Ioo a b, has_deriv_at h (h' x) x, from λ x hx, ((hff' x hx).const_mul (g b - g a)).sub ((hgg' x hx).const_mul (f b - f a)), have hhc : continuous_on h (Icc a b), from (continuous_on_const.mul hfc).sub (continuous_on_const.mul hgc), rcases exists_has_deriv_at_eq_zero h h' hab hhc hI hhh' with ⟨c, cmem, hc⟩, exact ⟨c, cmem, sub_eq_zero.1 hc⟩ end omit hfc hgc /-- Cauchy's **Mean Value Theorem**, extended `has_deriv_at` version. -/ lemma exists_ratio_has_deriv_at_eq_ratio_slope' {lfa lga lfb lgb : ℝ} (hff' : ∀ x ∈ Ioo a b, has_deriv_at f (f' x) x) (hgg' : ∀ x ∈ Ioo a b, has_deriv_at g (g' x) x) (hfa : tendsto f (𝓝[>] a) (𝓝 lfa)) (hga : tendsto g (𝓝[>] a) (𝓝 lga)) (hfb : tendsto f (𝓝[<] b) (𝓝 lfb)) (hgb : tendsto g (𝓝[<] b) (𝓝 lgb)) : ∃ c ∈ Ioo a b, (lgb - lga) * (f' c) = (lfb - lfa) * (g' c) := begin let h := λ x, (lgb - lga) * f x - (lfb - lfa) * g x, have hha : tendsto h (𝓝[>] a) (𝓝 $ lgb * lfa - lfb * lga), { have : tendsto h (𝓝[>] a)(𝓝 $ (lgb - lga) * lfa - (lfb - lfa) * lga) := (tendsto_const_nhds.mul hfa).sub (tendsto_const_nhds.mul hga), convert this using 2, ring }, have hhb : tendsto h (𝓝[<] b) (𝓝 $ lgb * lfa - lfb * lga), { have : tendsto h (𝓝[<] b)(𝓝 $ (lgb - lga) * lfb - (lfb - lfa) * lgb) := (tendsto_const_nhds.mul hfb).sub (tendsto_const_nhds.mul hgb), convert this using 2, ring }, let h' := λ x, (lgb - lga) * f' x - (lfb - lfa) * g' x, have hhh' : ∀ x ∈ Ioo a b, has_deriv_at h (h' x) x, { intros x hx, exact ((hff' x hx).const_mul _ ).sub (((hgg' x hx)).const_mul _) }, rcases exists_has_deriv_at_eq_zero' hab hha hhb hhh' with ⟨c, cmem, hc⟩, exact ⟨c, cmem, sub_eq_zero.1 hc⟩ end include hfc omit hgg' /-- Lagrange's Mean Value Theorem, `has_deriv_at` version -/ lemma exists_has_deriv_at_eq_slope : ∃ c ∈ Ioo a b, f' c = (f b - f a) / (b - a) := begin rcases exists_ratio_has_deriv_at_eq_ratio_slope f f' hab hfc hff' id 1 continuous_id.continuous_on (λ x hx, has_deriv_at_id x) with ⟨c, cmem, hc⟩, use [c, cmem], simp only [_root_.id, pi.one_apply, mul_one] at hc, rw [← hc, mul_div_cancel_left], exact ne_of_gt (sub_pos.2 hab) end omit hff' /-- Cauchy's Mean Value Theorem, `deriv` version. -/ lemma exists_ratio_deriv_eq_ratio_slope : ∃ c ∈ Ioo a b, (g b - g a) * (deriv f c) = (f b - f a) * (deriv g c) := exists_ratio_has_deriv_at_eq_ratio_slope f (deriv f) hab hfc (λ x hx, ((hfd x hx).differentiable_at $ is_open.mem_nhds is_open_Ioo hx).has_deriv_at) g (deriv g) hgc $ λ x hx, ((hgd x hx).differentiable_at $ is_open.mem_nhds is_open_Ioo hx).has_deriv_at omit hfc /-- Cauchy's Mean Value Theorem, extended `deriv` version. -/ lemma exists_ratio_deriv_eq_ratio_slope' {lfa lga lfb lgb : ℝ} (hdf : differentiable_on ℝ f $ Ioo a b) (hdg : differentiable_on ℝ g $ Ioo a b) (hfa : tendsto f (𝓝[>] a) (𝓝 lfa)) (hga : tendsto g (𝓝[>] a) (𝓝 lga)) (hfb : tendsto f (𝓝[<] b) (𝓝 lfb)) (hgb : tendsto g (𝓝[<] b) (𝓝 lgb)) : ∃ c ∈ Ioo a b, (lgb - lga) * (deriv f c) = (lfb - lfa) * (deriv g c) := exists_ratio_has_deriv_at_eq_ratio_slope' _ _ hab _ _ (λ x hx, ((hdf x hx).differentiable_at $ Ioo_mem_nhds hx.1 hx.2).has_deriv_at) (λ x hx, ((hdg x hx).differentiable_at $ Ioo_mem_nhds hx.1 hx.2).has_deriv_at) hfa hga hfb hgb /-- Lagrange's **Mean Value Theorem**, `deriv` version. -/ lemma exists_deriv_eq_slope : ∃ c ∈ Ioo a b, deriv f c = (f b - f a) / (b - a) := exists_has_deriv_at_eq_slope f (deriv f) hab hfc (λ x hx, ((hfd x hx).differentiable_at $ is_open.mem_nhds is_open_Ioo hx).has_deriv_at) end interval /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `C < f'`, then `f` grows faster than `C * x` on `D`, i.e., `C * (y - x) < f y - f x` whenever `x, y ∈ D`, `x < y`. -/ theorem convex.mul_sub_lt_image_sub_of_lt_deriv {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) {C} (hf'_gt : ∀ x ∈ interior D, C < deriv f x) : ∀ x y ∈ D, x < y → C * (y - x) < f y - f x := begin assume x hx y hy hxy, have hxyD : Icc x y ⊆ D, from hD.ord_connected.out hx hy, have hxyD' : Ioo x y ⊆ interior D, from subset_sUnion_of_mem ⟨is_open_Ioo, subset.trans Ioo_subset_Icc_self hxyD⟩, obtain ⟨a, a_mem, ha⟩ : ∃ a ∈ Ioo x y, deriv f a = (f y - f x) / (y - x), from exists_deriv_eq_slope f hxy (hf.mono hxyD) (hf'.mono hxyD'), have : C < (f y - f x) / (y - x), by { rw [← ha], exact hf'_gt _ (hxyD' a_mem) }, exact (lt_div_iff (sub_pos.2 hxy)).1 this end /-- Let `f : ℝ → ℝ` be a differentiable function. If `C < f'`, then `f` grows faster than `C * x`, i.e., `C * (y - x) < f y - f x` whenever `x < y`. -/ theorem mul_sub_lt_image_sub_of_lt_deriv {f : ℝ → ℝ} (hf : differentiable ℝ f) {C} (hf'_gt : ∀ x, C < deriv f x) ⦃x y⦄ (hxy : x < y) : C * (y - x) < f y - f x := convex_univ.mul_sub_lt_image_sub_of_lt_deriv hf.continuous.continuous_on hf.differentiable_on (λ x _, hf'_gt x) x trivial y trivial hxy /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `C ≤ f'`, then `f` grows at least as fast as `C * x` on `D`, i.e., `C * (y - x) ≤ f y - f x` whenever `x, y ∈ D`, `x ≤ y`. -/ theorem convex.mul_sub_le_image_sub_of_le_deriv {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) {C} (hf'_ge : ∀ x ∈ interior D, C ≤ deriv f x) : ∀ x y ∈ D, x ≤ y → C * (y - x) ≤ f y - f x := begin assume x hx y hy hxy, cases eq_or_lt_of_le hxy with hxy' hxy', by rw [hxy', sub_self, sub_self, mul_zero], have hxyD : Icc x y ⊆ D, from hD.ord_connected.out hx hy, have hxyD' : Ioo x y ⊆ interior D, from subset_sUnion_of_mem ⟨is_open_Ioo, subset.trans Ioo_subset_Icc_self hxyD⟩, obtain ⟨a, a_mem, ha⟩ : ∃ a ∈ Ioo x y, deriv f a = (f y - f x) / (y - x), from exists_deriv_eq_slope f hxy' (hf.mono hxyD) (hf'.mono hxyD'), have : C ≤ (f y - f x) / (y - x), by { rw [← ha], exact hf'_ge _ (hxyD' a_mem) }, exact (le_div_iff (sub_pos.2 hxy')).1 this end /-- Let `f : ℝ → ℝ` be a differentiable function. If `C ≤ f'`, then `f` grows at least as fast as `C * x`, i.e., `C * (y - x) ≤ f y - f x` whenever `x ≤ y`. -/ theorem mul_sub_le_image_sub_of_le_deriv {f : ℝ → ℝ} (hf : differentiable ℝ f) {C} (hf'_ge : ∀ x, C ≤ deriv f x) ⦃x y⦄ (hxy : x ≤ y) : C * (y - x) ≤ f y - f x := convex_univ.mul_sub_le_image_sub_of_le_deriv hf.continuous.continuous_on hf.differentiable_on (λ x _, hf'_ge x) x trivial y trivial hxy /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `f' < C`, then `f` grows slower than `C * x` on `D`, i.e., `f y - f x < C * (y - x)` whenever `x, y ∈ D`, `x < y`. -/ theorem convex.image_sub_lt_mul_sub_of_deriv_lt {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) {C} (lt_hf' : ∀ x ∈ interior D, deriv f x < C) : ∀ x y ∈ D, x < y → f y - f x < C * (y - x) := begin assume x hx y hy hxy, have hf'_gt : ∀ x ∈ interior D, -C < deriv (λ y, -f y) x, { assume x hx, rw [deriv.neg, neg_lt_neg_iff], exact lt_hf' x hx }, simpa [-neg_lt_neg_iff] using neg_lt_neg (hD.mul_sub_lt_image_sub_of_lt_deriv hf.neg hf'.neg hf'_gt x hx y hy hxy) end /-- Let `f : ℝ → ℝ` be a differentiable function. If `f' < C`, then `f` grows slower than `C * x` on `D`, i.e., `f y - f x < C * (y - x)` whenever `x < y`. -/ theorem image_sub_lt_mul_sub_of_deriv_lt {f : ℝ → ℝ} (hf : differentiable ℝ f) {C} (lt_hf' : ∀ x, deriv f x < C) ⦃x y⦄ (hxy : x < y) : f y - f x < C * (y - x) := convex_univ.image_sub_lt_mul_sub_of_deriv_lt hf.continuous.continuous_on hf.differentiable_on (λ x _, lt_hf' x) x trivial y trivial hxy /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `f' ≤ C`, then `f` grows at most as fast as `C * x` on `D`, i.e., `f y - f x ≤ C * (y - x)` whenever `x, y ∈ D`, `x ≤ y`. -/ theorem convex.image_sub_le_mul_sub_of_deriv_le {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) {C} (le_hf' : ∀ x ∈ interior D, deriv f x ≤ C) : ∀ x y ∈ D, x ≤ y → f y - f x ≤ C * (y - x) := begin assume x hx y hy hxy, have hf'_ge : ∀ x ∈ interior D, -C ≤ deriv (λ y, -f y) x, { assume x hx, rw [deriv.neg, neg_le_neg_iff], exact le_hf' x hx }, simpa [-neg_le_neg_iff] using neg_le_neg (hD.mul_sub_le_image_sub_of_le_deriv hf.neg hf'.neg hf'_ge x hx y hy hxy) end /-- Let `f : ℝ → ℝ` be a differentiable function. If `f' ≤ C`, then `f` grows at most as fast as `C * x`, i.e., `f y - f x ≤ C * (y - x)` whenever `x ≤ y`. -/ theorem image_sub_le_mul_sub_of_deriv_le {f : ℝ → ℝ} (hf : differentiable ℝ f) {C} (le_hf' : ∀ x, deriv f x ≤ C) ⦃x y⦄ (hxy : x ≤ y) : f y - f x ≤ C * (y - x) := convex_univ.image_sub_le_mul_sub_of_deriv_le hf.continuous.continuous_on hf.differentiable_on (λ x _, le_hf' x) x trivial y trivial hxy /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `f'` is positive, then `f` is a strictly monotone function on `D`. Note that we don't require differentiability explicitly as it already implied by the derivative being strictly positive. -/ theorem convex.strict_mono_on_of_deriv_pos {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : ∀ x ∈ interior D, 0 < deriv f x) : strict_mono_on f D := begin rintro x hx y hy, simpa only [zero_mul, sub_pos] using hD.mul_sub_lt_image_sub_of_lt_deriv hf _ hf' x hx y hy, exact λ z hz, (differentiable_at_of_deriv_ne_zero (hf' z hz).ne').differentiable_within_at, end /-- Let `f : ℝ → ℝ` be a differentiable function. If `f'` is positive, then `f` is a strictly monotone function. Note that we don't require differentiability explicitly as it already implied by the derivative being strictly positive. -/ theorem strict_mono_of_deriv_pos {f : ℝ → ℝ} (hf' : ∀ x, 0 < deriv f x) : strict_mono f := strict_mono_on_univ.1 $ convex_univ.strict_mono_on_of_deriv_pos (λ z _, (differentiable_at_of_deriv_ne_zero (hf' z).ne').differentiable_within_at .continuous_within_at) (λ x _, hf' x) /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `f'` is nonnegative, then `f` is a monotone function on `D`. -/ theorem convex.monotone_on_of_deriv_nonneg {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'_nonneg : ∀ x ∈ interior D, 0 ≤ deriv f x) : monotone_on f D := λ x hx y hy hxy, by simpa only [zero_mul, sub_nonneg] using hD.mul_sub_le_image_sub_of_le_deriv hf hf' hf'_nonneg x hx y hy hxy /-- Let `f : ℝ → ℝ` be a differentiable function. If `f'` is nonnegative, then `f` is a monotone function. -/ theorem monotone_of_deriv_nonneg {f : ℝ → ℝ} (hf : differentiable ℝ f) (hf' : ∀ x, 0 ≤ deriv f x) : monotone f := monotone_on_univ.1 $ convex_univ.monotone_on_of_deriv_nonneg hf.continuous.continuous_on hf.differentiable_on (λ x _, hf' x) /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `f'` is negative, then `f` is a strictly antitone function on `D`. -/ theorem convex.strict_anti_on_of_deriv_neg {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : ∀ x ∈ interior D, deriv f x < 0) : strict_anti_on f D := λ x hx y, by simpa only [zero_mul, sub_lt_zero] using hD.image_sub_lt_mul_sub_of_deriv_lt hf (λ z hz, (differentiable_at_of_deriv_ne_zero (hf' z hz).ne).differentiable_within_at) hf' x hx y /-- Let `f : ℝ → ℝ` be a differentiable function. If `f'` is negative, then `f` is a strictly antitone function. Note that we don't require differentiability explicitly as it already implied by the derivative being strictly negative. -/ theorem strict_anti_of_deriv_neg {f : ℝ → ℝ} (hf' : ∀ x, deriv f x < 0) : strict_anti f := strict_anti_on_univ.1 $ convex_univ.strict_anti_on_of_deriv_neg (λ z _, (differentiable_at_of_deriv_ne_zero (hf' z).ne).differentiable_within_at .continuous_within_at) (λ x _, hf' x) /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `f'` is nonpositive, then `f` is an antitone function on `D`. -/ theorem convex.antitone_on_of_deriv_nonpos {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'_nonpos : ∀ x ∈ interior D, deriv f x ≤ 0) : antitone_on f D := λ x hx y hy hxy, by simpa only [zero_mul, sub_nonpos] using hD.image_sub_le_mul_sub_of_deriv_le hf hf' hf'_nonpos x hx y hy hxy /-- Let `f : ℝ → ℝ` be a differentiable function. If `f'` is nonpositive, then `f` is an antitone function. -/ theorem antitone_of_deriv_nonpos {f : ℝ → ℝ} (hf : differentiable ℝ f) (hf' : ∀ x, deriv f x ≤ 0) : antitone f := antitone_on_univ.1 $ convex_univ.antitone_on_of_deriv_nonpos hf.continuous.continuous_on hf.differentiable_on (λ x _, hf' x) /-- If a function `f` is continuous on a convex set `D ⊆ ℝ`, is differentiable on its interior, and `f'` is monotone on the interior, then `f` is convex on `D`. -/ theorem monotone_on.convex_on_of_deriv {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'_mono : monotone_on (deriv f) (interior D)) : convex_on ℝ D f := convex_on_of_slope_mono_adjacent hD begin intros x y z hx hz hxy hyz, -- First we prove some trivial inclusions have hxzD : Icc x z ⊆ D, from hD.ord_connected.out hx hz, have hxyD : Icc x y ⊆ D, from subset.trans (Icc_subset_Icc_right $ le_of_lt hyz) hxzD, have hxyD' : Ioo x y ⊆ interior D, from subset_sUnion_of_mem ⟨is_open_Ioo, subset.trans Ioo_subset_Icc_self hxyD⟩, have hyzD : Icc y z ⊆ D, from subset.trans (Icc_subset_Icc_left $ le_of_lt hxy) hxzD, have hyzD' : Ioo y z ⊆ interior D, from subset_sUnion_of_mem ⟨is_open_Ioo, subset.trans Ioo_subset_Icc_self hyzD⟩, -- Then we apply MVT to both `[x, y]` and `[y, z]` obtain ⟨a, ⟨hxa, hay⟩, ha⟩ : ∃ a ∈ Ioo x y, deriv f a = (f y - f x) / (y - x), from exists_deriv_eq_slope f hxy (hf.mono hxyD) (hf'.mono hxyD'), obtain ⟨b, ⟨hyb, hbz⟩, hb⟩ : ∃ b ∈ Ioo y z, deriv f b = (f z - f y) / (z - y), from exists_deriv_eq_slope f hyz (hf.mono hyzD) (hf'.mono hyzD'), rw [← ha, ← hb], exact hf'_mono (hxyD' ⟨hxa, hay⟩) (hyzD' ⟨hyb, hbz⟩) (hay.trans hyb).le end /-- If a function `f` is continuous on a convex set `D ⊆ ℝ`, is differentiable on its interior, and `f'` is antitone on the interior, then `f` is concave on `D`. -/ theorem antitone_on.concave_on_of_deriv {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (h_anti : antitone_on (deriv f) (interior D)) : concave_on ℝ D f := begin have : monotone_on (deriv (-f)) (interior D), { intros x hx y hy hxy, convert neg_le_neg (h_anti hx hy hxy); convert deriv.neg }, exact neg_convex_on_iff.mp (this.convex_on_of_deriv hD hf.neg hf'.neg), end lemma strict_mono_on.exists_slope_lt_deriv_aux {x y : ℝ} {f : ℝ → ℝ} (hf : continuous_on f (Icc x y)) (hxy : x < y) (hf'_mono : strict_mono_on (deriv f) (Ioo x y)) (h : ∀ w ∈ Ioo x y, deriv f w ≠ 0) : ∃ a ∈ Ioo x y, (f y - f x) / (y - x) < deriv f a := begin have A : differentiable_on ℝ f (Ioo x y), from λ w wmem, (differentiable_at_of_deriv_ne_zero (h w wmem)).differentiable_within_at, obtain ⟨a, ⟨hxa, hay⟩, ha⟩ : ∃ a ∈ Ioo x y, deriv f a = (f y - f x) / (y - x), from exists_deriv_eq_slope f hxy hf A, rcases nonempty_Ioo.2 hay with ⟨b, ⟨hab, hby⟩⟩, refine ⟨b, ⟨hxa.trans hab, hby⟩, _⟩, rw ← ha, exact hf'_mono ⟨hxa, hay⟩ ⟨hxa.trans hab, hby⟩ hab end lemma strict_mono_on.exists_slope_lt_deriv {x y : ℝ} {f : ℝ → ℝ} (hf : continuous_on f (Icc x y)) (hxy : x < y) (hf'_mono : strict_mono_on (deriv f) (Ioo x y)) : ∃ a ∈ Ioo x y, (f y - f x) / (y - x) < deriv f a := begin by_cases h : ∀ w ∈ Ioo x y, deriv f w ≠ 0, { apply strict_mono_on.exists_slope_lt_deriv_aux hf hxy hf'_mono h }, { push_neg at h, rcases h with ⟨w, ⟨hxw, hwy⟩, hw⟩, obtain ⟨a, ⟨hxa, haw⟩, ha⟩ : ∃ (a : ℝ) (H : a ∈ Ioo x w), (f w - f x) / (w - x) < deriv f a, { apply strict_mono_on.exists_slope_lt_deriv_aux _ hxw _ _, { exact hf.mono (Icc_subset_Icc le_rfl hwy.le) }, { exact hf'_mono.mono (Ioo_subset_Ioo le_rfl hwy.le) }, { assume z hz, rw ← hw, apply ne_of_lt, exact hf'_mono ⟨hz.1, hz.2.trans hwy⟩ ⟨hxw, hwy⟩ hz.2 } }, obtain ⟨b, ⟨hwb, hby⟩, hb⟩ : ∃ (b : ℝ) (H : b ∈ Ioo w y), (f y - f w) / (y - w) < deriv f b, { apply strict_mono_on.exists_slope_lt_deriv_aux _ hwy _ _, { refine hf.mono (Icc_subset_Icc hxw.le le_rfl), }, { exact hf'_mono.mono (Ioo_subset_Ioo hxw.le le_rfl) }, { assume z hz, rw ← hw, apply ne_of_gt, exact hf'_mono ⟨hxw, hwy⟩ ⟨hxw.trans hz.1, hz.2⟩ hz.1, } }, refine ⟨b, ⟨hxw.trans hwb, hby⟩, _⟩, simp only [div_lt_iff, hxy, hxw, hwy, sub_pos] at ⊢ ha hb, have : deriv f a * (w - x) < deriv f b * (w - x), { apply mul_lt_mul _ le_rfl (sub_pos.2 hxw) _, { exact hf'_mono ⟨hxa, haw.trans hwy⟩ ⟨hxw.trans hwb, hby⟩ (haw.trans hwb) }, { rw ← hw, exact (hf'_mono ⟨hxw, hwy⟩ ⟨hxw.trans hwb, hby⟩ hwb).le } }, linarith } end lemma strict_mono_on.exists_deriv_lt_slope_aux {x y : ℝ} {f : ℝ → ℝ} (hf : continuous_on f (Icc x y)) (hxy : x < y) (hf'_mono : strict_mono_on (deriv f) (Ioo x y)) (h : ∀ w ∈ Ioo x y, deriv f w ≠ 0) : ∃ a ∈ Ioo x y, deriv f a < (f y - f x) / (y - x) := begin have A : differentiable_on ℝ f (Ioo x y), from λ w wmem, (differentiable_at_of_deriv_ne_zero (h w wmem)).differentiable_within_at, obtain ⟨a, ⟨hxa, hay⟩, ha⟩ : ∃ a ∈ Ioo x y, deriv f a = (f y - f x) / (y - x), from exists_deriv_eq_slope f hxy hf A, rcases nonempty_Ioo.2 hxa with ⟨b, ⟨hxb, hba⟩⟩, refine ⟨b, ⟨hxb, hba.trans hay⟩, _⟩, rw ← ha, exact hf'_mono ⟨hxb, hba.trans hay⟩ ⟨hxa, hay⟩ hba end lemma strict_mono_on.exists_deriv_lt_slope {x y : ℝ} {f : ℝ → ℝ} (hf : continuous_on f (Icc x y)) (hxy : x < y) (hf'_mono : strict_mono_on (deriv f) (Ioo x y)) : ∃ a ∈ Ioo x y, deriv f a < (f y - f x) / (y - x) := begin by_cases h : ∀ w ∈ Ioo x y, deriv f w ≠ 0, { apply strict_mono_on.exists_deriv_lt_slope_aux hf hxy hf'_mono h }, { push_neg at h, rcases h with ⟨w, ⟨hxw, hwy⟩, hw⟩, obtain ⟨a, ⟨hxa, haw⟩, ha⟩ : ∃ (a : ℝ) (H : a ∈ Ioo x w), deriv f a < (f w - f x) / (w - x), { apply strict_mono_on.exists_deriv_lt_slope_aux _ hxw _ _, { exact hf.mono (Icc_subset_Icc le_rfl hwy.le) }, { exact hf'_mono.mono (Ioo_subset_Ioo le_rfl hwy.le) }, { assume z hz, rw ← hw, apply ne_of_lt, exact hf'_mono ⟨hz.1, hz.2.trans hwy⟩ ⟨hxw, hwy⟩ hz.2 } }, obtain ⟨b, ⟨hwb, hby⟩, hb⟩ : ∃ (b : ℝ) (H : b ∈ Ioo w y), deriv f b < (f y - f w) / (y - w), { apply strict_mono_on.exists_deriv_lt_slope_aux _ hwy _ _, { refine hf.mono (Icc_subset_Icc hxw.le le_rfl), }, { exact hf'_mono.mono (Ioo_subset_Ioo hxw.le le_rfl) }, { assume z hz, rw ← hw, apply ne_of_gt, exact hf'_mono ⟨hxw, hwy⟩ ⟨hxw.trans hz.1, hz.2⟩ hz.1, } }, refine ⟨a, ⟨hxa, haw.trans hwy⟩, _⟩, simp only [lt_div_iff, hxy, hxw, hwy, sub_pos] at ⊢ ha hb, have : deriv f a * (y - w) < deriv f b * (y - w), { apply mul_lt_mul _ le_rfl (sub_pos.2 hwy) _, { exact hf'_mono ⟨hxa, haw.trans hwy⟩ ⟨hxw.trans hwb, hby⟩ (haw.trans hwb) }, { rw ← hw, exact (hf'_mono ⟨hxw, hwy⟩ ⟨hxw.trans hwb, hby⟩ hwb).le } }, linarith } end /-- If a function `f` is continuous on a convex set `D ⊆ ℝ`, and `f'` is strictly monotone on the interior, then `f` is strictly convex on `D`. Note that we don't require differentiability, since it is guaranteed at all but at most one point by the strict monotonicity of `f'`. -/ lemma strict_mono_on.strict_convex_on_of_deriv {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : strict_mono_on (deriv f) (interior D)) : strict_convex_on ℝ D f := strict_convex_on_of_slope_strict_mono_adjacent hD begin intros x y z hx hz hxy hyz, -- First we prove some trivial inclusions have hxzD : Icc x z ⊆ D, from hD.ord_connected.out hx hz, have hxyD : Icc x y ⊆ D, from subset.trans (Icc_subset_Icc_right $ le_of_lt hyz) hxzD, have hxyD' : Ioo x y ⊆ interior D, from subset_sUnion_of_mem ⟨is_open_Ioo, subset.trans Ioo_subset_Icc_self hxyD⟩, have hyzD : Icc y z ⊆ D, from subset.trans (Icc_subset_Icc_left $ le_of_lt hxy) hxzD, have hyzD' : Ioo y z ⊆ interior D, from subset_sUnion_of_mem ⟨is_open_Ioo, subset.trans Ioo_subset_Icc_self hyzD⟩, -- Then we get points `a` and `b` in each interval `[x, y]` and `[y, z]` where the derivatives -- can be compared to the slopes between `x, y` and `y, z` respectively. obtain ⟨a, ⟨hxa, hay⟩, ha⟩ : ∃ a ∈ Ioo x y, (f y - f x) / (y - x) < deriv f a, from strict_mono_on.exists_slope_lt_deriv (hf.mono hxyD) hxy (hf'.mono hxyD'), obtain ⟨b, ⟨hyb, hbz⟩, hb⟩ : ∃ b ∈ Ioo y z, deriv f b < (f z - f y) / (z - y), from strict_mono_on.exists_deriv_lt_slope (hf.mono hyzD) hyz (hf'.mono hyzD'), apply ha.trans (lt_trans _ hb), exact hf' (hxyD' ⟨hxa, hay⟩) (hyzD' ⟨hyb, hbz⟩) (hay.trans hyb), end /-- If a function `f` is continuous on a convex set `D ⊆ ℝ` and `f'` is strictly antitone on the interior, then `f` is strictly concave on `D`. Note that we don't require differentiability, since it is guaranteed at all but at most one point by the strict antitonicity of `f'`. -/ lemma strict_anti_on.strict_concave_on_of_deriv {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (h_anti : strict_anti_on (deriv f) (interior D)) : strict_concave_on ℝ D f := begin have : strict_mono_on (deriv (-f)) (interior D), { intros x hx y hy hxy, convert neg_lt_neg (h_anti hx hy hxy); convert deriv.neg }, exact neg_strict_convex_on_iff.mp (this.strict_convex_on_of_deriv hD hf.neg), end /-- If a function `f` is differentiable and `f'` is monotone on `ℝ` then `f` is convex. -/ theorem monotone.convex_on_univ_of_deriv {f : ℝ → ℝ} (hf : differentiable ℝ f) (hf'_mono : monotone (deriv f)) : convex_on ℝ univ f := (hf'_mono.monotone_on _).convex_on_of_deriv convex_univ hf.continuous.continuous_on hf.differentiable_on /-- If a function `f` is differentiable and `f'` is antitone on `ℝ` then `f` is concave. -/ theorem antitone.concave_on_univ_of_deriv {f : ℝ → ℝ} (hf : differentiable ℝ f) (hf'_anti : antitone (deriv f)) : concave_on ℝ univ f := (hf'_anti.antitone_on _).concave_on_of_deriv convex_univ hf.continuous.continuous_on hf.differentiable_on /-- If a function `f` is continuous and `f'` is strictly monotone on `ℝ` then `f` is strictly convex. Note that we don't require differentiability, since it is guaranteed at all but at most one point by the strict monotonicity of `f'`. -/ lemma strict_mono.strict_convex_on_univ_of_deriv {f : ℝ → ℝ} (hf : continuous f) (hf'_mono : strict_mono (deriv f)) : strict_convex_on ℝ univ f := (hf'_mono.strict_mono_on _).strict_convex_on_of_deriv convex_univ hf.continuous_on /-- If a function `f` is continuous and `f'` is strictly antitone on `ℝ` then `f` is strictly concave. Note that we don't require differentiability, since it is guaranteed at all but at most one point by the strict antitonicity of `f'`. -/ lemma strict_anti.strict_concave_on_univ_of_deriv {f : ℝ → ℝ} (hf : continuous f) (hf'_anti : strict_anti (deriv f)) : strict_concave_on ℝ univ f := (hf'_anti.strict_anti_on _).strict_concave_on_of_deriv convex_univ hf.continuous_on /-- If a function `f` is continuous on a convex set `D ⊆ ℝ`, is twice differentiable on its interior, and `f''` is nonnegative on the interior, then `f` is convex on `D`. -/ theorem convex_on_of_deriv2_nonneg {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'' : differentiable_on ℝ (deriv f) (interior D)) (hf''_nonneg : ∀ x ∈ interior D, 0 ≤ (deriv^[2] f x)) : convex_on ℝ D f := (hD.interior.monotone_on_of_deriv_nonneg hf''.continuous_on (by rwa interior_interior) $ by rwa interior_interior).convex_on_of_deriv hD hf hf' /-- If a function `f` is continuous on a convex set `D ⊆ ℝ`, is twice differentiable on its interior, and `f''` is nonpositive on the interior, then `f` is concave on `D`. -/ theorem concave_on_of_deriv2_nonpos {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'' : differentiable_on ℝ (deriv f) (interior D)) (hf''_nonpos : ∀ x ∈ interior D, deriv^[2] f x ≤ 0) : concave_on ℝ D f := (hD.interior.antitone_on_of_deriv_nonpos hf''.continuous_on (by rwa interior_interior) $ by rwa interior_interior).concave_on_of_deriv hD hf hf' /-- If a function `f` is continuous on a convex set `D ⊆ ℝ` and `f''` is strictly positive on the interior, then `f` is strictly convex on `D`. Note that we don't require twice differentiability explicitly as it is already implied by the second derivative being strictly positive, except at at most one point. -/ lemma strict_convex_on_of_deriv2_pos {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf'' : ∀ x ∈ interior D, 0 < (deriv^[2] f) x) : strict_convex_on ℝ D f := (hD.interior.strict_mono_on_of_deriv_pos (λ z hz, (differentiable_at_of_deriv_ne_zero (hf'' z hz).ne').differentiable_within_at .continuous_within_at) $ by rwa interior_interior).strict_convex_on_of_deriv hD hf /-- If a function `f` is continuous on a convex set `D ⊆ ℝ` and `f''` is strictly negative on the interior, then `f` is strictly concave on `D`. Note that we don't require twice differentiability explicitly as it already implied by the second derivative being strictly negative, except at at most one point. -/ lemma strict_concave_on_of_deriv2_neg {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf'' : ∀ x ∈ interior D, deriv^[2] f x < 0) : strict_concave_on ℝ D f := (hD.interior.strict_anti_on_of_deriv_neg (λ z hz, (differentiable_at_of_deriv_ne_zero (hf'' z hz).ne).differentiable_within_at .continuous_within_at) $ by rwa interior_interior).strict_concave_on_of_deriv hD hf /-- If a function `f` is twice differentiable on a open convex set `D ⊆ ℝ` and `f''` is nonnegative on `D`, then `f` is convex on `D`. -/ theorem convex_on_of_deriv2_nonneg' {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf' : differentiable_on ℝ f D) (hf'' : differentiable_on ℝ (deriv f) D) (hf''_nonneg : ∀ x ∈ D, 0 ≤ (deriv^[2] f) x) : convex_on ℝ D f := convex_on_of_deriv2_nonneg hD hf'.continuous_on (hf'.mono interior_subset) (hf''.mono interior_subset) (λ x hx, hf''_nonneg x (interior_subset hx)) /-- If a function `f` is twice differentiable on an open convex set `D ⊆ ℝ` and `f''` is nonpositive on `D`, then `f` is concave on `D`. -/ theorem concave_on_of_deriv2_nonpos' {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf' : differentiable_on ℝ f D) (hf'' : differentiable_on ℝ (deriv f) D) (hf''_nonpos : ∀ x ∈ D, deriv^[2] f x ≤ 0) : concave_on ℝ D f := concave_on_of_deriv2_nonpos hD hf'.continuous_on (hf'.mono interior_subset) (hf''.mono interior_subset) (λ x hx, hf''_nonpos x (interior_subset hx)) /-- If a function `f` is continuous on a convex set `D ⊆ ℝ` and `f''` is strictly positive on `D`, then `f` is strictly convex on `D`. Note that we don't require twice differentiability explicitly as it is already implied by the second derivative being strictly positive, except at at most one point. -/ lemma strict_convex_on_of_deriv2_pos' {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf'' : ∀ x ∈ D, 0 < (deriv^[2] f) x) : strict_convex_on ℝ D f := strict_convex_on_of_deriv2_pos hD hf $ λ x hx, hf'' x (interior_subset hx) /-- If a function `f` is continuous on a convex set `D ⊆ ℝ` and `f''` is strictly negative on `D`, then `f` is strictly concave on `D`. Note that we don't require twice differentiability explicitly as it is already implied by the second derivative being strictly negative, except at at most one point. -/ lemma strict_concave_on_of_deriv2_neg' {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf'' : ∀ x ∈ D, deriv^[2] f x < 0) : strict_concave_on ℝ D f := strict_concave_on_of_deriv2_neg hD hf $ λ x hx, hf'' x (interior_subset hx) /-- If a function `f` is twice differentiable on `ℝ`, and `f''` is nonnegative on `ℝ`, then `f` is convex on `ℝ`. -/ theorem convex_on_univ_of_deriv2_nonneg {f : ℝ → ℝ} (hf' : differentiable ℝ f) (hf'' : differentiable ℝ (deriv f)) (hf''_nonneg : ∀ x, 0 ≤ (deriv^[2] f) x) : convex_on ℝ univ f := convex_on_of_deriv2_nonneg' convex_univ hf'.differentiable_on hf''.differentiable_on (λ x _, hf''_nonneg x) /-- If a function `f` is twice differentiable on `ℝ`, and `f''` is nonpositive on `ℝ`, then `f` is concave on `ℝ`. -/ theorem concave_on_univ_of_deriv2_nonpos {f : ℝ → ℝ} (hf' : differentiable ℝ f) (hf'' : differentiable ℝ (deriv f)) (hf''_nonpos : ∀ x, deriv^[2] f x ≤ 0) : concave_on ℝ univ f := concave_on_of_deriv2_nonpos' convex_univ hf'.differentiable_on hf''.differentiable_on (λ x _, hf''_nonpos x) /-- If a function `f` is continuous on `ℝ`, and `f''` is strictly positive on `ℝ`, then `f` is strictly convex on `ℝ`. Note that we don't require twice differentiability explicitly as it is already implied by the second derivative being strictly positive, except at at most one point. -/ lemma strict_convex_on_univ_of_deriv2_pos {f : ℝ → ℝ} (hf : continuous f) (hf'' : ∀ x, 0 < (deriv^[2] f) x) : strict_convex_on ℝ univ f := strict_convex_on_of_deriv2_pos' convex_univ hf.continuous_on $ λ x _, hf'' x /-- If a function `f` is continuous on `ℝ`, and `f''` is strictly negative on `ℝ`, then `f` is strictly concave on `ℝ`. Note that we don't require twice differentiability explicitly as it is already implied by the second derivative being strictly negative, except at at most one point. -/ lemma strict_concave_on_univ_of_deriv2_neg {f : ℝ → ℝ} (hf : continuous f) (hf'' : ∀ x, deriv^[2] f x < 0) : strict_concave_on ℝ univ f := strict_concave_on_of_deriv2_neg' convex_univ hf.continuous_on $ λ x _, hf'' x /-! ### Functions `f : E → ℝ` -/ /-- Lagrange's Mean Value Theorem, applied to convex domains. -/ theorem domain_mvt {f : E → ℝ} {s : set E} {x y : E} {f' : E → (E →L[ℝ] ℝ)} (hf : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ∃ z ∈ segment ℝ x y, f y - f x = f' z (y - x) := begin have hIccIoo := @Ioo_subset_Icc_self ℝ _ 0 1, -- parametrize segment set g : ℝ → E := λ t, x + t • (y - x), have hseg : ∀ t ∈ Icc (0:ℝ) 1, g t ∈ segment ℝ x y, { rw segment_eq_image', simp only [mem_image, and_imp, add_right_inj], intros t ht, exact ⟨t, ht, rfl⟩ }, have hseg' : Icc 0 1 ⊆ g ⁻¹' s, { rw ← image_subset_iff, unfold image, change ∀ _, _, intros z Hz, rw mem_set_of_eq at Hz, rcases Hz with ⟨t, Ht, hgt⟩, rw ← hgt, exact hs.segment_subset xs ys (hseg t Ht) }, -- derivative of pullback of f under parametrization have hfg: ∀ t ∈ Icc (0:ℝ) 1, has_deriv_within_at (f ∘ g) ((f' (g t) : E → ℝ) (y-x)) (Icc (0:ℝ) 1) t, { intros t Ht, have hg : has_deriv_at g (y-x) t, { have := ((has_deriv_at_id t).smul_const (y - x)).const_add x, rwa one_smul at this }, exact (hf (g t) $ hseg' Ht).comp_has_deriv_within_at _ hg.has_deriv_within_at hseg' }, -- apply 1-variable mean value theorem to pullback have hMVT : ∃ (t ∈ Ioo (0:ℝ) 1), ((f' (g t) : E → ℝ) (y-x)) = (f (g 1) - f (g 0)) / (1 - 0), { refine exists_has_deriv_at_eq_slope (f ∘ g) _ (by norm_num) _ _, { exact λ t Ht, (hfg t Ht).continuous_within_at }, { exact λ t Ht, (hfg t $ hIccIoo Ht).has_deriv_at (Icc_mem_nhds Ht.1 Ht.2) } }, -- reinterpret on domain rcases hMVT with ⟨t, Ht, hMVT'⟩, use g t, refine ⟨hseg t $ hIccIoo Ht, _⟩, simp [g, hMVT'], end section is_R_or_C /-! ### Vector-valued functions `f : E → F`. Strict differentiability. A `C^1` function is strictly differentiable, when the field is `ℝ` or `ℂ`. This follows from the mean value inequality on balls, which is a particular case of the above results after restricting the scalars to `ℝ`. Note that it does not make sense to talk of a convex set over `ℂ`, but balls make sense and are enough. Many formulations of the mean value inequality could be generalized to balls over `ℝ` or `ℂ`. For now, we only include the ones that we need. -/ variables {𝕜 : Type*} [is_R_or_C 𝕜] {G : Type*} [normed_add_comm_group G] [normed_space 𝕜 G] {H : Type*} [normed_add_comm_group H] [normed_space 𝕜 H] {f : G → H} {f' : G → G →L[𝕜] H} {x : G} /-- Over the reals or the complexes, a continuously differentiable function is strictly differentiable. -/ lemma has_strict_fderiv_at_of_has_fderiv_at_of_continuous_at (hder : ∀ᶠ y in 𝓝 x, has_fderiv_at f (f' y) y) (hcont : continuous_at f' x) : has_strict_fderiv_at f (f' x) x := begin -- turn little-o definition of strict_fderiv into an epsilon-delta statement refine is_o_iff.mpr (λ c hc, metric.eventually_nhds_iff_ball.mpr _), -- the correct ε is the modulus of continuity of f' rcases metric.mem_nhds_iff.mp (inter_mem hder (hcont $ ball_mem_nhds _ hc)) with ⟨ε, ε0, hε⟩, refine ⟨ε, ε0, _⟩, -- simplify formulas involving the product E × E rintros ⟨a, b⟩ h, rw [← ball_prod_same, prod_mk_mem_set_prod_eq] at h, -- exploit the choice of ε as the modulus of continuity of f' have hf' : ∀ x' ∈ ball x ε, ∥f' x' - f' x∥ ≤ c, { intros x' H', rw ← dist_eq_norm, exact le_of_lt (hε H').2 }, -- apply mean value theorem letI : normed_space ℝ G := restrict_scalars.normed_space ℝ 𝕜 G, refine (convex_ball _ _).norm_image_sub_le_of_norm_has_fderiv_within_le' _ hf' h.2 h.1, exact λ y hy, (hε hy).1.has_fderiv_within_at end /-- Over the reals or the complexes, a continuously differentiable function is strictly differentiable. -/ lemma has_strict_deriv_at_of_has_deriv_at_of_continuous_at {f f' : 𝕜 → G} {x : 𝕜} (hder : ∀ᶠ y in 𝓝 x, has_deriv_at f (f' y) y) (hcont : continuous_at f' x) : has_strict_deriv_at f (f' x) x := has_strict_fderiv_at_of_has_fderiv_at_of_continuous_at (hder.mono (λ y hy, hy.has_fderiv_at)) $ (smul_rightL 𝕜 𝕜 G 1).continuous.continuous_at.comp hcont end is_R_or_C
4d17ac359513957e9d264a1f4c926caee7177832
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/808.lean
0faaab79524a17923f13d4ba922b6a7b05828946
[ "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
193
lean
notation 1 := eq postfix `x`:(max+1) := eq postfix [priority 1] `y`:max := eq attribute [instance, priority 1] definition foo : inhabited nat := inhabited.mk nat.zero definition bar := @eq
1e14d4a079cfdab1e6ba44fcc73caced1ce49b47
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/limits/constructions/binary_products.lean
c9be3227021adad77c6bfe16bba6bbbada904080
[ "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
6,588
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta, Andrew Yang -/ import category_theory.limits.shapes.terminal import category_theory.limits.shapes.pullbacks import category_theory.limits.shapes.binary_products /-! # Constructing binary product from pullbacks and terminal object. The product is the pullback over the terminal objects. In particular, if a category has pullbacks and a terminal object, then it has binary products. We also provide the dual. -/ universes v u open category_theory category_theory.category category_theory.limits variables {C : Type u} [category.{v} C] /-- The pullback over the terminal object is the product -/ def is_product_of_is_terminal_is_pullback {W X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) (h : W ⟶ X) (k : W ⟶ Y) (H₁ : is_terminal Z) (H₂ : is_limit (pullback_cone.mk _ _ (show h ≫ f = k ≫ g, from H₁.hom_ext _ _))) : is_limit (binary_fan.mk h k) := { lift := λ c, H₂.lift (pullback_cone.mk (c.π.app walking_pair.left) (c.π.app walking_pair.right) (H₁.hom_ext _ _)), fac' := λ c j, begin convert H₂.fac (pullback_cone.mk (c.π.app walking_pair.left) (c.π.app walking_pair.right) (H₁.hom_ext _ _)) (some j) using 1, cases j; refl end, uniq' := λ c m hm, begin apply pullback_cone.is_limit.hom_ext H₂, { exact (hm walking_pair.left).trans (H₂.fac (pullback_cone.mk (c.π.app walking_pair.left) (c.π.app walking_pair.right) (H₁.hom_ext _ _)) walking_cospan.left).symm }, { exact (hm walking_pair.right).trans (H₂.fac (pullback_cone.mk (c.π.app walking_pair.left) (c.π.app walking_pair.right) (H₁.hom_ext _ _)) walking_cospan.right).symm }, end } /-- The product is the pullback over the terminal object. -/ def is_pullback_of_is_terminal_is_product {W X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) (h : W ⟶ X) (k : W ⟶ Y) (H₁ : is_terminal Z) (H₂ : is_limit (binary_fan.mk h k)) : is_limit (pullback_cone.mk _ _ (show h ≫ f = k ≫ g, from H₁.hom_ext _ _)) := begin apply pullback_cone.is_limit_aux', intro s, use H₂.lift (binary_fan.mk s.fst s.snd), use H₂.fac (binary_fan.mk s.fst s.snd) walking_pair.left, use H₂.fac (binary_fan.mk s.fst s.snd) walking_pair.right, intros m h₁ h₂, apply H₂.hom_ext, rintro ⟨⟩, { exact h₁.trans (H₂.fac (binary_fan.mk s.fst s.snd) walking_pair.left).symm }, { exact h₂.trans (H₂.fac (binary_fan.mk s.fst s.snd) walking_pair.right).symm } end variable (C) /-- Any category with pullbacks and terminal object has binary products. -/ -- This is not an instance, as it is not always how one wants to construct binary products! lemma has_binary_products_of_terminal_and_pullbacks [has_terminal C] [has_pullbacks C] : has_binary_products C := { has_limit := λ F, has_limit.mk { cone := { X := pullback (terminal.from (F.obj walking_pair.left)) (terminal.from (F.obj walking_pair.right)), π := discrete.nat_trans (λ x, walking_pair.cases_on x pullback.fst pullback.snd)}, is_limit := { lift := λ c, pullback.lift ((c.π).app walking_pair.left) ((c.π).app walking_pair.right) (subsingleton.elim _ _), fac' := λ s c, walking_pair.cases_on c (limit.lift_π _ _) (limit.lift_π _ _), uniq' := λ s m J, begin rw [←J, ←J], ext; rw limit.lift_π; refl end } } } variable {C} /-- The pushout under the initial object is the coproduct -/ def is_coproduct_of_is_initial_is_pushout {W X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) (h : W ⟶ X) (k : W ⟶ Y) (H₁ : is_initial W) (H₂ : is_colimit (pushout_cocone.mk _ _ (show h ≫ f = k ≫ g, from H₁.hom_ext _ _))) : is_colimit (binary_cofan.mk f g) := { desc := λ c, H₂.desc (pushout_cocone.mk (c.ι.app walking_pair.left) (c.ι.app walking_pair.right) (H₁.hom_ext _ _)), fac' := λ c j, begin convert H₂.fac (pushout_cocone.mk (c.ι.app walking_pair.left) (c.ι.app walking_pair.right) (H₁.hom_ext _ _)) (some j) using 1, cases j; refl end, uniq' := λ c m hm, begin apply pushout_cocone.is_colimit.hom_ext H₂, { exact (hm walking_pair.left).trans (H₂.fac (pushout_cocone.mk (c.ι.app walking_pair.left) (c.ι.app walking_pair.right) (H₁.hom_ext _ _)) walking_cospan.left).symm }, { exact (hm walking_pair.right).trans (H₂.fac (pushout_cocone.mk (c.ι.app walking_pair.left) (c.ι.app walking_pair.right) (H₁.hom_ext _ _)) walking_cospan.right).symm }, end } /-- The coproduct is the pushout under the initial object. -/ def is_pushout_of_is_initial_is_coproduct {W X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) (h : W ⟶ X) (k : W ⟶ Y) (H₁ : is_terminal Z) (H₂ : is_limit (binary_fan.mk h k)) : is_limit (pullback_cone.mk _ _ (show h ≫ f = k ≫ g, from H₁.hom_ext _ _)) := begin apply pullback_cone.is_limit_aux', intro s, use H₂.lift (binary_fan.mk s.fst s.snd), use H₂.fac (binary_fan.mk s.fst s.snd) walking_pair.left, use H₂.fac (binary_fan.mk s.fst s.snd) walking_pair.right, intros m h₁ h₂, apply H₂.hom_ext, rintro ⟨⟩, { exact h₁.trans (H₂.fac (binary_fan.mk s.fst s.snd) walking_pair.left).symm }, { exact h₂.trans (H₂.fac (binary_fan.mk s.fst s.snd) walking_pair.right).symm } end variable (C) /-- Any category with pushouts and initial object has binary coproducts. -/ -- This is not an instance, as it is not always how one wants to construct binary coproducts! lemma has_binary_coproducts_of_initial_and_pushouts [has_initial C] [has_pushouts C] : has_binary_coproducts C := { has_colimit := λ F, has_colimit.mk { cocone := { X := pushout (initial.to (F.obj walking_pair.left)) (initial.to (F.obj walking_pair.right)), ι := discrete.nat_trans (λ x, walking_pair.cases_on x pushout.inl pushout.inr)}, is_colimit := { desc := λ c, pushout.desc (c.ι.app walking_pair.left) (c.ι.app walking_pair.right) (subsingleton.elim _ _), fac' := λ s c, walking_pair.cases_on c (colimit.ι_desc _ _) (colimit.ι_desc _ _), uniq' := λ s m J, begin rw [←J, ←J], ext; rw colimit.ι_desc; refl end } } }
bd39cf51333521f04f1bfe0da32ff0b2181ebba3
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/omega/nat/sub_elim.lean
165ac5f8b2461b6ad498bac63cbd91e33f670b94
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
2,982
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Seul Baek -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.omega.nat.form import Mathlib.PostPort namespace Mathlib /- Subtraction elimination for linear natural number arithmetic. Works by repeatedly rewriting goals of the preform `P[t-s]` into `P[x] ∧ (t = s + x ∨ (t ≤ s ∧ x = 0))`, where `x` is fresh. -/ namespace omega namespace nat namespace preterm /-- Find subtraction inside preterm and return its operands -/ def sub_terms : preterm → Option (preterm × preterm) := sorry /-- Find (t - s) inside a preterm and replace it with variable k -/ def sub_subst (t : preterm) (s : preterm) (k : ℕ) : preterm → preterm := sorry theorem val_sub_subst {k : ℕ} {x : preterm} {y : preterm} {v : ℕ → ℕ} {t : preterm} : fresh_index t ≤ k → val (update k (val v x - val v y) v) (sub_subst x y k t) = val v t := sorry end preterm namespace preform /-- Find subtraction inside preform and return its operands -/ def sub_terms : preform → Option (preterm × preterm) := sorry /-- Find (t - s) inside a preform and replace it with variable k -/ @[simp] def sub_subst (x : preterm) (y : preterm) (k : ℕ) : preform → preform := sorry end preform /-- Preform which asserts that the value of variable k is the truncated difference between preterms t and s -/ def is_diff (t : preterm) (s : preterm) (k : ℕ) : preform := preform.or (preform.eq t (preterm.add s (preterm.var 1 k))) (preform.and (preform.le t s) (preform.eq (preterm.var 1 k) (preterm.cst 0))) theorem holds_is_diff {t : preterm} {s : preterm} {k : ℕ} {v : ℕ → ℕ} : v k = preterm.val v t - preterm.val v s → preform.holds v (is_diff t s k) := sorry /-- Helper function for sub_elim -/ def sub_elim_core (t : preterm) (s : preterm) (k : ℕ) (p : preform) : preform := preform.and (preform.sub_subst t s k p) (is_diff t s k) /-- Return de Brujin index of fresh variable that does not occur in any of the arguments -/ def sub_fresh_index (t : preterm) (s : preterm) (p : preform) : ℕ := max (preform.fresh_index p) (max (preterm.fresh_index t) (preterm.fresh_index s)) /-- Return a new preform with all subtractions eliminated -/ def sub_elim (t : preterm) (s : preterm) (p : preform) : preform := sub_elim_core t s (sub_fresh_index t s p) p theorem sub_subst_equiv {k : ℕ} {x : preterm} {y : preterm} {v : ℕ → ℕ} (p : preform) : preform.fresh_index p ≤ k → (preform.holds (update k (preterm.val v x - preterm.val v y) v) (preform.sub_subst x y k p) ↔ preform.holds v p) := sorry theorem sat_sub_elim {t : preterm} {s : preterm} {p : preform} : preform.sat p → preform.sat (sub_elim t s p) := sorry theorem unsat_of_unsat_sub_elim (t : preterm) (s : preterm) (p : preform) : preform.unsat (sub_elim t s p) → preform.unsat p := mt sat_sub_elim
71cbbe6c373d3d3a517a6651aa1a54ecb71eb912
e030b0259b777fedcdf73dd966f3f1556d392178
/library/init/native/default.lean
6a19fe0ac88ca74830580175ec3fe9fcb754e2c3
[ "Apache-2.0" ]
permissive
fgdorais/lean
17b46a095b70b21fa0790ce74876658dc5faca06
c3b7c54d7cca7aaa25328f0a5660b6b75fe26055
refs/heads/master
1,611,523,590,686
1,484,412,902,000
1,484,412,902,000
38,489,734
0
0
null
1,435,923,380,000
1,435,923,379,000
null
UTF-8
Lean
false
false
23,820
lean
/- Copyright (c) 2016 Jared Roesch. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jared Roesch -/ prelude import init.meta.format import init.meta.expr import init.category.state import init.data.string import init.data.list.instances import init.native.ir import init.native.format import init.native.internal import init.native.anf import init.native.cf import init.native.pass import init.native.util import init.native.config import init.native.result namespace native inductive error | string : string → error | many : list error → error meta def error.to_string : error → string | (error.string s) := s | (error.many es) := to_string $ list.map error.to_string es meta def arity_map : Type := rb_map name nat meta def get_arity : expr → nat | (expr.lam _ _ _ body) := 1 + get_arity body | _ := 0 @[reducible] def ir_result (A : Type*) := native.result error A meta def mk_arity_map : list (name × expr) → arity_map | [] := rb_map.mk name nat | ((n, body) :: rest) := rb_map.insert (mk_arity_map rest) n (get_arity body) @[reducible] meta def ir_compiler_state := (config × arity_map × nat) @[reducible] meta def ir_compiler (A : Type) := native.resultT (state ir_compiler_state) error A meta def lift {A} (action : state ir_compiler_state A) : ir_compiler A := ⟨fmap (fun (a : A), native.result.ok a) action⟩ meta def trace_ir (s : string) : ir_compiler unit := do (conf, map, counter) ← lift $ state.read, if config.debug conf then trace s (fun u, return ()) else return () -- An `exotic` monad combinator that accumulates errors. meta def run {M E A} (res : native.resultT M E A) : M (native.result E A) := match res with | ⟨action⟩ := action end meta def sequence_err : list (ir_compiler format) → ir_compiler (list format × list error) | [] := return ([], []) | (action :: remaining) := ⟨ fun s, match (run (sequence_err remaining)) s with | (native.result.err e, s') := (native.result.err e, s) | (native.result.ok (res, errs), s') := match (run action) s' with | (native.result.err e, s'') := (native.result.ok (res, e :: errs), s'') | (native.result.ok v, s'') := (native.result.ok (v :: res, errs), s'') end end ⟩ -- meta lemma sequence_err_always_ok : -- forall xs v s s', sequence_err xs s = native.result.ok (v, s') := sorry meta def lift_result {A} (action : ir_result A) : ir_compiler A := ⟨fun s, (action, s)⟩ -- TODO: fix naming here private meta def take_arguments' : expr → list name → (list name × expr) | (expr.lam n _ _ body) ns := take_arguments' body (n :: ns) | e' ns := (ns, e') meta def fresh_name : ir_compiler name := do (conf, map, counter) ← lift state.read, let fresh := name.mk_numeral (unsigned.of_nat counter) `native._ir_compiler_ in do lift $ state.write (conf, map, counter + 1), return fresh meta def take_arguments (e : expr) : ir_compiler (list name × expr) := let (arg_names, body) := take_arguments' e [] in do fresh_names ← monad.mapm (fun x, fresh_name) arg_names, let locals := list.map mk_local fresh_names in return $ (fresh_names, expr.instantiate_vars body (list.reverse locals)) -- meta def lift_state {A} (action : state arity_map A) : ir_compiler A := -- fun (s : arity_map), match action s with -- | (a, s) := (return a, s) -- end meta def mk_error {T} : string → ir_compiler T := fun s, do trace_ir "CREATEDERROR", lift_result (native.result.err $ error.string s) meta def lookup_arity (n : name) : ir_compiler nat := do (_, map, counter) ← lift state.read, if n = `nat.cases_on then pure 2 else match rb_map.find map n with | option.none := mk_error $ "could not find arity for: " ++ to_string n | option.some n := return n end meta def mk_nat_literal (n : nat) : ir_compiler ir.expr := return (ir.expr.lit $ ir.literal.nat n) def repeat {A : Type} : nat → A → list A | 0 _ := [] | (n + 1) a := a :: repeat n a def zip {A B : Type} : list A → list B → list (A × B) | [] [] := [] | [] (y :: ys) := [] | (x :: xs) [] := [] | (x :: xs) (y :: ys) := (x, y) :: zip xs ys private def upto' : ℕ → list ℕ | 0 := [] | (n + 1) := n :: upto' n def upto (n : ℕ) : list ℕ := list.reverse $ upto' n def label {A : Type} (xs : list A) : list (nat × A) := zip (upto (list.length xs)) xs -- lemma label_size_eq : -- forall A (xs : list A), -- list.length (label xs) = list.length xs := -- begin -- intros, -- induction xs, -- apply sorry -- apply sorry -- end -- HELPERS -- meta def assert_name : ir.expr → ir_compiler name | (ir.expr.locl n) := lift_result $ native.result.ok n | e := mk_error $ "expected name found: " ++ to_string (format_cpp.expr e) meta def assert_expr : ir.stmt → ir_compiler ir.expr | (ir.stmt.e exp) := return exp | s := mk_error ("internal invariant violated, found: " ++ (to_string (format_cpp.stmt s))) meta def mk_call (head : name) (args : list ir.expr) : ir_compiler ir.expr := let args'' := list.map assert_name args in do args' ← monad.sequence args'', return (ir.expr.call head args') meta def mk_under_sat_call (head : name) (args : list ir.expr) : ir_compiler ir.expr := let args'' := list.map assert_name args in do args' ← monad.sequence args'', return $ ir.expr.mk_native_closure head args' meta def bind_value_with_ty (val : ir.expr) (ty : ir.ty) (body : name → ir_compiler ir.stmt) : ir_compiler ir.stmt := do fresh ← fresh_name, ir.stmt.letb fresh ty val <$> (body fresh) meta def bind_value (val : ir.expr) (body : name → ir_compiler ir.stmt) : ir_compiler ir.stmt := bind_value_with_ty val ir.ty.object body -- not in love with this --solution-- hack, revisit meta def compile_local (n : name) : ir_compiler name := return $ (mk_str_name "_$local$_" (name.to_string_with_sep "_" n)) meta def mk_invoke (loc : name) (args : list ir.expr) : ir_compiler ir.expr := let args'' := list.map assert_name args in do args' ← monad.sequence args'', loc' ← compile_local loc, lift_result (native.result.ok $ ir.expr.invoke loc' args') meta def mk_over_sat_call (head : name) (fst snd : list ir.expr) : ir_compiler ir.expr := let fst' := list.map assert_name fst, snd' := list.map assert_name snd in do args' ← monad.sequence fst', args'' ← monad.sequence snd', fresh ← fresh_name, locl ← compile_local fresh, invoke ← ir.stmt.e <$> (mk_invoke fresh (fmap ir.expr.locl args'')), return $ ir.expr.block (ir.stmt.seq [ ir.stmt.letb locl ir.ty.object (ir.expr.call head args') ir.stmt.nop, invoke ]) meta def is_return (n : name) : bool := decidable.to_bool $ `native_compiler.return = n meta def compile_call (head : name) (arity : nat) (args : list ir.expr) : ir_compiler ir.expr := do trace_ir $ "compile_call: " ++ (to_string head), if list.length args = arity then mk_call head args else if list.length args < arity then mk_under_sat_call head args else mk_over_sat_call head (list.taken arity args) (list.dropn arity args) meta def mk_object (arity : unsigned) (args : list ir.expr) : ir_compiler ir.expr := let args'' := list.map assert_name args in do args' ← monad.sequence args'', lift_result (native.result.ok $ ir.expr.mk_object (unsigned.to_nat arity) args') meta def one_or_error (args : list expr) : ir_compiler expr := match args with | ((h : expr) :: []) := lift_result $ native.result.ok h | _ := mk_error "internal invariant violated, should only have one argument" end meta def panic (msg : string) : ir_compiler ir.expr := return $ ir.expr.panic msg -- END HELPERS -- meta def bind_case_fields' (scrut : name) : list (nat × name) → ir.stmt → ir_compiler ir.stmt | [] body := return body | ((n, f) :: fs) body := do loc ← compile_local f, ir.stmt.letb f ir.ty.object (ir.expr.project scrut n) <$> (bind_case_fields' fs body) meta def bind_case_fields (scrut : name) (fs : list name) (body : ir.stmt) : ir_compiler ir.stmt := bind_case_fields' scrut (label fs) body meta def mk_cases_on (case_name scrut : name) (cases : list (nat × ir.stmt)) (default : ir.stmt) : ir.stmt := ir.stmt.seq [ ir.stmt.letb `ctor_index ir.ty.int (ir.expr.call `cidx [scrut]) ir.stmt.nop, ir.stmt.switch `ctor_index cases default ] meta def compile_cases (action : expr → ir_compiler ir.stmt) (scrut : name) : list (nat × expr) → ir_compiler (list (nat × ir.stmt)) | [] := return [] | ((n, body) :: cs) := do (fs, body') ← take_arguments body, body'' ← action body', cs' ← compile_cases cs, case ← bind_case_fields scrut fs body'', return $ (n, case) :: cs' meta def compile_cases_on_to_ir_expr (case_name : name) (cases : list expr) (action : expr → ir_compiler ir.stmt) : ir_compiler ir.expr := do default ← panic "default case should never be reached", match cases with | [] := mk_error $ "found " ++ to_string case_name ++ "applied to zero arguments" | (h :: cs) := do ir_scrut ← action h >>= assert_expr, ir.expr.block <$> bind_value ir_scrut (fun scrut, do cs' ← compile_cases action scrut (label cs), return (mk_cases_on case_name scrut cs' (ir.stmt.e default))) end meta def bind_builtin_case_fields' (scrut : name) : list (nat × name) → ir.stmt → ir_compiler ir.stmt | [] body := return body | ((n, f) :: fs) body := do loc ← compile_local f, ir.stmt.letb loc ir.ty.object (ir.expr.project scrut n) <$> (bind_builtin_case_fields' fs body) meta def bind_builtin_case_fields (scrut : name) (fs : list name) (body : ir.stmt) : ir_compiler ir.stmt := bind_builtin_case_fields' scrut (label fs) body meta def compile_builtin_cases (action : expr → ir_compiler ir.stmt) (scrut : name) : list (nat × expr) → ir_compiler (list (nat × ir.stmt)) | [] := return [] | ((n, body) :: cs) := do (fs, body') ← take_arguments body, body'' ← action body', cs' ← compile_builtin_cases cs, case ← bind_builtin_case_fields scrut fs body'', return $ (n, case) :: cs' meta def in_lean_ns (n : name) : name := mk_simple_name ("lean::" ++ name.to_string_with_sep "_" n) meta def mk_builtin_cases_on (case_name scrut : name) (cases : list (nat × ir.stmt)) (default : ir.stmt) : ir.stmt := -- replace `ctor_index with a generated name ir.stmt.seq [ ir.stmt.letb `buffer ir.ty.object_buffer ir.expr.uninitialized ir.stmt.nop, ir.stmt.letb `ctor_index ir.ty.int (ir.expr.call (in_lean_ns case_name) [scrut, `buffer]) ir.stmt.nop, ir.stmt.switch `ctor_index cases default ] meta def compile_builtin_cases_on_to_ir_expr (case_name : name) (cases : list expr) (action : expr → ir_compiler ir.stmt) : ir_compiler ir.expr := do default ← panic "default case should never be reached", match cases with | [] := mk_error $ "found " ++ to_string case_name ++ "applied to zero arguments" | (h :: cs) := do ir_scrut ← action h >>= assert_expr, ir.expr.block <$> bind_value ir_scrut (fun scrut, do cs' ← compile_builtin_cases action scrut (label cs), return (mk_builtin_cases_on case_name scrut cs' (ir.stmt.e default))) end meta def mk_is_simple (scrut : name) : ir.expr := ir.expr.call `is_simple [scrut] meta def mk_is_zero (n : name) : ir.expr := ir.expr.equals (ir.expr.raw_int 0) (ir.expr.locl n) meta def mk_cidx (obj : name) : ir.expr := ir.expr.call `cidx [obj] -- we should add applicative brackets meta def mk_simple_nat_cases_on (scrut : name) (zero_case succ_case : ir.stmt) : ir_compiler ir.stmt := bind_value_with_ty (mk_cidx scrut) (ir.ty.name `int) (fun cidx, bind_value_with_ty (mk_is_zero cidx) (ir.ty.name `bool) (fun is_zero, pure $ ir.stmt.ite is_zero zero_case succ_case)) meta def mk_mpz_nat_cases_on (scrut : name) (zero_case succ_case : ir.stmt) : ir_compiler ir.stmt := ir.stmt.e <$> panic "mpz" meta def mk_nat_cases_on (scrut : name) (zero_case succ_case : ir.stmt) : ir_compiler ir.stmt := bind_value_with_ty (mk_is_simple scrut) (ir.ty.name `bool) (fun is_simple, ir.stmt.ite is_simple <$> mk_simple_nat_cases_on scrut zero_case succ_case <*> mk_mpz_nat_cases_on scrut zero_case succ_case) meta def assert_two_cases (cases : list expr) : ir_compiler (expr × expr) := match cases with | c1 :: c2 :: _ := return (c1, c2) | _ := mk_error "nat.cases_on should have exactly two cases" end meta def mk_vm_nat (n : name) : ir.expr := ir.expr.call (in_lean_ns `mk_vm_simple) [n] meta def compile_succ_case (action : expr → ir_compiler ir.stmt) (scrut : name) (succ_case : expr) : ir_compiler ir.stmt := do (fs, body') ← take_arguments succ_case, body'' ← action body', match fs with | pred :: _ := do loc ← compile_local pred, fresh ← fresh_name, bind_value_with_ty (mk_cidx scrut) (ir.ty.name `int) (fun cidx, bind_value_with_ty (ir.expr.sub (ir.expr.locl cidx) (ir.expr.raw_int 1)) (ir.ty.name `int) (fun sub, pure $ ir.stmt.letb loc ir.ty.object (mk_vm_nat sub) body'' )) | _ := mk_error "compile_succ_case too many fields" end meta def compile_nat_cases_on_to_ir_expr (case_name : name) (cases : list expr) (action : expr → ir_compiler ir.stmt) : ir_compiler ir.expr := match cases with | [] := mk_error $ "found " ++ to_string case_name ++ "applied to zero arguments" | (h :: cs) := do ir_scrut ← action h >>= assert_expr, (zero_case, succ_case) ← assert_two_cases cs, trace_ir (to_string zero_case), trace_ir (to_string succ_case), ir.expr.block <$> bind_value ir_scrut (fun scrut, do zc ← action zero_case, sc ← compile_succ_case action scrut succ_case, mk_nat_cases_on scrut zc sc ) end -- this→emit_indented("if (is_simple("); -- action(scrutinee); -- this→emit_string("))"); -- this→emit_block([&] () { -- this→emit_indented("if (cidx("); -- action(scrutinee); -- this→emit_string(") == 0) "); -- this→emit_block([&] () { -- action(zero_case); -- *this→m_output_stream << ";\n"; -- }); -- this→emit_string("else "); -- this→emit_block([&] () { -- action(succ_case); -- *this→m_output_stream << ";\n"; -- }); -- }); -- this→emit_string("else "); -- this→emit_block([&] () { -- this→emit_indented("if (to_mpz("); -- action(scrutinee); -- this→emit_string(") == 0) "); -- this→emit_block([&] () { -- action(zero_case); -- *this→m_output_stream << ";\n"; -- }); -- this→emit_string("else "); -- this→emit_block([&] () { -- action(succ_case); -- }); -- }); -- this code isnt' great working around the semi-functional frontend meta def compile_expr_app_to_ir_expr (head : expr) (args : list expr) (action : expr → ir_compiler ir.stmt) : ir_compiler ir.expr := do trace_ir (to_string head ++ to_string args), if expr.is_constant head = bool.tt then (if is_return (expr.const_name head) then do rexp ← one_or_error args, (ir.expr.block ∘ ir.stmt.return) <$> ((action rexp) >>= assert_expr) else if is_nat_cases_on (expr.const_name head) then compile_nat_cases_on_to_ir_expr (expr.const_name head) args action else match is_internal_cnstr head with | option.some n := do args' ← monad.sequence $ list.map (fun x, action x >>= assert_expr) args, mk_object n args' | option.none := match is_internal_cases head with | option.some n := compile_cases_on_to_ir_expr (expr.const_name head) args action | option.none := match get_builtin (expr.const_name head) with | option.some builtin := match builtin with | builtin.vm n := mk_error "vm" | builtin.cfun n arity := do args' ← monad.sequence $ list.map (fun x, action x >>= assert_expr) args, compile_call n arity args' | builtin.cases n arity := compile_builtin_cases_on_to_ir_expr (expr.const_name head) args action end | option.none := do args' ← monad.sequence $ list.map (fun x, action x >>= assert_expr) args, arity ← lookup_arity (expr.const_name head), compile_call (expr.const_name head) arity args' end end end) else if expr.is_local_constant head then do args' ← monad.sequence $ list.map (fun x, action x >>= assert_expr) args, mk_invoke (expr.local_uniq_name head) args' else (mk_error ("unsupported call position" ++ (to_string head))) meta def compile_expr_macro_to_ir_expr (e : expr) : ir_compiler ir.expr := match native.get_nat_value e with | option.none := mk_error "unsupported macro" | option.some n := mk_nat_literal n end meta def compile_expr_to_ir_expr (action : expr → ir_compiler ir.stmt): expr → ir_compiler ir.expr | (expr.const n ls) := match native.is_internal_cnstr (expr.const n ls) with | option.none := -- TODO, do I need to case on arity here? I should probably always emit a call match get_builtin n with | option.some (builtin.cfun n' arity) := compile_call n arity [] | _ := if n = "_neutral_" then (pure $ ir.expr.mk_object 0 []) else do arity ← lookup_arity n, compile_call n arity [] end | option.some arity := pure $ ir.expr.mk_object (unsigned.to_nat arity) [] end | (expr.var i) := mk_error "there should be no bound variables in compiled terms" | (expr.sort _) := mk_error "found sort" | (expr.mvar _ _) := mk_error "unexpected meta-variable in expr" | (expr.local_const n _ _ _) := ir.expr.locl <$> compile_local n | (expr.app f x) := let head := expr.get_app_fn (expr.app f x), args := expr.get_app_args (expr.app f x) in compile_expr_app_to_ir_expr head args action | (expr.lam _ _ _ _) := mk_error "found lam" | (expr.pi _ _ _ _) := mk_error "found pi" | (expr.elet n _ v body) := mk_error "internal error: can not translate let binding into a ir_expr" | (expr.macro d sz args) := compile_expr_macro_to_ir_expr (expr.macro d sz args) meta def compile_expr_to_ir_stmt : expr → ir_compiler ir.stmt | (expr.pi _ _ _ _) := mk_error "found pi, should not be translating a Pi for any reason (yet ...)" | (expr.elet n _ v body) := do n' ← compile_local n, v' ← compile_expr_to_ir_expr compile_expr_to_ir_stmt v, -- this is a scoping fail, we need to fix how we compile locals body' ← compile_expr_to_ir_stmt (expr.instantiate_vars body [mk_local n]), -- not the best solution, here need to think hard about how to prevent thing, more aggressive anf? match v' with | ir.expr.block stmt := return (ir.stmt.seq [ir.stmt.letb n' ir.ty.object ir.expr.uninitialized ir.stmt.nop, body']) | _ := return (ir.stmt.letb n' ir.ty.object v' body') end | e' := ir.stmt.e <$> compile_expr_to_ir_expr compile_expr_to_ir_stmt e' meta def compile_defn_to_ir (decl_name : name) (args : list name) (body : expr) : ir_compiler ir.defn := do body' ← compile_expr_to_ir_stmt body, let params := (zip args (repeat (list.length args) (ir.ty.ref ir.ty.object))) in pure (ir.defn.mk decl_name params ir.ty.object body') def unwrap_or_else {T R : Type} : ir_result T → (T → R) → (error → R) → R | (native.result.err e) f err := err e | (native.result.ok t) f err := f t meta def replace_main (n : name) : name := if n = `main then "___lean__main" else n meta def trace_expr (e : expr) : ir_compiler unit := trace ("trace_expr: " ++ to_string e) (fun u, return ()) meta def compile_defn (decl_name : name) (e : expr) : ir_compiler format := let arity := get_arity e in do (args, body) ← take_arguments e, ir ← compile_defn_to_ir (replace_main decl_name) args body, return $ format_cpp.defn ir meta def compile' : list (name × expr) → list (ir_compiler format) | [] := [] | ((n, e) :: rest) := do let decl := (fun d, d ++ format.line ++ format.line) <$> compile_defn n e in decl :: (compile' rest) meta def format_error : error → format | (error.string s) := to_fmt s | (error.many es) := format_concat (list.map format_error es) meta def mk_lean_name (n : name) : ir.expr := ir.expr.constructor (in_lean_ns `name) (name.components n) meta def emit_declare_vm_builtins : list (name × expr) → ir_compiler (list ir.stmt) | [] := return [] | ((n, body) :: es) := do vm_name ← pure $ (mk_lean_name n), tail ← emit_declare_vm_builtins es, fresh ← fresh_name, let cpp_name := in_lean_ns `name, single_binding := ir.stmt.seq [ ir.stmt.letb fresh (ir.ty.name cpp_name) vm_name ir.stmt.nop, ir.stmt.e $ ir.expr.assign `env (ir.expr.call `add_native [`env, fresh, replace_main n]) ] in return $ single_binding :: tail meta def emit_main (procs : list (name × expr)) : ir_compiler ir.defn := do builtins ← emit_declare_vm_builtins procs, arity ← lookup_arity `main, vm_simple_obj ← fresh_name, call_main ← compile_call "___lean__main" arity [ir.expr.locl vm_simple_obj], return (ir.defn.mk `main [] ir.ty.int $ ir.stmt.seq ([ ir.stmt.e $ ir.expr.call (in_lean_ns `initialize) [], ir.stmt.letb `env (ir.ty.name (in_lean_ns `environment)) ir.expr.uninitialized ir.stmt.nop ] ++ builtins ++ [ ir.stmt.letb `ios (ir.ty.name (in_lean_ns `io_state)) (ir.expr.call (in_lean_ns `get_global_ios) []) ir.stmt.nop, ir.stmt.letb `opts (ir.ty.name (in_lean_ns `options)) (ir.expr.call (in_lean_ns `get_options_from_ios) [`ios]) ir.stmt.nop, ir.stmt.letb `S (ir.ty.name (in_lean_ns `vm_state)) (ir.expr.constructor (in_lean_ns `vm_state) [`env, `opts]) ir.stmt.nop, ir.stmt.letb `scoped (ir.ty.name (in_lean_ns `scope_vm_state)) (ir.expr.constructor (in_lean_ns `scope_vm_state) [`S]) ir.stmt.nop, ir.stmt.e $ ir.expr.assign `g_env (ir.expr.address_of `env), ir.stmt.letb vm_simple_obj ir.ty.object (ir.expr.mk_object 0 []) ir.stmt.nop, ir.stmt.e call_main ])) -- -- call_mains -- -- buffer<expr> args; -- -- auto unit = mk_neutral_expr(); -- -- args.push_back(unit); -- -- // Make sure to invoke the C call machinery since it is non-deterministic -- -- // which case we enter here. -- -- compile_to_c_call(main_fn, args, 0, name_map<unsigned>()); -- -- *this→m_output_stream << ";\n return 0;\n}" << std::endl; -- ] meta def unzip {A B} : list (A × B) → (list A × list B) | [] := ([], []) | ((x, y) :: rest) := let (xs, ys) := unzip rest in (x :: xs, y :: ys) meta def configuration : ir_compiler config := do (conf, _, _) ← lift $ state.read, pure conf meta def apply_pre_ir_passes (procs : list procedure) (conf : config) : list procedure := run_passes conf [anf, cf] procs meta def driver (procs : list (name × expr)) : ir_compiler (list format × list error) := do procs' ← apply_pre_ir_passes procs <$> configuration, (fmt_decls, errs) ← sequence_err (compile' procs'), main ← emit_main procs', return (format_cpp.defn main :: fmt_decls, errs) meta def compile (conf : config) (procs : list (name × expr)) : format := let arities := mk_arity_map procs in -- Put this in a combinator or something ... match run (driver procs) (conf, arities, 0) with | (native.result.err e, s) := error.to_string e | (native.result.ok (decls, errs), s) := if list.length errs = 0 then format_concat decls else format_error (error.many errs) end -- meta def compile (procs : list (name)) end native
8344ccc102d007d3704548e1256fed42ea041e42
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/analysis/normed_space/dual.lean
a58102cd917d4ed462a30b119954059241883eb6
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,210
lean
/- Copyright (c) 2020 Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth -/ import analysis.normed_space.hahn_banach /-! # The topological dual of a normed space In this file we define the topological dual `normed_space.dual` of a normed space, and the continuous linear map `normed_space.inclusion_in_double_dual` from a normed space into its double dual. For base field `𝕜 = ℝ` or `𝕜 = ℂ`, this map is actually an isometric embedding; we provide a version `normed_space.inclusion_in_double_dual_li` of the map which is of type a bundled linear isometric embedding, `E →ₗᵢ[𝕜] (dual 𝕜 (dual 𝕜 E))`. Since a lot of elementary properties don't require `eq_of_dist_eq_zero` we start setting up the theory for `semi_normed_space` and we specialize to `normed_space` when needed. ## Tags dual -/ noncomputable theory open_locale classical universes u v namespace normed_space section general variables (𝕜 : Type*) [nondiscrete_normed_field 𝕜] variables (E : Type*) [semi_normed_group E] [semi_normed_space 𝕜 E] variables (F : Type*) [normed_group F] [normed_space 𝕜 F] /-- The topological dual of a seminormed space `E`. -/ @[derive [inhabited, has_coe_to_fun, semi_normed_group, semi_normed_space 𝕜]] def dual := E →L[𝕜] 𝕜 instance : normed_group (dual 𝕜 F) := continuous_linear_map.to_normed_group instance : normed_space 𝕜 (dual 𝕜 F) := continuous_linear_map.to_normed_space /-- The inclusion of a normed space in its double (topological) dual, considered as a bounded linear map. -/ def inclusion_in_double_dual : E →L[𝕜] (dual 𝕜 (dual 𝕜 E)) := continuous_linear_map.apply 𝕜 𝕜 @[simp] lemma dual_def (x : E) (f : dual 𝕜 E) : inclusion_in_double_dual 𝕜 E x f = f x := rfl lemma inclusion_in_double_dual_norm_eq : ∥inclusion_in_double_dual 𝕜 E∥ = ∥(continuous_linear_map.id 𝕜 (dual 𝕜 E))∥ := continuous_linear_map.op_norm_flip _ lemma inclusion_in_double_dual_norm_le : ∥inclusion_in_double_dual 𝕜 E∥ ≤ 1 := by { rw inclusion_in_double_dual_norm_eq, exact continuous_linear_map.norm_id_le } lemma double_dual_bound (x : E) : ∥(inclusion_in_double_dual 𝕜 E) x∥ ≤ ∥x∥ := by simpa using continuous_linear_map.le_of_op_norm_le _ (inclusion_in_double_dual_norm_le 𝕜 E) x end general section bidual_isometry variables (𝕜 : Type v) [is_R_or_C 𝕜] {E : Type u} [normed_group E] [normed_space 𝕜 E] /-- If one controls the norm of every `f x`, then one controls the norm of `x`. Compare `continuous_linear_map.op_norm_le_bound`. -/ lemma norm_le_dual_bound (x : E) {M : ℝ} (hMp: 0 ≤ M) (hM : ∀ (f : dual 𝕜 E), ∥f x∥ ≤ M * ∥f∥) : ∥x∥ ≤ M := begin classical, by_cases h : x = 0, { simp only [h, hMp, norm_zero] }, { obtain ⟨f, hf⟩ : ∃ g : E →L[𝕜] 𝕜, _ := exists_dual_vector 𝕜 x h, calc ∥x∥ = ∥norm' 𝕜 x∥ : (norm_norm' _ _ _).symm ... = ∥f x∥ : by rw hf.2 ... ≤ M * ∥f∥ : hM f ... = M : by rw [hf.1, mul_one] } end lemma eq_zero_of_forall_dual_eq_zero {x : E} (h : ∀ f : dual 𝕜 E, f x = (0 : 𝕜)) : x = 0 := norm_eq_zero.mp (le_antisymm (norm_le_dual_bound 𝕜 x le_rfl (λ f, by simp [h f])) (norm_nonneg _)) lemma eq_zero_iff_forall_dual_eq_zero (x : E) : x = 0 ↔ ∀ g : dual 𝕜 E, g x = 0 := ⟨λ hx, by simp [hx], λ h, eq_zero_of_forall_dual_eq_zero 𝕜 h⟩ lemma eq_iff_forall_dual_eq {x y : E} : x = y ↔ ∀ g : dual 𝕜 E, g x = g y := begin rw [← sub_eq_zero, eq_zero_iff_forall_dual_eq_zero 𝕜 (x - y)], simp [sub_eq_zero], end /-- The inclusion of a normed space in its double dual is an isometry onto its image.-/ def inclusion_in_double_dual_li : E →ₗᵢ[𝕜] (dual 𝕜 (dual 𝕜 E)) := { norm_map' := begin intros x, apply le_antisymm, { exact double_dual_bound 𝕜 E x }, rw continuous_linear_map.norm_def, apply le_cInf continuous_linear_map.bounds_nonempty, rintros c ⟨hc1, hc2⟩, exact norm_le_dual_bound 𝕜 x hc1 hc2 end, .. inclusion_in_double_dual 𝕜 E } end bidual_isometry end normed_space
603c18fd0ea6860791555864322bf9397972841f
b3c7090f393c11bd47c82d2f8bb4edf8213173f5
/src/equivalence.lean
ed38d13a5cafa13c75fa8d9eb51c4512a5a89b30
[]
no_license
ImperialCollegeLondon/lean-groups
964b197478f0313d826073576a3e0ae8b166a584
9a82d2a66ef7f549107fcb4e1504d734c43ebb33
refs/heads/master
1,592,371,184,330
1,567,197,270,000
1,567,197,270,000
195,810,480
4
0
null
null
null
null
UTF-8
Lean
false
false
3,384
lean
import data.quot -- equivalence relations and equivalence classes import tactic.interactive -- for "choose" tactic -- Sian's definition of an equivalence relation on X corresponding to a function f : X → Y -- X and Y and f are fixed once and for all in this story, so let's make them parameters -- in a section. section -- in this section X and Y and the surjection f will be fixed once and for all open function -- so I can write "surjective" instead of "function.surjective" parameters {X : Type} {Y : Type} (f : X → Y) (hf : surjective f) -- now let's define the binary relation that Sian came up with def R (x₁ x₂ : X) : Prop := f x₁ = f x₂ -- top tip -- sometimes "unfold R" doesn't work. I don't know why. Try the tactic "delta R"? This always works. theorem R.equivalence : equivalence R := begin split, delta R, unfold reflexive, intro, refl, split, delta R, unfold symmetric, intros, rw a, delta R, unfold transitive, intros, rw a, assumption, end -- A "setoid" is Lean's rather pretentious term for -- the data of a type and an equivalence relation on the type. -- More precisely, a term of type `setoid X` is a *pair* -- consisting of -- 1) a binary relation R on X -- 2) a proof that R is an equivalence relation. -- We just proved R was an equivalence relation on X so we can make a setoid. -- Note that we have to give both the relation and the proof that it's an equivalence relation. def s : setoid X := ⟨R, R.equivalence⟩ -- pointy brackets is often a constructor for a type which is a pair. -- let's define Q to be the set of equivalence classes for this equivalence relation. -- Lean takes the "quotient of the setoid". def Q := quotient s -- Now Q is the set of equivalence classes. -- when you left the office today Friday, I had challenged you to give maps from Q to Y -- You said "Let S be an equivalence class. Define F(S) = f(x) where x is any element of S." -- I said "yeah but you need to check that that is well-defined, because what if your definition -- of F(S) depends on the choice of x?" -- If you try to make this definition in Lean, as below, then Lean makes precisely the -- same objection. It wants to know why two things in the same equivalence class give the same answer. def F : Q → Y := λ q, quotient.lift_on' q (λ (x : X), f x) begin show ∀ a b : X, R a b → f a = f b, delta R, intros, assumption, end theorem commutes' (x : X) : f x = F (quotient.mk' x) := begin refl end -- technical note: I managed to define a function from Q to somewhere because I knew -- an "eliminator" for Q, namely quotient.lift_on' -- def G : Y → Q := sorry -- you never did that bit. How will you do it? -- you will need to know a "constructor" for Q, namely a way to make elements of Q. -- Here is a function from X to Q. example : X → Q := quotient.mk' -- Using that function, can you make a function from Y to Q? Here's a hint. include hf -- need surjectivity for this one noncomputable def G : Y → Q := λ y, quotient.mk' (classical.some (hf y)) -- What shall we do next? lemma commutes (x : X) : G (f x) = quotient.mk' x := begin let x' := classical.some (hf (f x)), have xh' := classical.some_spec (hf (f x)), change f x' = f x at xh', change quotient.mk' (x') = _, rw quotient.eq', show R _ x, exact xh', end end -- section
eea58d8cdf0846a113b36896f36176fd93ddd3c0
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/multiset/sort.lean
210190a1dae072cf8c6154e1aafbb1204b5616d1
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
2,633
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.list.sort import Mathlib.data.multiset.basic import Mathlib.data.string.basic import Mathlib.PostPort universes u_1 namespace Mathlib /-! # Construct a sorted list from a multiset. -/ namespace multiset /-- `sort s` constructs a sorted list from the multiset `s`. (Uses merge sort algorithm.) -/ def sort {α : Type u_1} (r : α → α → Prop) [DecidableRel r] [is_trans α r] [is_antisymm α r] [is_total α r] (s : multiset α) : List α := quot.lift_on s (list.merge_sort r) sorry @[simp] theorem coe_sort {α : Type u_1} (r : α → α → Prop) [DecidableRel r] [is_trans α r] [is_antisymm α r] [is_total α r] (l : List α) : sort r ↑l = list.merge_sort r l := rfl @[simp] theorem sort_sorted {α : Type u_1} (r : α → α → Prop) [DecidableRel r] [is_trans α r] [is_antisymm α r] [is_total α r] (s : multiset α) : list.sorted r (sort r s) := quot.induction_on s fun (l : List α) => list.sorted_merge_sort r l @[simp] theorem sort_eq {α : Type u_1} (r : α → α → Prop) [DecidableRel r] [is_trans α r] [is_antisymm α r] [is_total α r] (s : multiset α) : ↑(sort r s) = s := quot.induction_on s fun (l : List α) => quot.sound (list.perm_merge_sort r l) @[simp] theorem mem_sort {α : Type u_1} (r : α → α → Prop) [DecidableRel r] [is_trans α r] [is_antisymm α r] [is_total α r] {s : multiset α} {a : α} : a ∈ sort r s ↔ a ∈ s := eq.mpr (id (Eq._oldrec (Eq.refl (a ∈ sort r s ↔ a ∈ s)) (Eq.symm (propext mem_coe)))) (eq.mpr (id (Eq._oldrec (Eq.refl (a ∈ ↑(sort r s) ↔ a ∈ s)) (sort_eq r s))) (iff.refl (a ∈ s))) @[simp] theorem length_sort {α : Type u_1} (r : α → α → Prop) [DecidableRel r] [is_trans α r] [is_antisymm α r] [is_total α r] {s : multiset α} : list.length (sort r s) = coe_fn card s := quot.induction_on s (list.length_merge_sort r) protected instance has_repr {α : Type u_1} [has_repr α] : has_repr (multiset α) := has_repr.mk fun (s : multiset α) => string.str string.empty (char.of_nat (bit1 (bit1 (bit0 (bit1 (bit1 (bit1 1))))))) ++ string.intercalate (string.str (string.str string.empty (char.of_nat (bit0 (bit0 (bit1 (bit1 (bit0 1))))))) (char.of_nat (bit0 (bit0 (bit0 (bit0 (bit0 1))))))) (sort LessEq (map repr s)) ++ string.str string.empty (char.of_nat (bit1 (bit0 (bit1 (bit1 (bit1 (bit1 1)))))))
71a8ffd4acf95b032441ec19c43965b714c1980e
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/normed_space/completion.lean
11b159a3fcf99ce747e2dfd7b08993beb00309f7
[ "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,722
lean
/- Copyright (c) 2022 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import analysis.normed.group.completion import analysis.normed_space.operator_norm import topology.algebra.uniform_ring /-! # Normed space structure on the completion of a normed space If `E` is a normed space over `𝕜`, then so is `uniform_space.completion E`. In this file we provide necessary instances and define `uniform_space.completion.to_complₗᵢ` - coercion `E → uniform_space.completion E` as a bundled linear isometry. We also show that if `A` is a normed algebra over `𝕜`, then so is `uniform_space.completion A`. TODO: Generalise the results here from the concrete `completion` to any `abstract_completion`. -/ noncomputable theory namespace uniform_space namespace completion variables (𝕜 E : Type*) [normed_field 𝕜] [normed_add_comm_group E] [normed_space 𝕜 E] @[priority 100] instance normed_space.to_has_uniform_continuous_const_smul : has_uniform_continuous_const_smul 𝕜 E := ⟨λ c, (lipschitz_with_smul c).uniform_continuous⟩ instance : normed_space 𝕜 (completion E) := { smul := (•), norm_smul_le := λ c x, induction_on x (is_closed_le (continuous_const_smul _).norm (continuous_const.mul continuous_norm)) $ λ y, by simp only [← coe_smul, norm_coe, norm_smul], .. completion.module } variables {𝕜 E} /-- Embedding of a normed space to its completion as a linear isometry. -/ def to_complₗᵢ : E →ₗᵢ[𝕜] completion E := { to_fun := coe, map_smul' := coe_smul, norm_map' := norm_coe, .. to_compl } @[simp] lemma coe_to_complₗᵢ : ⇑(to_complₗᵢ : E →ₗᵢ[𝕜] completion E) = coe := rfl /-- Embedding of a normed space to its completion as a continuous linear map. -/ def to_complL : E →L[𝕜] completion E := to_complₗᵢ.to_continuous_linear_map @[simp] lemma coe_to_complL : ⇑(to_complL : E →L[𝕜] completion E) = coe := rfl @[simp] lemma norm_to_complL {𝕜 E : Type*} [nontrivially_normed_field 𝕜] [normed_add_comm_group E] [normed_space 𝕜 E] [nontrivial E] : ‖(to_complL : E →L[𝕜] completion E)‖ = 1 := (to_complₗᵢ : E →ₗᵢ[𝕜] completion E).norm_to_continuous_linear_map section algebra variables (𝕜) (A : Type*) instance [semi_normed_ring A] : normed_ring (completion A) := { dist_eq := λ x y, begin apply completion.induction_on₂ x y; clear x y, { refine is_closed_eq (completion.uniform_continuous_extension₂ _).continuous _, exact continuous.comp completion.continuous_extension continuous_sub }, { intros x y, rw [← completion.coe_sub, norm_coe, completion.dist_eq, dist_eq_norm] } end, norm_mul := λ x y, begin apply completion.induction_on₂ x y; clear x y, { exact is_closed_le (continuous.comp (continuous_norm) continuous_mul) (continuous.comp real.continuous_mul (continuous.prod_map continuous_norm continuous_norm)) }, { intros x y, simp only [← coe_mul, norm_coe], exact norm_mul_le x y, } end, ..completion.ring, ..completion.metric_space } instance [semi_normed_comm_ring A] [normed_algebra 𝕜 A] [has_uniform_continuous_const_smul 𝕜 A] : normed_algebra 𝕜 (completion A) := { norm_smul_le := λ r x, begin apply completion.induction_on x; clear x, { exact is_closed_le (continuous.comp (continuous_norm) (continuous_const_smul r)) (continuous.comp (continuous_mul_left _) continuous_norm), }, { intros x, simp only [← coe_smul, norm_coe], exact normed_space.norm_smul_le r x } end, ..completion.algebra A 𝕜} end algebra end completion end uniform_space
aeab3439dbc871ed55ebb39f07a6384252df440a
7b9ff28673cd3dd7dd3dcfe2ab8449f9244fe05a
/src/rob/type_classes.lean
ebf5e8a26e1afff9be84815262ae49c432951cbb
[]
no_license
jesse-michael-han/hanoi-lean-2019
ea2f0e04f81093373c48447065765a964ee82262
a5a9f368e394d563bfcc13e3773863924505b1ce
refs/heads/master
1,591,320,223,247
1,561,022,886,000
1,561,022,886,000
192,264,820
1
1
null
null
null
null
UTF-8
Lean
false
false
2,478
lean
import topology.metric_space.basic namespace playground class my_add_semigroup (α : Type) := (add : α → α → α) (add_assoc' : ∀ a b c, add (add a b) c = add a (add b c)) (add_comm' : ∀ a b, add a b = add b a) section open my_add_semigroup theorem comm_assoc' {α : Type} [my_add_semigroup α] (a b c : α) : add (add a b) c = add c (add b a) := begin rw [add_comm' _ c, add_comm' b] end --set_option old_structure_cmd true class my_add_group (α : Type) extends my_add_semigroup α := (zero : α) (add_zero' : ∀ a, add a zero = a) #print my_add_group open my_add_group theorem zero_add' {α : Type} [my_add_group α] (a : α) : add (zero α) a = a := begin rw [add_comm', add_zero'] end instance : my_add_semigroup ℕ := { add := (+), add_assoc' := by intros; simp, add_comm' := by intros; simp } theorem nat_comm_assoc (a b c : ℕ) : (a + b) + c = c + (b + a) := comm_assoc' a b c set_option pp.all true #print nat_comm_assoc set_option pp.all false theorem new_thm {α : Type} [my_add_group α] (a : α) : add a a = a := sorry example (α : Type) [my_add_semigroup α] (a : α) : add a a = a := begin rw new_thm end end #check topological_space #check @continuous #check metric_space example (α : Type) [metric_space α] : continuous (λ x : α, x) := continuous_id class t1 (α : Type) := (val1 : α) class t2 (α : Type) := (val2 : ℕ) class t3 (α : Type) := (val3 : α) (val4 : ℕ) instance inst_t1_of_t3 (α : Type) [t3 α] : t1 α := { val1 := t3.val3 α } instance inst_t2_of_t3 (α : Type) [t3 α] : t2 α := { val2 := t3.val4 α } instance t3_int : t3 ℤ := { val3 := -1, val4 := 100 } #eval t1.val1 ℤ /- instance inst_t3_of_t1_t2 (α : Type) [t1 α] [t2 α] : t3 α := { val3 := t1.val1 α, val4 := t2.val2 α } -/ example (α : Type) [t1 α] [t2 α] : ℕ := t3.val4 α set_option trace.class_instances true example (α : Type) : ℕ := t3.val4 α set_option trace.class_instances false instance bad_instance (α β : Type) [has_add β] : t2 α := { val2 := 5 } set_option trace.class_instances true #check t2.val2 ℕ set_option trace.class_instances false end playground #check group #check comm_group #check ordered_comm_group #check ring #check field #check discrete_field #check fintype #check decidable_eq /- Exercise: Define a type class for your favorite kind of structure. Suggestions: monoids, groups, additive groups, rings, fields Define instances of your type class. -/
79276dca40cd8acff02b533a58e4be7fc8fb457a
5412d79aa1dc0b521605c38bef9f0d4557b5a29d
/stage0/src/Lean/Compiler/IR/Basic.lean
8b258f49b95bc960f98a92ebcafe91db326accd8
[ "Apache-2.0" ]
permissive
smunix/lean4
a450ec0927dc1c74816a1bf2818bf8600c9fc9bf
3407202436c141e3243eafbecb4b8720599b970a
refs/heads/master
1,676,334,875,188
1,610,128,510,000
1,610,128,521,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
25,751
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Data.KVMap import Lean.Data.Name import Lean.Data.Format import Lean.Compiler.ExternAttr /- Implements (extended) λPure and λRc proposed in the article "Counting Immutable Beans", Sebastian Ullrich and Leonardo de Moura. The Lean to IR transformation produces λPure code, and this part is implemented in C++. The procedures described in the paper above are implemented in Lean. -/ namespace Lean.IR /- Function identifier -/ abbrev FunId := Name abbrev Index := Nat /- Variable identifier -/ structure VarId where idx : Index deriving Inhabited /- Join point identifier -/ structure JoinPointId where idx : Index deriving Inhabited abbrev Index.lt (a b : Index) : Bool := a < b instance : BEq VarId := ⟨fun a b => a.idx == b.idx⟩ instance : ToString VarId := ⟨fun a => "x_" ++ toString a.idx⟩ instance : ToFormat VarId := ⟨fun a => toString a⟩ instance : Hashable VarId := ⟨fun a => hash a.idx⟩ instance : BEq JoinPointId := ⟨fun a b => a.idx == b.idx⟩ instance : ToString JoinPointId := ⟨fun a => "block_" ++ toString a.idx⟩ instance : ToFormat JoinPointId := ⟨fun a => toString a⟩ instance : Hashable JoinPointId := ⟨fun a => hash a.idx⟩ abbrev MData := KVMap abbrev MData.empty : MData := {} /- Low Level IR types. Most are self explanatory. - `usize` represents the C++ `size_t` Type. We have it here because it is 32-bit in 32-bit machines, and 64-bit in 64-bit machines, and we want the C++ backend for our Compiler to generate platform independent code. - `irrelevant` for Lean types, propositions and proofs. - `object` a pointer to a value in the heap. - `tobject` a pointer to a value in the heap or tagged pointer (i.e., the least significant bit is 1) storing a scalar value. - `struct` and `union` are used to return small values (e.g., `Option`, `Prod`, `Except`) on the stack. Remark: the RC operations for `tobject` are slightly more expensive because we first need to test whether the `tobject` is really a pointer or not. Remark: the Lean runtime assumes that sizeof(void*) == sizeof(sizeT). Lean cannot be compiled on old platforms where this is not True. Since values of type `struct` and `union` are only used to return values, We assume they must be used/consumed "linearly". We use the term "linear" here to mean "exactly once" in each execution. That is, given `x : S`, where `S` is a struct, then one of the following must hold in each (execution) branch. 1- `x` occurs only at a single `ret x` instruction. That is, it is being consumed by being returned. 2- `x` occurs only at a single `ctor`. That is, it is being "consumed" by being stored into another `struct/union`. 3- We extract (aka project) every single field of `x` exactly once. That is, we are consuming `x` by consuming each of one of its components. Minor refinement: we don't need to consume scalar fields or struct/union fields that do not contain object fields. -/ inductive IRType where | float | uint8 | uint16 | uint32 | uint64 | usize | irrelevant | object | tobject | struct (leanTypeName : Option Name) (types : Array IRType) : IRType | union (leanTypeName : Name) (types : Array IRType) : IRType deriving Inhabited namespace IRType partial def beq : IRType → IRType → Bool | float, float => true | uint8, uint8 => true | uint16, uint16 => true | uint32, uint32 => true | uint64, uint64 => true | usize, usize => true | irrelevant, irrelevant => true | object, object => true | tobject, tobject => true | struct n₁ tys₁, struct n₂ tys₂ => n₁ == n₂ && Array.isEqv tys₁ tys₂ beq | union n₁ tys₁, union n₂ tys₂ => n₁ == n₂ && Array.isEqv tys₁ tys₂ beq | _, _ => false instance : BEq IRType := ⟨beq⟩ def isScalar : IRType → Bool | float => true | uint8 => true | uint16 => true | uint32 => true | uint64 => true | usize => true | _ => false def isObj : IRType → Bool | object => true | tobject => true | _ => false def isIrrelevant : IRType → Bool | irrelevant => true | _ => false def isStruct : IRType → Bool | struct _ _ => true | _ => false def isUnion : IRType → Bool | union _ _ => true | _ => false end IRType /- Arguments to applications, constructors, etc. We use `irrelevant` for Lean types, propositions and proofs that have been erased. Recall that for a Function `f`, we also generate `f._rarg` which does not take `irrelevant` arguments. However, `f._rarg` is only safe to be used in full applications. -/ inductive Arg where | var (id : VarId) | irrelevant deriving Inhabited protected def Arg.beq : Arg → Arg → Bool | var x, var y => x == y | irrelevant, irrelevant => true | _, _ => false instance : BEq Arg := ⟨Arg.beq⟩ @[export lean_ir_mk_var_arg] def mkVarArg (id : VarId) : Arg := Arg.var id inductive LitVal where | num (v : Nat) | str (v : String) def LitVal.beq : LitVal → LitVal → Bool | num v₁, num v₂ => v₁ == v₂ | str v₁, str v₂ => v₁ == v₂ | _, _ => false instance : BEq LitVal := ⟨LitVal.beq⟩ /- Constructor information. - `name` is the Name of the Constructor in Lean. - `cidx` is the Constructor index (aka tag). - `size` is the number of arguments of type `object/tobject`. - `usize` is the number of arguments of type `usize`. - `ssize` is the number of bytes used to store scalar values. Recall that a Constructor object contains a header, then a sequence of pointers to other Lean objects, a sequence of `USize` (i.e., `size_t`) scalar values, and a sequence of other scalar values. -/ structure CtorInfo where name : Name cidx : Nat size : Nat usize : Nat ssize : Nat def CtorInfo.beq : CtorInfo → CtorInfo → Bool | ⟨n₁, cidx₁, size₁, usize₁, ssize₁⟩, ⟨n₂, cidx₂, size₂, usize₂, ssize₂⟩ => n₁ == n₂ && cidx₁ == cidx₂ && size₁ == size₂ && usize₁ == usize₂ && ssize₁ == ssize₂ instance : BEq CtorInfo := ⟨CtorInfo.beq⟩ def CtorInfo.isRef (info : CtorInfo) : Bool := info.size > 0 || info.usize > 0 || info.ssize > 0 def CtorInfo.isScalar (info : CtorInfo) : Bool := !info.isRef inductive Expr where /- We use `ctor` mainly for constructing Lean object/tobject values `lean_ctor_object` in the runtime. This instruction is also used to creat `struct` and `union` return values. For `union`, only `i.cidx` is relevant. For `struct`, `i` is irrelevant. -/ | ctor (i : CtorInfo) (ys : Array Arg) | reset (n : Nat) (x : VarId) /- `reuse x in ctor_i ys` instruction in the paper. -/ | reuse (x : VarId) (i : CtorInfo) (updtHeader : Bool) (ys : Array Arg) /- Extract the `tobject` value at Position `sizeof(void*)*i` from `x`. We also use `proj` for extracting fields from `struct` return values, and casting `union` return values. -/ | proj (i : Nat) (x : VarId) /- Extract the `Usize` value at Position `sizeof(void*)*i` from `x`. -/ | uproj (i : Nat) (x : VarId) /- Extract the scalar value at Position `sizeof(void*)*n + offset` from `x`. -/ | sproj (n : Nat) (offset : Nat) (x : VarId) /- Full application. -/ | fap (c : FunId) (ys : Array Arg) /- Partial application that creates a `pap` value (aka closure in our nonstandard terminology). -/ | pap (c : FunId) (ys : Array Arg) /- Application. `x` must be a `pap` value. -/ | ap (x : VarId) (ys : Array Arg) /- Given `x : ty` where `ty` is a scalar type, this operation returns a value of Type `tobject`. For small scalar values, the Result is a tagged pointer, and no memory allocation is performed. -/ | box (ty : IRType) (x : VarId) /- Given `x : [t]object`, obtain the scalar value. -/ | unbox (x : VarId) | lit (v : LitVal) /- Return `1 : uint8` Iff `RC(x) > 1` -/ | isShared (x : VarId) /- Return `1 : uint8` Iff `x : tobject` is a tagged pointer (storing a scalar value). -/ | isTaggedPtr (x : VarId) @[export lean_ir_mk_ctor_expr] def mkCtorExpr (n : Name) (cidx : Nat) (size : Nat) (usize : Nat) (ssize : Nat) (ys : Array Arg) : Expr := Expr.ctor ⟨n, cidx, size, usize, ssize⟩ ys @[export lean_ir_mk_proj_expr] def mkProjExpr (i : Nat) (x : VarId) : Expr := Expr.proj i x @[export lean_ir_mk_uproj_expr] def mkUProjExpr (i : Nat) (x : VarId) : Expr := Expr.uproj i x @[export lean_ir_mk_sproj_expr] def mkSProjExpr (n : Nat) (offset : Nat) (x : VarId) : Expr := Expr.sproj n offset x @[export lean_ir_mk_fapp_expr] def mkFAppExpr (c : FunId) (ys : Array Arg) : Expr := Expr.fap c ys @[export lean_ir_mk_papp_expr] def mkPAppExpr (c : FunId) (ys : Array Arg) : Expr := Expr.pap c ys @[export lean_ir_mk_app_expr] def mkAppExpr (x : VarId) (ys : Array Arg) : Expr := Expr.ap x ys @[export lean_ir_mk_num_expr] def mkNumExpr (v : Nat) : Expr := Expr.lit (LitVal.num v) @[export lean_ir_mk_str_expr] def mkStrExpr (v : String) : Expr := Expr.lit (LitVal.str v) structure Param where x : VarId borrow : Bool ty : IRType deriving Inhabited @[export lean_ir_mk_param] def mkParam (x : VarId) (borrow : Bool) (ty : IRType) : Param := ⟨x, borrow, ty⟩ inductive AltCore (FnBody : Type) : Type where | ctor (info : CtorInfo) (b : FnBody) : AltCore FnBody | default (b : FnBody) : AltCore FnBody inductive FnBody where /- `let x : ty := e; b` -/ | vdecl (x : VarId) (ty : IRType) (e : Expr) (b : FnBody) /- Join point Declaration `block_j (xs) := e; b` -/ | jdecl (j : JoinPointId) (xs : Array Param) (v : FnBody) (b : FnBody) /- Store `y` at Position `sizeof(void*)*i` in `x`. `x` must be a Constructor object and `RC(x)` must be 1. This operation is not part of λPure is only used during optimization. -/ | set (x : VarId) (i : Nat) (y : Arg) (b : FnBody) | setTag (x : VarId) (cidx : Nat) (b : FnBody) /- Store `y : Usize` at Position `sizeof(void*)*i` in `x`. `x` must be a Constructor object and `RC(x)` must be 1. -/ | uset (x : VarId) (i : Nat) (y : VarId) (b : FnBody) /- Store `y : ty` at Position `sizeof(void*)*i + offset` in `x`. `x` must be a Constructor object and `RC(x)` must be 1. `ty` must not be `object`, `tobject`, `irrelevant` nor `Usize`. -/ | sset (x : VarId) (i : Nat) (offset : Nat) (y : VarId) (ty : IRType) (b : FnBody) /- RC increment for `object`. If c == `true`, then `inc` must check whether `x` is a tagged pointer or not. If `persistent == true` then `x` is statically known to be a persistent object. -/ | inc (x : VarId) (n : Nat) (c : Bool) (persistent : Bool) (b : FnBody) /- RC decrement for `object`. If c == `true`, then `inc` must check whether `x` is a tagged pointer or not. If `persistent == true` then `x` is statically known to be a persistent object. -/ | dec (x : VarId) (n : Nat) (c : Bool) (persistent : Bool) (b : FnBody) | del (x : VarId) (b : FnBody) | mdata (d : MData) (b : FnBody) | case (tid : Name) (x : VarId) (xType : IRType) (cs : Array (AltCore FnBody)) | ret (x : Arg) /- Jump to join point `j` -/ | jmp (j : JoinPointId) (ys : Array Arg) | unreachable instance : Inhabited FnBody := ⟨FnBody.unreachable⟩ abbrev FnBody.nil := FnBody.unreachable @[export lean_ir_mk_vdecl] def mkVDecl (x : VarId) (ty : IRType) (e : Expr) (b : FnBody) : FnBody := FnBody.vdecl x ty e b @[export lean_ir_mk_jdecl] def mkJDecl (j : JoinPointId) (xs : Array Param) (v : FnBody) (b : FnBody) : FnBody := FnBody.jdecl j xs v b @[export lean_ir_mk_uset] def mkUSet (x : VarId) (i : Nat) (y : VarId) (b : FnBody) : FnBody := FnBody.uset x i y b @[export lean_ir_mk_sset] def mkSSet (x : VarId) (i : Nat) (offset : Nat) (y : VarId) (ty : IRType) (b : FnBody) : FnBody := FnBody.sset x i offset y ty b @[export lean_ir_mk_case] def mkCase (tid : Name) (x : VarId) (cs : Array (AltCore FnBody)) : FnBody := -- Tyhe field `xType` is set by `explicitBoxing` compiler pass. FnBody.case tid x IRType.object cs @[export lean_ir_mk_ret] def mkRet (x : Arg) : FnBody := FnBody.ret x @[export lean_ir_mk_jmp] def mkJmp (j : JoinPointId) (ys : Array Arg) : FnBody := FnBody.jmp j ys @[export lean_ir_mk_unreachable] def mkUnreachable : Unit → FnBody := fun _ => FnBody.unreachable abbrev Alt := AltCore FnBody @[matchPattern] abbrev Alt.ctor := @AltCore.ctor FnBody @[matchPattern] abbrev Alt.default := @AltCore.default FnBody instance : Inhabited Alt := ⟨Alt.default arbitrary⟩ def FnBody.isTerminal : FnBody → Bool | FnBody.case _ _ _ _ => true | FnBody.ret _ => true | FnBody.jmp _ _ => true | FnBody.unreachable => true | _ => false def FnBody.body : FnBody → FnBody | FnBody.vdecl _ _ _ b => b | FnBody.jdecl _ _ _ b => b | FnBody.set _ _ _ b => b | FnBody.uset _ _ _ b => b | FnBody.sset _ _ _ _ _ b => b | FnBody.setTag _ _ b => b | FnBody.inc _ _ _ _ b => b | FnBody.dec _ _ _ _ b => b | FnBody.del _ b => b | FnBody.mdata _ b => b | other => other def FnBody.setBody : FnBody → FnBody → FnBody | FnBody.vdecl x t v _, b => FnBody.vdecl x t v b | FnBody.jdecl j xs v _, b => FnBody.jdecl j xs v b | FnBody.set x i y _, b => FnBody.set x i y b | FnBody.uset x i y _, b => FnBody.uset x i y b | FnBody.sset x i o y t _, b => FnBody.sset x i o y t b | FnBody.setTag x i _, b => FnBody.setTag x i b | FnBody.inc x n c p _, b => FnBody.inc x n c p b | FnBody.dec x n c p _, b => FnBody.dec x n c p b | FnBody.del x _, b => FnBody.del x b | FnBody.mdata d _, b => FnBody.mdata d b | other, b => other @[inline] def FnBody.resetBody (b : FnBody) : FnBody := b.setBody FnBody.nil /- If b is a non terminal, then return a pair `(c, b')` s.t. `b == c <;> b'`, and c.body == FnBody.nil -/ @[inline] def FnBody.split (b : FnBody) : FnBody × FnBody := let b' := b.body let c := b.resetBody (c, b') def AltCore.body : Alt → FnBody | Alt.ctor _ b => b | Alt.default b => b def AltCore.setBody : Alt → FnBody → Alt | Alt.ctor c _, b => Alt.ctor c b | Alt.default _, b => Alt.default b @[inline] def AltCore.modifyBody (f : FnBody → FnBody) : AltCore FnBody → Alt | Alt.ctor c b => Alt.ctor c (f b) | Alt.default b => Alt.default (f b) @[inline] def AltCore.mmodifyBody {m : Type → Type} [Monad m] (f : FnBody → m FnBody) : AltCore FnBody → m Alt | Alt.ctor c b => Alt.ctor c <$> f b | Alt.default b => Alt.default <$> f b def Alt.isDefault : Alt → Bool | Alt.ctor _ _ => false | Alt.default _ => true def push (bs : Array FnBody) (b : FnBody) : Array FnBody := let b := b.resetBody bs.push b partial def flattenAux (b : FnBody) (r : Array FnBody) : (Array FnBody) × FnBody := if b.isTerminal then (r, b) else flattenAux b.body (push r b) def FnBody.flatten (b : FnBody) : (Array FnBody) × FnBody := flattenAux b #[] partial def reshapeAux (a : Array FnBody) (i : Nat) (b : FnBody) : FnBody := if i == 0 then b else let i := i - 1 let (curr, a) := a.swapAt! i arbitrary let b := curr.setBody b reshapeAux a i b def reshape (bs : Array FnBody) (term : FnBody) : FnBody := reshapeAux bs bs.size term @[inline] def modifyJPs (bs : Array FnBody) (f : FnBody → FnBody) : Array FnBody := bs.map fun b => match b with | FnBody.jdecl j xs v k => FnBody.jdecl j xs (f v) k | other => other @[inline] def mmodifyJPs {m : Type → Type} [Monad m] (bs : Array FnBody) (f : FnBody → m FnBody) : m (Array FnBody) := bs.mapM fun b => match b with | FnBody.jdecl j xs v k => do let v ← f v; pure $ FnBody.jdecl j xs v k | other => pure other @[export lean_ir_mk_alt] def mkAlt (n : Name) (cidx : Nat) (size : Nat) (usize : Nat) (ssize : Nat) (b : FnBody) : Alt := Alt.ctor ⟨n, cidx, size, usize, ssize⟩ b inductive Decl where | fdecl (f : FunId) (xs : Array Param) (ty : IRType) (b : FnBody) | extern (f : FunId) (xs : Array Param) (ty : IRType) (ext : ExternAttrData) namespace Decl instance : Inhabited Decl := ⟨fdecl arbitrary arbitrary IRType.irrelevant arbitrary⟩ def name : Decl → FunId | Decl.fdecl f _ _ _ => f | Decl.extern f _ _ _ => f def params : Decl → Array Param | Decl.fdecl _ xs _ _ => xs | Decl.extern _ xs _ _ => xs def resultType : Decl → IRType | Decl.fdecl _ _ t _ => t | Decl.extern _ _ t _ => t def isExtern : Decl → Bool | Decl.extern _ _ _ _ => true | _ => false end Decl @[export lean_ir_mk_decl] def mkDecl (f : FunId) (xs : Array Param) (ty : IRType) (b : FnBody) : Decl := Decl.fdecl f xs ty b @[export lean_ir_mk_extern_decl] def mkExternDecl (f : FunId) (xs : Array Param) (ty : IRType) (e : ExternAttrData) : Decl := Decl.extern f xs ty e open Std (RBTree RBTree.empty RBMap) /-- Set of variable and join point names -/ abbrev IndexSet := RBTree Index Index.lt instance : Inhabited IndexSet := ⟨{}⟩ def mkIndexSet (idx : Index) : IndexSet := RBTree.empty.insert idx inductive LocalContextEntry where | param : IRType → LocalContextEntry | localVar : IRType → Expr → LocalContextEntry | joinPoint : Array Param → FnBody → LocalContextEntry abbrev LocalContext := RBMap Index LocalContextEntry Index.lt def LocalContext.addLocal (ctx : LocalContext) (x : VarId) (t : IRType) (v : Expr) : LocalContext := ctx.insert x.idx (LocalContextEntry.localVar t v) def LocalContext.addJP (ctx : LocalContext) (j : JoinPointId) (xs : Array Param) (b : FnBody) : LocalContext := ctx.insert j.idx (LocalContextEntry.joinPoint xs b) def LocalContext.addParam (ctx : LocalContext) (p : Param) : LocalContext := ctx.insert p.x.idx (LocalContextEntry.param p.ty) def LocalContext.addParams (ctx : LocalContext) (ps : Array Param) : LocalContext := ps.foldl LocalContext.addParam ctx def LocalContext.isJP (ctx : LocalContext) (idx : Index) : Bool := match ctx.find? idx with | some (LocalContextEntry.joinPoint _ _) => true | other => false def LocalContext.getJPBody (ctx : LocalContext) (j : JoinPointId) : Option FnBody := match ctx.find? j.idx with | some (LocalContextEntry.joinPoint _ b) => some b | other => none def LocalContext.getJPParams (ctx : LocalContext) (j : JoinPointId) : Option (Array Param) := match ctx.find? j.idx with | some (LocalContextEntry.joinPoint ys _) => some ys | other => none def LocalContext.isParam (ctx : LocalContext) (idx : Index) : Bool := match ctx.find? idx with | some (LocalContextEntry.param _) => true | other => false def LocalContext.isLocalVar (ctx : LocalContext) (idx : Index) : Bool := match ctx.find? idx with | some (LocalContextEntry.localVar _ _) => true | other => false def LocalContext.contains (ctx : LocalContext) (idx : Index) : Bool := Std.RBMap.contains ctx idx def LocalContext.eraseJoinPointDecl (ctx : LocalContext) (j : JoinPointId) : LocalContext := ctx.erase j.idx def LocalContext.getType (ctx : LocalContext) (x : VarId) : Option IRType := match ctx.find? x.idx with | some (LocalContextEntry.param t) => some t | some (LocalContextEntry.localVar t _) => some t | other => none def LocalContext.getValue (ctx : LocalContext) (x : VarId) : Option Expr := match ctx.find? x.idx with | some (LocalContextEntry.localVar _ v) => some v | other => none abbrev IndexRenaming := RBMap Index Index Index.lt class AlphaEqv (α : Type) where aeqv : IndexRenaming → α → α → Bool export AlphaEqv (aeqv) def VarId.alphaEqv (ρ : IndexRenaming) (v₁ v₂ : VarId) : Bool := match ρ.find? v₁.idx with | some v => v == v₂.idx | none => v₁ == v₂ instance : AlphaEqv VarId := ⟨VarId.alphaEqv⟩ def Arg.alphaEqv (ρ : IndexRenaming) : Arg → Arg → Bool | Arg.var v₁, Arg.var v₂ => aeqv ρ v₁ v₂ | Arg.irrelevant, Arg.irrelevant => true | _, _ => false instance : AlphaEqv Arg := ⟨Arg.alphaEqv⟩ def args.alphaEqv (ρ : IndexRenaming) (args₁ args₂ : Array Arg) : Bool := Array.isEqv args₁ args₂ (fun a b => aeqv ρ a b) instance: AlphaEqv (Array Arg) := ⟨args.alphaEqv⟩ def Expr.alphaEqv (ρ : IndexRenaming) : Expr → Expr → Bool | Expr.ctor i₁ ys₁, Expr.ctor i₂ ys₂ => i₁ == i₂ && aeqv ρ ys₁ ys₂ | Expr.reset n₁ x₁, Expr.reset n₂ x₂ => n₁ == n₂ && aeqv ρ x₁ x₂ | Expr.reuse x₁ i₁ u₁ ys₁, Expr.reuse x₂ i₂ u₂ ys₂ => aeqv ρ x₁ x₂ && i₁ == i₂ && u₁ == u₂ && aeqv ρ ys₁ ys₂ | Expr.proj i₁ x₁, Expr.proj i₂ x₂ => i₁ == i₂ && aeqv ρ x₁ x₂ | Expr.uproj i₁ x₁, Expr.uproj i₂ x₂ => i₁ == i₂ && aeqv ρ x₁ x₂ | Expr.sproj n₁ o₁ x₁, Expr.sproj n₂ o₂ x₂ => n₁ == n₂ && o₁ == o₂ && aeqv ρ x₁ x₂ | Expr.fap c₁ ys₁, Expr.fap c₂ ys₂ => c₁ == c₂ && aeqv ρ ys₁ ys₂ | Expr.pap c₁ ys₁, Expr.pap c₂ ys₂ => c₁ == c₂ && aeqv ρ ys₁ ys₂ | Expr.ap x₁ ys₁, Expr.ap x₂ ys₂ => aeqv ρ x₁ x₂ && aeqv ρ ys₁ ys₂ | Expr.box ty₁ x₁, Expr.box ty₂ x₂ => ty₁ == ty₂ && aeqv ρ x₁ x₂ | Expr.unbox x₁, Expr.unbox x₂ => aeqv ρ x₁ x₂ | Expr.lit v₁, Expr.lit v₂ => v₁ == v₂ | Expr.isShared x₁, Expr.isShared x₂ => aeqv ρ x₁ x₂ | Expr.isTaggedPtr x₁, Expr.isTaggedPtr x₂ => aeqv ρ x₁ x₂ | _, _ => false instance : AlphaEqv Expr:= ⟨Expr.alphaEqv⟩ def addVarRename (ρ : IndexRenaming) (x₁ x₂ : Nat) := if x₁ == x₂ then ρ else ρ.insert x₁ x₂ def addParamRename (ρ : IndexRenaming) (p₁ p₂ : Param) : Option IndexRenaming := if p₁.ty == p₂.ty && p₁.borrow = p₂.borrow then some (addVarRename ρ p₁.x.idx p₂.x.idx) else none def addParamsRename (ρ : IndexRenaming) (ps₁ ps₂ : Array Param) : Option IndexRenaming := do if ps₁.size != ps₂.size then none else let mut ρ := ρ for i in [:ps₁.size] do ρ ← addParamRename ρ ps₁[i] ps₂[i] pure ρ partial def FnBody.alphaEqv : IndexRenaming → FnBody → FnBody → Bool | ρ, FnBody.vdecl x₁ t₁ v₁ b₁, FnBody.vdecl x₂ t₂ v₂ b₂ => t₁ == t₂ && aeqv ρ v₁ v₂ && alphaEqv (addVarRename ρ x₁.idx x₂.idx) b₁ b₂ | ρ, FnBody.jdecl j₁ ys₁ v₁ b₁, FnBody.jdecl j₂ ys₂ v₂ b₂ => match addParamsRename ρ ys₁ ys₂ with | some ρ' => alphaEqv ρ' v₁ v₂ && alphaEqv (addVarRename ρ j₁.idx j₂.idx) b₁ b₂ | none => false | ρ, FnBody.set x₁ i₁ y₁ b₁, FnBody.set x₂ i₂ y₂ b₂ => aeqv ρ x₁ x₂ && i₁ == i₂ && aeqv ρ y₁ y₂ && alphaEqv ρ b₁ b₂ | ρ, FnBody.uset x₁ i₁ y₁ b₁, FnBody.uset x₂ i₂ y₂ b₂ => aeqv ρ x₁ x₂ && i₁ == i₂ && aeqv ρ y₁ y₂ && alphaEqv ρ b₁ b₂ | ρ, FnBody.sset x₁ i₁ o₁ y₁ t₁ b₁, FnBody.sset x₂ i₂ o₂ y₂ t₂ b₂ => aeqv ρ x₁ x₂ && i₁ = i₂ && o₁ = o₂ && aeqv ρ y₁ y₂ && t₁ == t₂ && alphaEqv ρ b₁ b₂ | ρ, FnBody.setTag x₁ i₁ b₁, FnBody.setTag x₂ i₂ b₂ => aeqv ρ x₁ x₂ && i₁ == i₂ && alphaEqv ρ b₁ b₂ | ρ, FnBody.inc x₁ n₁ c₁ p₁ b₁, FnBody.inc x₂ n₂ c₂ p₂ b₂ => aeqv ρ x₁ x₂ && n₁ == n₂ && c₁ == c₂ && p₁ == p₂ && alphaEqv ρ b₁ b₂ | ρ, FnBody.dec x₁ n₁ c₁ p₁ b₁, FnBody.dec x₂ n₂ c₂ p₂ b₂ => aeqv ρ x₁ x₂ && n₁ == n₂ && c₁ == c₂ && p₁ == p₂ && alphaEqv ρ b₁ b₂ | ρ, FnBody.del x₁ b₁, FnBody.del x₂ b₂ => aeqv ρ x₁ x₂ && alphaEqv ρ b₁ b₂ | ρ, FnBody.mdata m₁ b₁, FnBody.mdata m₂ b₂ => m₁ == m₂ && alphaEqv ρ b₁ b₂ | ρ, FnBody.case n₁ x₁ _ alts₁, FnBody.case n₂ x₂ _ alts₂ => n₁ == n₂ && aeqv ρ x₁ x₂ && Array.isEqv alts₁ alts₂ (fun alt₁ alt₂ => match alt₁, alt₂ with | Alt.ctor i₁ b₁, Alt.ctor i₂ b₂ => i₁ == i₂ && alphaEqv ρ b₁ b₂ | Alt.default b₁, Alt.default b₂ => alphaEqv ρ b₁ b₂ | _, _ => false) | ρ, FnBody.jmp j₁ ys₁, FnBody.jmp j₂ ys₂ => j₁ == j₂ && aeqv ρ ys₁ ys₂ | ρ, FnBody.ret x₁, FnBody.ret x₂ => aeqv ρ x₁ x₂ | _, FnBody.unreachable, FnBody.unreachable => true | _, _, _ => false def FnBody.beq (b₁ b₂ : FnBody) : Bool := FnBody.alphaEqv ∅ b₁ b₂ instance : BEq FnBody := ⟨FnBody.beq⟩ abbrev VarIdSet := RBTree VarId (fun x y => x.idx < y.idx) instance : Inhabited VarIdSet := ⟨{}⟩ def mkIf (x : VarId) (t e : FnBody) : FnBody := FnBody.case `Bool x IRType.uint8 #[ Alt.ctor {name := `Bool.false, cidx := 0, size := 0, usize := 0, ssize := 0} e, Alt.ctor {name := `Bool.true, cidx := 1, size := 0, usize := 0, ssize := 0} t ] end Lean.IR
e2880a3fc207cba5fe5734130d860ee8798d321b
acc85b4be2c618b11fc7cb3005521ae6858a8d07
/data/set/finite.lean
c307125247ed25f003e400f735c5e46a24c9a2c6
[ "Apache-2.0" ]
permissive
linpingchuan/mathlib
d49990b236574df2a45d9919ba43c923f693d341
5ad8020f67eb13896a41cc7691d072c9331b1f76
refs/heads/master
1,626,019,377,808
1,508,048,784,000
1,508,048,784,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,833
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 Finite sets -- assuming a classical logic. -/ import data.set.lattice data.set.prod data.nat.basic noncomputable theory universes u v w variables {α : Type u} {β : Type v} {ι : Sort w} open set lattice namespace set /- local attribute [instance] classical.decidable_inhabited classical.prop_decidable -/ inductive finite : set α → Prop | empty : finite ∅ | insert : ∀a s, a ∉ s → finite s → finite (insert a s) def infinite (s : set α) : Prop := ¬ finite s attribute [simp] finite.empty @[simp] theorem finite_insert {a : α} {s : set α} (h : finite s) : finite (insert a s) := classical.by_cases (assume : a ∈ s, by simp [*]) (assume : a ∉ s, finite.insert a s this h) @[simp] theorem finite_singleton {a : α} : finite ({a} : set α) := finite_insert finite.empty theorem finite_union {s t : set α} (hs : finite s) (ht : finite t) : finite (s ∪ t) := finite.drec_on ht (by simp [hs]) $ assume a t _ _, by simp; exact finite_insert theorem finite_subset {s : set α} (hs : finite s) : ∀{t}, t ⊆ s → finite t := begin induction hs with a t' ha ht' ih, { intros t ht, simp [(subset_empty_iff t).mp ht, finite.empty] }, { intros t ht, have tm : finite (t \ {a}) := (ih $ show t \ {a} ⊆ t', from assume x ⟨hxt, hna⟩, or.resolve_left (ht hxt) (by simp at hna; assumption)), cases (classical.em $ a ∈ t) with ha hna, { exact have finite (insert a (t \ {a})), from finite_insert tm, show finite t, by simp [ha] at this; assumption }, { simp [sdiff_singleton_eq_same, hna] at tm, exact tm } } end theorem finite_image {s : set α} {f : α → β} (h : finite s) : finite (f '' s) := begin induction h with a s' hns' hs' hi, simp [image_empty, finite.empty], simp [image_insert_eq, finite_insert, hi] end theorem finite_sUnion {s : set (set α)} (h : finite s) : (∀t∈s, finite t) → finite (⋃₀ s) := begin induction h with a s' hns' hs' hi, { simp [finite.empty] }, { intro h, simp, apply finite_union, { apply h, simp }, { exact (hi $ assume t ht, h _ $ mem_insert_of_mem _ ht) } } end lemma finite_le_nat : ∀{n:ℕ}, finite {i | i ≤ n} | 0 := by simp [nat.le_zero_iff, set_compr_eq_eq_singleton] | (n + 1) := have insert (n + 1) {i | i ≤ n} = {i | i ≤ n + 1}, from set.ext $ by simp [nat.le_add_one_iff], this ▸ finite_insert finite_le_nat lemma finite_prod {s : set α} {t : set β} (hs : finite s) (ht : finite t) : finite (set.prod s t) := begin induction hs, case finite.empty { simp }, case finite.insert a s has hs ih { rw [set.insert_prod], exact finite_union (finite_image ht) ih } end end set